645f74568006cc958cd35f7fe889d4eaa6aef426
[sbcl.git] / src / compiler / x86-64 / call.lisp
1 ;;;; function call for the x86 VM
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!VM")
13 \f
14 ;;;; interfaces to IR2 conversion
15
16 ;;; Return a wired TN describing the N'th full call argument passing
17 ;;; location.
18 (defun standard-arg-location (n)
19   (declare (type unsigned-byte n))
20   (if (< n register-arg-count)
21       (make-wired-tn *backend-t-primitive-type* descriptor-reg-sc-number
22                      (nth n *register-arg-offsets*))
23       (make-wired-tn *backend-t-primitive-type* control-stack-sc-number n)))
24
25 ;;; Make a passing location TN for a local call return PC.
26 ;;;
27 ;;; Always wire the return PC location to the stack in its standard
28 ;;; location.
29 (defun make-return-pc-passing-location (standard)
30   (declare (ignore standard))
31   (make-wired-tn (primitive-type-or-lose 'system-area-pointer)
32                  sap-stack-sc-number return-pc-save-offset))
33
34 ;;; This is similar to MAKE-RETURN-PC-PASSING-LOCATION, but makes a
35 ;;; location to pass OLD-FP in.
36 ;;;
37 ;;; This is wired in both the standard and the local-call conventions,
38 ;;; because we want to be able to assume it's always there. Besides,
39 ;;; the x86 doesn't have enough registers to really make it profitable
40 ;;; to pass it in a register.
41 (defun make-old-fp-passing-location (standard)
42   (declare (ignore standard))
43   (make-wired-tn *fixnum-primitive-type* control-stack-sc-number
44                  ocfp-save-offset))
45
46 ;;; Make the TNs used to hold OLD-FP and RETURN-PC within the current
47 ;;; function. We treat these specially so that the debugger can find
48 ;;; them at a known location.
49 ;;;
50 ;;; Without using a save-tn - which does not make much sense if it is
51 ;;; wired to the stack?
52 (defun make-old-fp-save-location (physenv)
53   (physenv-debug-live-tn (make-wired-tn *fixnum-primitive-type*
54                                         control-stack-sc-number
55                                         ocfp-save-offset)
56                          physenv))
57 (defun make-return-pc-save-location (physenv)
58   (physenv-debug-live-tn
59    (make-wired-tn (primitive-type-or-lose 'system-area-pointer)
60                   sap-stack-sc-number return-pc-save-offset)
61    physenv))
62
63 ;;; Make a TN for the standard argument count passing location. We only
64 ;;; need to make the standard location, since a count is never passed when we
65 ;;; are using non-standard conventions.
66 (defun make-arg-count-location ()
67   (make-wired-tn *fixnum-primitive-type* any-reg-sc-number rcx-offset))
68
69 ;;; Make a TN to hold the number-stack frame pointer. This is allocated
70 ;;; once per component, and is component-live.
71 (defun make-nfp-tn ()
72   (make-restricted-tn *fixnum-primitive-type* ignore-me-sc-number))
73
74 (defun make-stack-pointer-tn ()
75   (make-normal-tn *fixnum-primitive-type*))
76
77 (defun make-number-stack-pointer-tn ()
78   (make-restricted-tn *fixnum-primitive-type* ignore-me-sc-number))
79
80 ;;; Return a list of TNs that can be used to represent an unknown-values
81 ;;; continuation within a function.
82 (defun make-unknown-values-locations ()
83   (list (make-stack-pointer-tn)
84         (make-normal-tn *fixnum-primitive-type*)))
85
86 ;;; This function is called by the ENTRY-ANALYZE phase, allowing
87 ;;; VM-dependent initialization of the IR2-COMPONENT structure. We
88 ;;; push placeholder entries in the CONSTANTS to leave room for
89 ;;; additional noise in the code object header.
90 (defun select-component-format (component)
91   (declare (type component component))
92   (dotimes (i code-constants-offset)
93     (vector-push-extend nil
94                         (ir2-component-constants (component-info component))))
95   (values))
96 \f
97 ;;;; frame hackery
98
99 ;;; This is used for setting up the Old-FP in local call.
100 (define-vop (current-fp)
101   (:results (val :scs (any-reg control-stack)))
102   (:generator 1
103     (move val rbp-tn)))
104
105 ;;; We don't have a separate NFP, so we don't need to do anything here.
106 (define-vop (compute-old-nfp)
107   (:results (val))
108   (:ignore val)
109   (:generator 1
110     nil))
111
112 ;;; Accessing a slot from an earlier stack frame is definite hackery.
113 (define-vop (ancestor-frame-ref)
114   (:args (frame-pointer :scs (descriptor-reg))
115          (variable-home-tn :load-if nil))
116   (:results (value :scs (descriptor-reg any-reg)))
117   (:policy :fast-safe)
118   (:generator 4
119     (aver (sc-is variable-home-tn control-stack))
120     (loadw value frame-pointer
121            (frame-word-offset (tn-offset variable-home-tn)))))
122 (define-vop (ancestor-frame-set)
123   (:args (frame-pointer :scs (descriptor-reg))
124          (value :scs (descriptor-reg any-reg)))
125   (:results (variable-home-tn :load-if nil))
126   (:policy :fast-safe)
127   (:generator 4
128     (aver (sc-is variable-home-tn control-stack))
129     (storew value frame-pointer
130             (frame-word-offset (tn-offset variable-home-tn)))))
131
132 (macrolet ((define-frame-op
133                (suffix sc stack-sc instruction
134                 &optional (ea
135                            `(make-ea :qword
136                                      :base frame-pointer
137                                      :disp (frame-byte-offset
138                                             (tn-offset variable-home-tn)))))
139                (let ((reffer (symbolicate 'ancestor-frame-ref '/ suffix))
140                      (setter (symbolicate 'ancestor-frame-set '/ suffix)))
141                  `(progn
142                     (define-vop (,reffer ancestor-frame-ref)
143                       (:results (value :scs (,sc)))
144                       (:generator 4
145                         (aver (sc-is variable-home-tn ,stack-sc))
146                         (inst ,instruction value
147                               ,ea)))
148                     (define-vop (,setter ancestor-frame-set)
149                       (:args (frame-pointer :scs (descriptor-reg))
150                              (value :scs (,sc)))
151                       (:generator 4
152                         (aver (sc-is variable-home-tn ,stack-sc))
153                         (inst ,instruction ,ea value)))))))
154   (define-frame-op double-float double-reg double-stack movsd)
155   (define-frame-op single-float single-reg single-stack movss)
156   (define-frame-op complex-double-float complex-double-reg complex-double-stack
157     movupd (ea-for-cdf-data-stack variable-home-tn frame-pointer))
158   (define-frame-op complex-single-float complex-single-reg complex-single-stack
159     movq   (ea-for-csf-data-stack variable-home-tn frame-pointer))
160   (define-frame-op signed-byte-64 signed-reg signed-stack mov)
161   (define-frame-op unsigned-byte-64 unsigned-reg unsigned-stack mov)
162   (define-frame-op system-area-pointer sap-reg sap-stack mov))
163
164 (defun primitive-type-indirect-cell-type (ptype)
165   (declare (type primitive-type ptype))
166   (macrolet ((foo (&body data)
167                  `(case (primitive-type-name ptype)
168                     ,@(loop for (name stack-sc ref set) in data
169                             collect
170                             `(,name
171                                (load-time-value
172                                 (list (primitive-type-or-lose ',name)
173                                       (sc-or-lose ',stack-sc)
174                                       (lambda (node block fp value res)
175                                         (sb!c::vop ,ref node block
176                                                    fp value res))
177                                       (lambda (node block fp new-val value)
178                                         (sb!c::vop ,set node block
179                                                    fp new-val value)))))))))
180     (foo (double-float double-stack
181                        ancestor-frame-ref/double-float
182                        ancestor-frame-set/double-float)
183          (single-float single-stack
184                        ancestor-frame-ref/single-float
185                        ancestor-frame-set/single-float)
186          (complex-double-float complex-double-stack
187                                ancestor-frame-ref/complex-double-float
188                                ancestor-frame-set/complex-double-float)
189          (complex-single-float complex-single-stack
190                                ancestor-frame-ref/complex-single-float
191                                ancestor-frame-set/complex-single-float)
192          (signed-byte-64 signed-stack
193                          ancestor-frame-ref/signed-byte-64
194                          ancestor-frame-set/signed-byte-64)
195          (unsigned-byte-64 unsigned-stack
196                            ancestor-frame-ref/unsigned-byte-64
197                            ancestor-frame-set/unsigned-byte-64)
198          (unsigned-byte-63 unsigned-stack
199                            ancestor-frame-ref/unsigned-byte-64
200                            ancestor-frame-set/unsigned-byte-64)
201          (system-area-pointer sap-stack
202                               ancestor-frame-ref/system-area-pointer
203                               ancestor-frame-set/system-area-pointer))))
204
205 (define-vop (xep-allocate-frame)
206   (:info start-lab copy-more-arg-follows)
207   (:vop-var vop)
208   (:generator 1
209     (emit-alignment n-lowtag-bits)
210     (trace-table-entry trace-table-fun-prologue)
211     (emit-label start-lab)
212     ;; Skip space for the function header.
213     (inst simple-fun-header-word)
214     (dotimes (i (* n-word-bytes (1- simple-fun-code-offset)))
215       (inst byte 0))
216
217     ;; The start of the actual code.
218     ;; Save the return-pc.
219     (popw rbp-tn (frame-word-offset return-pc-save-offset))
220
221     ;; If copy-more-arg follows it will allocate the correct stack
222     ;; size. The stack is not allocated first here as this may expose
223     ;; args on the stack if they take up more space than the frame!
224     (unless copy-more-arg-follows
225       ;; The args fit within the frame so just allocate the frame.
226       (inst lea rsp-tn
227             (make-ea :qword :base rbp-tn
228                      :disp (- (* n-word-bytes
229                                  (- (max 3 (sb-allocated-size 'stack))
230                                     sp->fp-offset))))))
231
232     (trace-table-entry trace-table-normal)))
233
234 ;;; This is emitted directly before either a known-call-local, call-local,
235 ;;; or a multiple-call-local. All it does is allocate stack space for the
236 ;;; callee (who has the same size stack as us).
237 (define-vop (allocate-frame)
238   (:results (res :scs (any-reg))
239             (nfp))
240   (:info callee)
241   (:ignore nfp callee)
242   (:generator 2
243     (inst lea res (make-ea :qword :base rsp-tn
244                            :disp (- (* sp->fp-offset n-word-bytes))))
245     (inst sub rsp-tn (* n-word-bytes (sb-allocated-size 'stack)))))
246
247 ;;; Allocate a partial frame for passing stack arguments in a full
248 ;;; call. NARGS is the number of arguments passed. We allocate at
249 ;;; least 3 slots, because the XEP noise is going to want to use them
250 ;;; before it can extend the stack.
251 (define-vop (allocate-full-call-frame)
252   (:info nargs)
253   (:results (res :scs (any-reg)))
254   (:generator 2
255     (inst lea res (make-ea :qword :base rsp-tn
256                            :disp (- (* sp->fp-offset n-word-bytes))))
257     (inst sub rsp-tn (* (max nargs 3) n-word-bytes))))
258 \f
259 ;;; Emit code needed at the return-point from an unknown-values call
260 ;;; for a fixed number of values. Values is the head of the TN-REF
261 ;;; list for the locations that the values are to be received into.
262 ;;; Nvals is the number of values that are to be received (should
263 ;;; equal the length of Values).
264 ;;;
265 ;;; If 0 or 1 values are expected, then we just emit an instruction to
266 ;;; reset the SP (which will only be executed when other than 1 value
267 ;;; is returned.)
268 ;;;
269 ;;; In the general case we have to do three things:
270 ;;;  -- Default unsupplied register values. This need only be done
271 ;;;     when a single value is returned, since register values are
272 ;;;     defaulted by the called in the non-single case.
273 ;;;  -- Default unsupplied stack values. This needs to be done whenever
274 ;;;     there are stack values.
275 ;;;  -- Reset SP. This must be done whenever other than 1 value is
276 ;;;     returned, regardless of the number of values desired.
277 (defun default-unknown-values (vop values nvals node)
278   (declare (type (or tn-ref null) values)
279            (type unsigned-byte nvals))
280   (let ((type (sb!c::basic-combination-derived-type node)))
281     (cond
282       ((<= nvals 1)
283        (note-this-location vop :single-value-return)
284        (cond
285          ((<= (sb!kernel:values-type-max-value-count type)
286               register-arg-count)
287           (when (and (named-type-p type)
288                      (eq nil (named-type-name type)))
289             ;; The function never returns, it may happen that the code
290             ;; ends right here leavig the :SINGLE-VALUE-RETURN note
291             ;; dangling. Let's emit a NOP.
292             (inst nop)))
293          ((not (sb!kernel:values-type-may-be-single-value-p type))
294           (inst mov rsp-tn rbx-tn))
295          (t
296           (inst cmov :c rsp-tn rbx-tn))))
297       ((<= nvals register-arg-count)
298        (note-this-location vop :unknown-return)
299        (when (sb!kernel:values-type-may-be-single-value-p type)
300          (let ((regs-defaulted (gen-label)))
301            (inst jmp :c regs-defaulted)
302            ;; Default the unsupplied registers.
303            (let* ((2nd-tn-ref (tn-ref-across values))
304                   (2nd-tn (tn-ref-tn 2nd-tn-ref)))
305              (inst mov 2nd-tn nil-value)
306              (when (> nvals 2)
307                (loop
308                 for tn-ref = (tn-ref-across 2nd-tn-ref)
309                 then (tn-ref-across tn-ref)
310                 for count from 2 below register-arg-count
311                 do (inst mov (tn-ref-tn tn-ref) 2nd-tn))))
312            (inst mov rbx-tn rsp-tn)
313            (emit-label regs-defaulted)))
314        (when (< register-arg-count
315                 (sb!kernel:values-type-max-value-count type))
316          (inst mov rsp-tn rbx-tn)))
317       ((<= nvals 7)
318        ;; The number of bytes depends on the relative jump instructions.
319        ;; Best case is 31+(n-3)*14, worst case is 35+(n-3)*18. For
320        ;; NVALS=6 that is 73/89 bytes, and for NVALS=7 that is 87/107
321        ;; bytes which is likely better than using the blt below.
322        (let ((regs-defaulted (gen-label))
323              (defaulting-done (gen-label))
324              (default-stack-slots (gen-label)))
325          (note-this-location vop :unknown-return)
326          ;; Branch off to the MV case.
327          (inst jmp :c regs-defaulted)
328          ;; Do the single value case.
329          ;; Default the register args
330          (inst mov rax-tn nil-value)
331          (do ((i 1 (1+ i))
332               (val (tn-ref-across values) (tn-ref-across val)))
333              ((= i (min nvals register-arg-count)))
334            (inst mov (tn-ref-tn val) rax-tn))
335          ;; Fake other registers so it looks like we returned with all the
336          ;; registers filled in.
337          (move rbx-tn rsp-tn)
338          (inst jmp default-stack-slots)
339          (emit-label regs-defaulted)
340          (inst mov rax-tn nil-value)
341          (collect ((defaults))
342            (do ((i register-arg-count (1+ i))
343                 (val (do ((i 0 (1+ i))
344                           (val values (tn-ref-across val)))
345                          ((= i register-arg-count) val))
346                      (tn-ref-across val)))
347                ((null val))
348              (let ((default-lab (gen-label))
349                    (tn (tn-ref-tn val))
350                    (first-stack-arg-p (= i register-arg-count)))
351                (defaults (cons default-lab
352                                (cons tn first-stack-arg-p)))
353                (inst cmp rcx-tn (fixnumize i))
354                (inst jmp :be default-lab)
355                (when first-stack-arg-p
356                  ;; There are stack args so the frame of the callee is
357                  ;; still there, save RDX in its first slot temporalily.
358                  (storew rdx-tn rbx-tn (frame-word-offset sp->fp-offset)))
359                (loadw rdx-tn rbx-tn (frame-word-offset (+ sp->fp-offset i)))
360                (inst mov tn rdx-tn)))
361            (emit-label defaulting-done)
362            (loadw rdx-tn rbx-tn (frame-word-offset sp->fp-offset))
363            (move rsp-tn rbx-tn)
364            (let ((defaults (defaults)))
365              (when defaults
366                (assemble (*elsewhere*)
367                  (trace-table-entry trace-table-fun-prologue)
368                  (emit-label default-stack-slots)
369                  (dolist (default defaults)
370                    (emit-label (car default))
371                    (when (cddr default)
372                      ;; We are setting the first stack argument to NIL.
373                      ;; The callee's stack frame is dead, save RDX by
374                      ;; pushing it to the stack, it will end up at same
375                      ;; place as in the (STOREW RDX-TN RBX-TN -1) case
376                      ;; above.
377                      (inst push rdx-tn))
378                    (inst mov (second default) rax-tn))
379                  (inst jmp defaulting-done)
380                  (trace-table-entry trace-table-normal)))))))
381       (t
382        (let ((regs-defaulted (gen-label))
383              (restore-edi (gen-label))
384              (no-stack-args (gen-label))
385              (default-stack-vals (gen-label))
386              (count-okay (gen-label)))
387          (note-this-location vop :unknown-return)
388          ;; Branch off to the MV case.
389          (inst jmp :c regs-defaulted)
390          ;; Default the register args, and set up the stack as if we
391          ;; entered the MV return point.
392          (inst mov rbx-tn rsp-tn)
393          (inst mov rdi-tn nil-value)
394          (inst mov rsi-tn rdi-tn)
395          ;; Compute a pointer to where to put the [defaulted] stack values.
396          (emit-label no-stack-args)
397          (inst push rdx-tn)
398          (inst push rdi-tn)
399          (inst lea rdi-tn
400                (make-ea :qword :base rbp-tn
401                         :disp (frame-byte-offset register-arg-count)))
402          ;; Load RAX with NIL so we can quickly store it, and set up
403          ;; stuff for the loop.
404          (inst mov rax-tn nil-value)
405          (inst std)
406          (inst mov rcx-tn (- nvals register-arg-count))
407          ;; Jump into the default loop.
408          (inst jmp default-stack-vals)
409          ;; The regs are defaulted. We need to copy any stack arguments,
410          ;; and then default the remaining stack arguments.
411          (emit-label regs-defaulted)
412          ;; Compute the number of stack arguments, and if it's zero or
413          ;; less, don't copy any stack arguments.
414          (inst sub rcx-tn (fixnumize register-arg-count))
415          (inst jmp :le no-stack-args)
416          ;; Save EDI.
417          (storew rdi-tn rbx-tn (frame-word-offset (+ sp->fp-offset 1)))
418          ;; Throw away any unwanted args.
419          (inst cmp rcx-tn (fixnumize (- nvals register-arg-count)))
420          (inst jmp :be count-okay)
421          (inst mov rcx-tn (fixnumize (- nvals register-arg-count)))
422          (emit-label count-okay)
423          ;; Save the number of stack values.
424          (inst mov rax-tn rcx-tn)
425          ;; Compute a pointer to where the stack args go.
426          (inst lea rdi-tn
427                (make-ea :qword :base rbp-tn
428                         :disp (frame-byte-offset register-arg-count)))
429          ;; Save ESI, and compute a pointer to where the args come from.
430          (storew rsi-tn rbx-tn (frame-word-offset (+ sp->fp-offset 2)))
431          (inst lea rsi-tn
432                (make-ea :qword :base rbx-tn
433                         :disp (frame-byte-offset
434                                (+ sp->fp-offset register-arg-count))))
435          ;; Do the copy.
436          (inst shr rcx-tn n-fixnum-tag-bits)   ; make word count
437          (inst std)
438          (inst rep)
439          (inst movs :qword)
440          ;; Restore RSI.
441          (loadw rsi-tn rbx-tn (frame-word-offset (+ sp->fp-offset 2)))
442          ;; Now we have to default the remaining args. Find out how many.
443          (inst sub rax-tn (fixnumize (- nvals register-arg-count)))
444          (inst neg rax-tn)
445          ;; If none, then just blow out of here.
446          (inst jmp :le restore-edi)
447          (inst mov rcx-tn rax-tn)
448          (inst shr rcx-tn n-fixnum-tag-bits)   ; word count
449          ;; Load RAX with NIL for fast storing.
450          (inst mov rax-tn nil-value)
451          ;; Do the store.
452          (emit-label default-stack-vals)
453          (inst rep)
454          (inst stos rax-tn)
455          ;; Restore EDI, and reset the stack.
456          (emit-label restore-edi)
457          (loadw rdi-tn rbx-tn (frame-word-offset (+ sp->fp-offset 1)))
458          (inst mov rsp-tn rbx-tn)
459          (inst cld)))))
460   (values))
461 \f
462 ;;;; unknown values receiving
463
464 ;;; Emit code needed at the return point for an unknown-values call
465 ;;; for an arbitrary number of values.
466 ;;;
467 ;;; We do the single and non-single cases with no shared code: there
468 ;;; doesn't seem to be any potential overlap, and receiving a single
469 ;;; value is more important efficiency-wise.
470 ;;;
471 ;;; When there is a single value, we just push it on the stack,
472 ;;; returning the old SP and 1.
473 ;;;
474 ;;; When there is a variable number of values, we move all of the
475 ;;; argument registers onto the stack, and return ARGS and NARGS.
476 ;;;
477 ;;; ARGS and NARGS are TNs wired to the named locations. We must
478 ;;; explicitly allocate these TNs, since their lifetimes overlap with
479 ;;; the results start and count. (Also, it's nice to be able to target
480 ;;; them.)
481 (defun receive-unknown-values (args nargs start count node)
482   (declare (type tn args nargs start count))
483   (let ((type (sb!c::basic-combination-derived-type node))
484         (variable-values (gen-label))
485         (stack-values (gen-label))
486         (done (gen-label)))
487     (when (sb!kernel:values-type-may-be-single-value-p type)
488       (inst jmp :c variable-values)
489       (cond ((location= start (first *register-arg-tns*))
490              (inst push (first *register-arg-tns*))
491              (inst lea start (make-ea :qword :base rsp-tn :disp n-word-bytes)))
492             (t (inst mov start rsp-tn)
493                (inst push (first *register-arg-tns*))))
494       (inst mov count (fixnumize 1))
495       (inst jmp done)
496       (emit-label variable-values))
497     ;; The stack frame is burnt and RETurned from if there are no
498     ;; stack values. In this case quickly reallocate sufficient space.
499     (when (<= (sb!kernel:values-type-min-value-count type)
500               register-arg-count)
501       (inst cmp nargs (fixnumize register-arg-count))
502       (inst jmp :g stack-values)
503       #!+#.(cl:if (cl:= sb!vm:word-shift sb!vm:n-fixnum-tag-bits) '(and) '(or))
504       (inst sub rsp-tn nargs)
505       #!-#.(cl:if (cl:= sb!vm:word-shift sb!vm:n-fixnum-tag-bits) '(and) '(or))
506       (progn
507         ;; FIXME: This can't be efficient, but LEA (my first choice)
508         ;; doesn't do subtraction.
509         (inst shl nargs (- word-shift n-fixnum-tag-bits))
510         (inst sub rsp-tn nargs)
511         (inst shr nargs (- word-shift n-fixnum-tag-bits)))
512       (emit-label stack-values))
513     ;; dtc: this writes the registers onto the stack even if they are
514     ;; not needed, only the number specified in rcx are used and have
515     ;; stack allocated to them. No harm is done.
516     (loop
517       for arg in *register-arg-tns*
518       for i downfrom -1
519       for j below (sb!kernel:values-type-max-value-count type)
520       do (storew arg args i))
521     (move start args)
522     (move count nargs)
523
524     (emit-label done))
525   (values))
526
527 ;;; VOP that can be inherited by unknown values receivers. The main thing this
528 ;;; handles is allocation of the result temporaries.
529 (define-vop (unknown-values-receiver)
530   (:temporary (:sc descriptor-reg :offset rbx-offset
531                    :from :eval :to (:result 0))
532               values-start)
533   (:temporary (:sc any-reg :offset rcx-offset
534                :from :eval :to (:result 1))
535               nvals)
536   (:results (start :scs (any-reg control-stack))
537             (count :scs (any-reg control-stack))))
538 \f
539 ;;;; local call with unknown values convention return
540
541 (defun check-ocfp-and-return-pc (old-fp return-pc)
542   #+nil
543   (format t "*known-return: old-fp ~S, tn-kind ~S; ~S ~S~%"
544           old-fp (sb!c::tn-kind old-fp) (sb!c::tn-save-tn old-fp)
545           (sb!c::tn-kind (sb!c::tn-save-tn old-fp)))
546   #+nil
547   (format t "*known-return: return-pc ~S, tn-kind ~S; ~S ~S~%"
548           return-pc (sb!c::tn-kind return-pc)
549           (sb!c::tn-save-tn return-pc)
550           (sb!c::tn-kind (sb!c::tn-save-tn return-pc)))
551   (unless (and (sc-is old-fp control-stack)
552                (= (tn-offset old-fp) ocfp-save-offset))
553     (error "ocfp not on stack in standard save location?"))
554   (unless (and (sc-is return-pc sap-stack)
555                (= (tn-offset return-pc) return-pc-save-offset))
556     (error "return-pc not on stack in standard save location?")))
557
558 ;;; The local call convention doesn't fit that well with x86-style
559 ;;; calls. Emit a header for local calls to pop the return address
560 ;;; in the right place.
561 (defun emit-block-header (start-label trampoline-label fall-thru-p alignp)
562   (when (and fall-thru-p trampoline-label)
563     (inst jmp start-label))
564   (when trampoline-label
565     (emit-label trampoline-label)
566     (popw rbp-tn (frame-word-offset return-pc-save-offset)))
567   (when alignp
568     (emit-alignment n-lowtag-bits :long-nop))
569   (emit-label start-label))
570
571 ;;; Non-TR local call for a fixed number of values passed according to
572 ;;; the unknown values convention.
573 ;;;
574 ;;; FP is the frame pointer in install before doing the call.
575 ;;;
576 ;;; NFP would be the number-stack frame pointer if we had a separate
577 ;;; number stack.
578 ;;;
579 ;;; Args are the argument passing locations, which are specified only
580 ;;; to terminate their lifetimes in the caller.
581 ;;;
582 ;;; VALUES are the return value locations (wired to the standard
583 ;;; passing locations). NVALS is the number of values received.
584 ;;;
585 ;;; Save is the save info, which we can ignore since saving has been
586 ;;; done.
587 ;;;
588 ;;; TARGET is a continuation pointing to the start of the called
589 ;;; function.
590 (define-vop (call-local)
591   (:args (fp)
592          (nfp)
593          (args :more t))
594   (:results (values :more t))
595   (:save-p t)
596   (:move-args :local-call)
597   (:info arg-locs callee target nvals)
598   (:vop-var vop)
599   (:ignore nfp arg-locs args callee)
600   (:node-var node)
601   (:generator 5
602     (trace-table-entry trace-table-call-site)
603     (move rbp-tn fp)
604     (note-this-location vop :call-site)
605     (inst call target)
606     (default-unknown-values vop values nvals node)
607     (trace-table-entry trace-table-normal)))
608
609 ;;; Non-TR local call for a variable number of return values passed according
610 ;;; to the unknown values convention. The results are the start of the values
611 ;;; glob and the number of values received.
612 (define-vop (multiple-call-local unknown-values-receiver)
613   (:args (fp)
614          (nfp)
615          (args :more t))
616   (:save-p t)
617   (:move-args :local-call)
618   (:info save callee target)
619   (:ignore args save nfp callee)
620   (:vop-var vop)
621   (:node-var node)
622   (:generator 20
623     (trace-table-entry trace-table-call-site)
624     (move rbp-tn fp)
625     (note-this-location vop :call-site)
626     (inst call target)
627     (note-this-location vop :unknown-return)
628     (receive-unknown-values values-start nvals start count node)
629     (trace-table-entry trace-table-normal)))
630 \f
631 ;;;; local call with known values return
632
633 ;;; Non-TR local call with known return locations. Known-value return
634 ;;; works just like argument passing in local call.
635 ;;;
636 ;;; Note: we can't use normal load-tn allocation for the fixed args,
637 ;;; since all registers may be tied up by the more operand. Instead,
638 ;;; we use MAYBE-LOAD-STACK-TN.
639 (define-vop (known-call-local)
640   (:args (fp)
641          (nfp)
642          (args :more t))
643   (:results (res :more t))
644   (:move-args :local-call)
645   (:save-p t)
646   (:info save callee target)
647   (:ignore args res save nfp callee)
648   (:vop-var vop)
649   (:generator 5
650     (trace-table-entry trace-table-call-site)
651     (move rbp-tn fp)
652     (note-this-location vop :call-site)
653     (inst call target)
654     (note-this-location vop :known-return)
655     (trace-table-entry trace-table-normal)))
656 \f
657 ;;; From Douglas Crosher
658 ;;; Return from known values call. We receive the return locations as
659 ;;; arguments to terminate their lifetimes in the returning function. We
660 ;;; restore FP and CSP and jump to the Return-PC.
661 (define-vop (known-return)
662   (:args (old-fp)
663          (return-pc)
664          (vals :more t))
665   (:move-args :known-return)
666   (:info val-locs)
667   (:ignore val-locs vals)
668   (:vop-var vop)
669   (:generator 6
670     (check-ocfp-and-return-pc old-fp return-pc)
671     (trace-table-entry trace-table-fun-epilogue)
672     ;; Zot all of the stack except for the old-fp and return-pc.
673     (inst mov rsp-tn rbp-tn)
674     (inst pop rbp-tn)
675     (inst ret)
676     (trace-table-entry trace-table-normal)))
677 \f
678 ;;;; full call
679 ;;;
680 ;;; There is something of a cross-product effect with full calls.
681 ;;; Different versions are used depending on whether we know the
682 ;;; number of arguments or the name of the called function, and
683 ;;; whether we want fixed values, unknown values, or a tail call.
684 ;;;
685 ;;; In full call, the arguments are passed creating a partial frame on
686 ;;; the stack top and storing stack arguments into that frame. On
687 ;;; entry to the callee, this partial frame is pointed to by FP.
688
689 ;;; This macro helps in the definition of full call VOPs by avoiding
690 ;;; code replication in defining the cross-product VOPs.
691 ;;;
692 ;;; NAME is the name of the VOP to define.
693 ;;;
694 ;;; NAMED is true if the first argument is an fdefinition object whose
695 ;;; definition is to be called.
696 ;;;
697 ;;; RETURN is either :FIXED, :UNKNOWN or :TAIL:
698 ;;; -- If :FIXED, then the call is for a fixed number of values, returned in
699 ;;;    the standard passing locations (passed as result operands).
700 ;;; -- If :UNKNOWN, then the result values are pushed on the stack, and the
701 ;;;    result values are specified by the Start and Count as in the
702 ;;;    unknown-values continuation representation.
703 ;;; -- If :TAIL, then do a tail-recursive call. No values are returned.
704 ;;;    The Old-Fp and Return-PC are passed as the second and third arguments.
705 ;;;
706 ;;; In non-tail calls, the pointer to the stack arguments is passed as
707 ;;; the last fixed argument. If Variable is false, then the passing
708 ;;; locations are passed as a more arg. Variable is true if there are
709 ;;; a variable number of arguments passed on the stack. Variable
710 ;;; cannot be specified with :TAIL return. TR variable argument call
711 ;;; is implemented separately.
712 ;;;
713 ;;; In tail call with fixed arguments, the passing locations are
714 ;;; passed as a more arg, but there is no new-FP, since the arguments
715 ;;; have been set up in the current frame.
716 (macrolet ((define-full-call (name named return variable)
717             (aver (not (and variable (eq return :tail))))
718             `(define-vop (,name
719                           ,@(when (eq return :unknown)
720                               '(unknown-values-receiver)))
721                (:args
722                ,@(unless (eq return :tail)
723                    '((new-fp :scs (any-reg) :to (:argument 1))))
724
725                (fun :scs (descriptor-reg control-stack)
726                     :target rax :to (:argument 0))
727
728                ,@(when (eq return :tail)
729                    '((old-fp)
730                      (return-pc)))
731
732                ,@(unless variable '((args :more t :scs (descriptor-reg)))))
733
734                ,@(when (eq return :fixed)
735                '((:results (values :more t))))
736
737                (:save-p ,(if (eq return :tail) :compute-only t))
738
739                ,@(unless (or (eq return :tail) variable)
740                '((:move-args :full-call)))
741
742                (:vop-var vop)
743                (:info
744                ,@(unless (or variable (eq return :tail)) '(arg-locs))
745                ,@(unless variable '(nargs))
746                ,@(when (eq return :fixed) '(nvals))
747                step-instrumenting)
748
749                (:ignore
750                ,@(unless (or variable (eq return :tail)) '(arg-locs))
751                ,@(unless variable '(args)))
752
753                ;; We pass either the fdefn object (for named call) or
754                ;; the actual function object (for unnamed call) in
755                ;; RAX. With named call, closure-tramp will replace it
756                ;; with the real function and invoke the real function
757                ;; for closures. Non-closures do not need this value,
758                ;; so don't care what shows up in it.
759                (:temporary
760                (:sc descriptor-reg
761                     :offset rax-offset
762                     :from (:argument 0)
763                     :to :eval)
764                rax)
765
766                ;; We pass the number of arguments in RCX.
767                (:temporary (:sc unsigned-reg :offset rcx-offset :to :eval) rcx)
768
769                ;; With variable call, we have to load the
770                ;; register-args out of the (new) stack frame before
771                ;; doing the call. Therefore, we have to tell the
772                ;; lifetime stuff that we need to use them.
773                ,@(when variable
774                    (mapcar (lambda (name offset)
775                              `(:temporary (:sc descriptor-reg
776                                                :offset ,offset
777                                                :from (:argument 0)
778                                                :to :eval)
779                                           ,name))
780                            *register-arg-names* *register-arg-offsets*))
781
782                ,@(when (eq return :tail)
783                    '((:temporary (:sc unsigned-reg
784                                       :from (:argument 1)
785                                       :to (:argument 2))
786                                  old-fp-tmp)))
787                ,@(unless (eq return :tail)
788                    '((:node-var node)))
789
790                (:generator ,(+ (if named 5 0)
791                                (if variable 19 1)
792                                (if (eq return :tail) 0 10)
793                                15
794                                (if (eq return :unknown) 25 0))
795                (trace-table-entry trace-table-call-site)
796
797                ;; This has to be done before the frame pointer is
798                ;; changed! RAX stores the 'lexical environment' needed
799                ;; for closures.
800                (move rax fun)
801
802
803                ,@(if variable
804                      ;; For variable call, compute the number of
805                      ;; arguments and move some of the arguments to
806                      ;; registers.
807                      (collect ((noise))
808                               ;; Compute the number of arguments.
809                               (noise '(inst mov rcx new-fp))
810                               (noise '(inst sub rcx rsp-tn))
811                               #.(unless (= word-shift n-fixnum-tag-bits)
812                                   '(noise '(inst shr rcx
813                                             (- word-shift n-fixnum-tag-bits))))
814                               ;; Move the necessary args to registers,
815                               ;; this moves them all even if they are
816                               ;; not all needed.
817                               (loop
818                                for name in *register-arg-names*
819                                for index downfrom -1
820                                do (noise `(loadw ,name new-fp ,index)))
821                               (noise))
822                    '((if (zerop nargs)
823                          (zeroize rcx)
824                        (inst mov rcx (fixnumize nargs)))))
825                ,@(cond ((eq return :tail)
826                         '(;; Python has figured out what frame we should
827                           ;; return to so might as well use that clue.
828                           ;; This seems really important to the
829                           ;; implementation of things like
830                           ;; (without-interrupts ...)
831                           ;;
832                           ;; dtc; Could be doing a tail call from a
833                           ;; known-local-call etc in which the old-fp
834                           ;; or ret-pc are in regs or in non-standard
835                           ;; places. If the passing location were
836                           ;; wired to the stack in standard locations
837                           ;; then these moves will be un-necessary;
838                           ;; this is probably best for the x86.
839                           (sc-case old-fp
840                                    ((control-stack)
841                                     (unless (= ocfp-save-offset
842                                                (tn-offset old-fp))
843                                       ;; FIXME: FORMAT T for stale
844                                       ;; diagnostic output (several of
845                                       ;; them around here), ick
846                                       (error "** tail-call old-fp not S0~%")
847                                       (move old-fp-tmp old-fp)
848                                       (storew old-fp-tmp
849                                               rbp-tn
850                                               (frame-word-offset ocfp-save-offset))))
851                                    ((any-reg descriptor-reg)
852                                     (error "** tail-call old-fp in reg not S0~%")
853                                     (storew old-fp
854                                             rbp-tn
855                                             (frame-word-offset ocfp-save-offset))))
856
857                           ;; For tail call, we have to push the
858                           ;; return-pc so that it looks like we CALLed
859                           ;; despite the fact that we are going to JMP.
860                           (inst push return-pc)
861                           ))
862                        (t
863                         ;; For non-tail call, we have to save our
864                         ;; frame pointer and install the new frame
865                         ;; pointer. We can't load stack tns after this
866                         ;; point.
867                         `(;; Python doesn't seem to allocate a frame
868                           ;; here which doesn't leave room for the
869                           ;; ofp/ret stuff.
870
871                           ;; The variable args are on the stack and
872                           ;; become the frame, but there may be <3
873                           ;; args and 3 stack slots are assumed
874                           ;; allocate on the call. So need to ensure
875                           ;; there are at least 3 slots. This hack
876                           ;; just adds 3 more.
877                           ,(if variable
878                                '(inst sub rsp-tn (* 3 n-word-bytes)))
879
880                           ;; Bias the new-fp for use as an fp
881                           ,(if variable
882                                '(inst sub new-fp (* sp->fp-offset n-word-bytes)))
883
884                           ;; Save the fp
885                           (storew rbp-tn new-fp
886                                   (frame-word-offset ocfp-save-offset))
887
888                           (move rbp-tn new-fp) ; NB - now on new stack frame.
889                           )))
890
891                (when step-instrumenting
892                  (emit-single-step-test)
893                  (inst jmp :eq DONE)
894                  (inst break single-step-around-trap))
895                DONE
896
897                (note-this-location vop :call-site)
898
899                (inst ,(if (eq return :tail) 'jmp 'call)
900                      (make-ea :qword :base rax
901                               :disp ,(if named
902                                          '(- (* fdefn-raw-addr-slot
903                                                 n-word-bytes)
904                                              other-pointer-lowtag)
905                                        '(- (* closure-fun-slot n-word-bytes)
906                                            fun-pointer-lowtag))))
907                ,@(ecase return
908                    (:fixed
909                     '((default-unknown-values vop values nvals node)))
910                    (:unknown
911                     '((note-this-location vop :unknown-return)
912                       (receive-unknown-values values-start nvals start count
913                                               node)))
914                    (:tail))
915                (trace-table-entry trace-table-normal)))))
916
917   (define-full-call call nil :fixed nil)
918   (define-full-call call-named t :fixed nil)
919   (define-full-call multiple-call nil :unknown nil)
920   (define-full-call multiple-call-named t :unknown nil)
921   (define-full-call tail-call nil :tail nil)
922   (define-full-call tail-call-named t :tail nil)
923
924   (define-full-call call-variable nil :fixed t)
925   (define-full-call multiple-call-variable nil :unknown t))
926
927 ;;; This is defined separately, since it needs special code that BLT's
928 ;;; the arguments down. All the real work is done in the assembly
929 ;;; routine. We just set things up so that it can find what it needs.
930 (define-vop (tail-call-variable)
931   (:args (args :scs (any-reg control-stack) :target rsi)
932          (function :scs (descriptor-reg control-stack) :target rax)
933          (old-fp)
934          (return-pc))
935   (:temporary (:sc unsigned-reg :offset rsi-offset :from (:argument 0)) rsi)
936   (:temporary (:sc unsigned-reg :offset rax-offset :from (:argument 1)) rax)
937   (:temporary (:sc unsigned-reg) call-target)
938   (:generator 75
939     (check-ocfp-and-return-pc old-fp return-pc)
940     ;; Move these into the passing locations if they are not already there.
941     (move rsi args)
942     (move rax function)
943     ;; And jump to the assembly routine.
944     (inst mov call-target (make-fixup 'tail-call-variable :assembly-routine))
945     (inst jmp call-target)))
946 \f
947 ;;;; unknown values return
948
949 ;;; Return a single-value using the Unknown-Values convention.
950 ;;;
951 ;;; pfw--get wired-tn conflicts sometimes if register sc specd for args
952 ;;; having problems targeting args to regs -- using temps instead.
953 ;;;
954 ;;; First off, modifying the return-pc defeats the branch-prediction
955 ;;; optimizations on modern CPUs quite handily. Second, we can do all
956 ;;; this without needing a temp register. Fixed the latter, at least.
957 ;;; -- AB 2006/Feb/04
958 (define-vop (return-single)
959   (:args (old-fp)
960          (return-pc)
961          (value))
962   (:ignore value)
963   (:generator 6
964     (check-ocfp-and-return-pc old-fp return-pc)
965     (trace-table-entry trace-table-fun-epilogue)
966     ;; Drop stack above old-fp
967     (inst mov rsp-tn rbp-tn)
968     ;; Clear the multiple-value return flag
969     (inst clc)
970     ;; Restore the old frame pointer
971     (inst pop rbp-tn)
972     ;; And return.
973     (inst ret)))
974
975 ;;; Do unknown-values return of a fixed (other than 1) number of
976 ;;; values. The VALUES are required to be set up in the standard
977 ;;; passing locations. NVALS is the number of values returned.
978 ;;;
979 ;;; Basically, we just load RCX with the number of values returned and
980 ;;; RBX with a pointer to the values, set RSP to point to the end of
981 ;;; the values, and jump directly to return-pc.
982 (define-vop (return)
983   (:args (old-fp)
984          (return-pc :to (:eval 1))
985          (values :more t))
986   (:ignore values)
987   (:info nvals)
988   ;; In the case of other than one value, we need these registers to
989   ;; tell the caller where they are and how many there are.
990   (:temporary (:sc unsigned-reg :offset rbx-offset) rbx)
991   (:temporary (:sc unsigned-reg :offset rcx-offset) rcx)
992   ;; We need to stretch the lifetime of return-pc past the argument
993   ;; registers so that we can default the argument registers without
994   ;; trashing return-pc.
995   (:temporary (:sc unsigned-reg :offset (first *register-arg-offsets*)
996                    :from :eval) a0)
997   (:temporary (:sc unsigned-reg :offset (second *register-arg-offsets*)
998                    :from :eval) a1)
999   (:temporary (:sc unsigned-reg :offset (third *register-arg-offsets*)
1000                    :from :eval) a2)
1001
1002   (:generator 6
1003     (check-ocfp-and-return-pc old-fp return-pc)
1004     (when (= nvals 1)
1005       ;; This is handled in RETURN-SINGLE.
1006       (error "nvalues is 1"))
1007     (trace-table-entry trace-table-fun-epilogue)
1008     ;; Establish the values pointer and values count.
1009     (inst lea rbx (make-ea :qword :base rbp-tn
1010                            :disp (* sp->fp-offset n-word-bytes)))
1011     (if (zerop nvals)
1012         (zeroize rcx) ; smaller
1013         (inst mov rcx (fixnumize nvals)))
1014     ;; Pre-default any argument register that need it.
1015     (when (< nvals register-arg-count)
1016       (let* ((arg-tns (nthcdr nvals (list a0 a1 a2)))
1017              (first (first arg-tns)))
1018         (inst mov first nil-value)
1019         (dolist (tn (cdr arg-tns))
1020           (inst mov tn first))))
1021     ;; Set the multiple value return flag.
1022     (inst stc)
1023     ;; And away we go. Except that return-pc is still on the
1024     ;; stack and we've changed the stack pointer. So we have to
1025     ;; tell it to index off of RBX instead of RBP.
1026     (cond ((<= nvals register-arg-count)
1027            (inst mov rsp-tn rbp-tn)
1028            (inst pop rbp-tn)
1029            (inst ret))
1030           (t
1031            ;; Some values are on the stack after RETURN-PC and OLD-FP,
1032            ;; can't return normally and some slots of the frame will
1033            ;; be used as temporaries by the receiver.
1034            ;;
1035            ;; Clear as much of the stack as possible, but not past the
1036            ;; old frame address.
1037            (inst lea rsp-tn
1038                  (make-ea :qword :base rbp-tn
1039                           :disp (frame-byte-offset (1- nvals))))
1040            (move rbp-tn old-fp)
1041            (inst push (make-ea :qword :base rbx
1042                                :disp (frame-byte-offset
1043                                       (+ sp->fp-offset
1044                                          (tn-offset return-pc)))))
1045            (inst ret)))
1046
1047     (trace-table-entry trace-table-normal)))
1048
1049 ;;; Do unknown-values return of an arbitrary number of values (passed
1050 ;;; on the stack.) We check for the common case of a single return
1051 ;;; value, and do that inline using the normal single value return
1052 ;;; convention. Otherwise, we branch off to code that calls an
1053 ;;; assembly-routine.
1054 ;;;
1055 ;;; The assembly routine takes the following args:
1056 ;;;  RCX -- number of values to find there.
1057 ;;;  RSI -- pointer to where to find the values.
1058 (define-vop (return-multiple)
1059   (:args (old-fp)
1060          (return-pc)
1061          (vals :scs (any-reg) :target rsi)
1062          (nvals :scs (any-reg) :target rcx))
1063   (:temporary (:sc unsigned-reg :offset rsi-offset :from (:argument 2)) rsi)
1064   (:temporary (:sc unsigned-reg :offset rcx-offset :from (:argument 3)) rcx)
1065   (:temporary (:sc unsigned-reg) return-asm)
1066   (:temporary (:sc descriptor-reg :offset (first *register-arg-offsets*)
1067                    :from (:eval 0)) a0)
1068   (:node-var node)
1069   (:generator 13
1070     (check-ocfp-and-return-pc old-fp return-pc)
1071     (trace-table-entry trace-table-fun-epilogue)
1072     (unless (policy node (> space speed))
1073       ;; Check for the single case.
1074       (let ((not-single (gen-label)))
1075         (inst cmp nvals (fixnumize 1))
1076         (inst jmp :ne not-single)
1077         ;; Return with one value.
1078         (loadw a0 vals -1)
1079         ;; Clear the stack until ocfp.
1080         (inst mov rsp-tn rbp-tn)
1081         ;; clear the multiple-value return flag
1082         (inst clc)
1083         ;; Out of here.
1084         (inst pop rbp-tn)
1085         (inst ret)
1086         ;; Nope, not the single case. Jump to the assembly routine.
1087         (emit-label not-single)))
1088     (move rsi vals)
1089     (move rcx nvals)
1090     (inst mov return-asm (make-fixup 'return-multiple :assembly-routine))
1091     (inst jmp return-asm)
1092     (trace-table-entry trace-table-normal)))
1093 \f
1094 ;;;; XEP hackery
1095
1096 ;;; We don't need to do anything special for regular functions.
1097 (define-vop (setup-environment)
1098   (:info label)
1099   (:ignore label)
1100   (:generator 0
1101     ;; Don't bother doing anything.
1102     nil))
1103
1104 ;;; Get the lexical environment from its passing location.
1105 (define-vop (setup-closure-environment)
1106   (:results (closure :scs (descriptor-reg)))
1107   (:info label)
1108   (:ignore label)
1109   (:generator 6
1110     ;; Get result.
1111     (move closure rax-tn)))
1112
1113 ;;; Copy a &MORE arg from the argument area to the end of the current
1114 ;;; frame. FIXED is the number of non-&MORE arguments.
1115 (define-vop (copy-more-arg)
1116   (:temporary (:sc any-reg :offset r8-offset) copy-index)
1117   (:temporary (:sc any-reg :offset r9-offset) source)
1118   (:temporary (:sc descriptor-reg :offset r10-offset) temp)
1119   (:info fixed)
1120   (:generator 20
1121     ;; Avoid the copy if there are no more args.
1122     (cond ((zerop fixed)
1123            (inst jrcxz JUST-ALLOC-FRAME))
1124           (t
1125            (inst cmp rcx-tn (fixnumize fixed))
1126            (inst jmp :be JUST-ALLOC-FRAME)))
1127
1128     ;; Create a negated copy of the number of arguments to allow us to
1129     ;; use EA calculations in order to do scaled subtraction.
1130     (inst mov temp rcx-tn)
1131     (inst neg temp)
1132
1133     ;; Allocate the space on the stack.
1134     ;; stack = rbp + sp->fp-offset - (max 3 frame-size) - (nargs - fixed)
1135     (inst lea rsp-tn
1136           (make-ea :qword :base rbp-tn
1137                    :index temp :scale (ash 1 (- word-shift n-fixnum-tag-bits))
1138                    :disp (* n-word-bytes
1139                             (- (+ sp->fp-offset fixed)
1140                                (max 3 (sb-allocated-size 'stack))))))
1141
1142     ;; Now: nargs>=1 && nargs>fixed
1143
1144     ;; Save the original count of args.
1145     (inst mov rbx-tn rcx-tn)
1146
1147     (cond ((< fixed register-arg-count)
1148            ;; We must stop when we run out of stack args, not when we
1149            ;; run out of more args.
1150            ;; Number to copy = nargs-3
1151            (inst sub rbx-tn (fixnumize register-arg-count))
1152            ;; Everything of interest in registers.
1153            (inst jmp :be DO-REGS))
1154           (t
1155            ;; Number to copy = nargs-fixed
1156            (inst sub rbx-tn (fixnumize fixed))))
1157
1158     ;; Initialize R8 to be the end of args.
1159     (inst lea source (make-ea :qword :base rbp-tn
1160                               :index temp :scale (ash 1 (- word-shift n-fixnum-tag-bits))
1161                               :disp (* sp->fp-offset n-word-bytes)))
1162
1163     ;; We need to copy from downwards up to avoid overwriting some of
1164     ;; the yet uncopied args. So we need to use R9 as the copy index
1165     ;; and RBX as the loop counter, rather than using RBX for both.
1166     (zeroize copy-index)
1167
1168     ;; We used to use REP MOVS here, but on modern x86 it performs
1169     ;; much worse than an explicit loop for small blocks.
1170     COPY-LOOP
1171     (inst mov temp (make-ea :qword :base source :index copy-index))
1172     (inst mov (make-ea :qword :base rsp-tn :index copy-index) temp)
1173     (inst add copy-index n-word-bytes)
1174     (inst sub rbx-tn (fixnumize 1))
1175     (inst jmp :nz COPY-LOOP)
1176
1177     DO-REGS
1178
1179     ;; Here: nargs>=1 && nargs>fixed
1180     (when (< fixed register-arg-count)
1181       ;; Now we have to deposit any more args that showed up in
1182       ;; registers.
1183       (do ((i fixed))
1184           ( nil )
1185         ;; Store it relative to rbp
1186         (inst mov (make-ea :qword :base rbp-tn
1187                            :disp (* n-word-bytes
1188                                     (- sp->fp-offset
1189                                        (+ 1
1190                                           (- i fixed)
1191                                           (max 3 (sb-allocated-size
1192                                                   'stack))))))
1193               (nth i *register-arg-tns*))
1194
1195         (incf i)
1196         (when (>= i register-arg-count)
1197           (return))
1198
1199         ;; Don't deposit any more than there are.
1200         (if (zerop i)
1201             (inst test rcx-tn rcx-tn)
1202             (inst cmp rcx-tn (fixnumize i)))
1203         (inst jmp :eq DONE)))
1204
1205     (inst jmp DONE)
1206
1207     JUST-ALLOC-FRAME
1208     (inst lea rsp-tn
1209           (make-ea :qword :base rbp-tn
1210                    :disp (* n-word-bytes
1211                             (- sp->fp-offset
1212                                (max 3 (sb-allocated-size 'stack))))))
1213
1214     DONE))
1215
1216 (define-vop (more-kw-arg)
1217   (:translate sb!c::%more-kw-arg)
1218   (:policy :fast-safe)
1219   (:args (object :scs (descriptor-reg) :to (:result 1))
1220          (index :scs (any-reg) :to (:result 1) :target keyword))
1221   (:arg-types * tagged-num)
1222   (:results (value :scs (descriptor-reg any-reg))
1223             (keyword :scs (descriptor-reg any-reg)))
1224   (:result-types * *)
1225   (:generator 4
1226      (inst mov value (make-ea :qword :base object :index index
1227                               :scale (ash 1 (- word-shift n-fixnum-tag-bits))))
1228      (inst mov keyword (make-ea :qword :base object :index index
1229                                 :scale (ash 1 (- word-shift n-fixnum-tag-bits))
1230                                 :disp n-word-bytes))))
1231
1232 (define-vop (more-arg)
1233   (:translate sb!c::%more-arg)
1234   (:policy :fast-safe)
1235   (:args (object :scs (descriptor-reg) :to (:result 1))
1236          (index :scs (any-reg) :to (:result 1) :target value))
1237   (:arg-types * tagged-num)
1238   (:results (value :scs (descriptor-reg any-reg)))
1239   (:result-types *)
1240   (:generator 4
1241     (move value index)
1242     (inst neg value)
1243     (inst mov value (make-ea :qword :base object :index value
1244                              :scale (ash 1 (- word-shift n-fixnum-tag-bits))))))
1245
1246 ;;; Turn more arg (context, count) into a list.
1247 (define-vop (listify-rest-args)
1248   (:translate %listify-rest-args)
1249   (:policy :safe)
1250   (:args (context :scs (descriptor-reg) :target src)
1251          (count :scs (any-reg) :target rcx))
1252   (:arg-types * tagged-num)
1253   (:temporary (:sc unsigned-reg :offset rsi-offset :from (:argument 0)) src)
1254   (:temporary (:sc unsigned-reg :offset rcx-offset :from (:argument 1)) rcx)
1255   (:temporary (:sc unsigned-reg :offset rax-offset) rax)
1256   (:temporary (:sc unsigned-reg) dst)
1257   (:results (result :scs (descriptor-reg)))
1258   (:node-var node)
1259   (:generator 20
1260     (let ((enter (gen-label))
1261           (loop (gen-label))
1262           (done (gen-label))
1263           (stack-allocate-p (node-stack-allocate-p node)))
1264       (move src context)
1265       (move rcx count)
1266       ;; Check to see whether there are no args, and just return NIL if so.
1267       (inst mov result nil-value)
1268       (inst jrcxz done)
1269       (inst lea dst (make-ea :qword :index rcx :scale (ash 2 (- word-shift n-fixnum-tag-bits))))
1270       (maybe-pseudo-atomic stack-allocate-p
1271        (allocation dst dst node stack-allocate-p list-pointer-lowtag)
1272        ;; Set up the result.
1273        (move result dst)
1274        ;; Jump into the middle of the loop, 'cause that's where we want
1275        ;; to start.
1276        (inst jmp enter)
1277        (emit-label loop)
1278        ;; Compute a pointer to the next cons.
1279        (inst add dst (* cons-size n-word-bytes))
1280        ;; Store a pointer to this cons in the CDR of the previous cons.
1281        (storew dst dst -1 list-pointer-lowtag)
1282        (emit-label enter)
1283        ;; Grab one value and stash it in the car of this cons.
1284        (inst mov rax (make-ea :qword :base src))
1285        (inst sub src n-word-bytes)
1286        (storew rax dst 0 list-pointer-lowtag)
1287        ;; Go back for more.
1288        (inst sub rcx (fixnumize 1))
1289        (inst jmp :nz loop)
1290        ;; NIL out the last cons.
1291        (storew nil-value dst 1 list-pointer-lowtag))
1292       (emit-label done))))
1293
1294 ;;; Return the location and size of the &MORE arg glob created by
1295 ;;; COPY-MORE-ARG. SUPPLIED is the total number of arguments supplied
1296 ;;; (originally passed in RCX). FIXED is the number of non-rest
1297 ;;; arguments.
1298 ;;;
1299 ;;; We must duplicate some of the work done by COPY-MORE-ARG, since at
1300 ;;; that time the environment is in a pretty brain-damaged state,
1301 ;;; preventing this info from being returned as values. What we do is
1302 ;;; compute supplied - fixed, and return a pointer that many words
1303 ;;; below the current stack top.
1304 (define-vop (more-arg-context)
1305   (:policy :fast-safe)
1306   (:translate sb!c::%more-arg-context)
1307   (:args (supplied :scs (any-reg) :target count))
1308   (:arg-types positive-fixnum (:constant fixnum))
1309   (:info fixed)
1310   (:results (context :scs (descriptor-reg))
1311             (count :scs (any-reg)))
1312   (:result-types t tagged-num)
1313   (:note "more-arg-context")
1314   (:generator 5
1315     (move count supplied)
1316     ;; SP at this point points at the last arg pushed.
1317     ;; Point to the first more-arg, not above it.
1318     (inst lea context (make-ea :qword :base rsp-tn
1319                                :index count
1320                                :scale (ash 1 (- word-shift n-fixnum-tag-bits))
1321                                :disp (- (* (1+ fixed) n-word-bytes))))
1322     (unless (zerop fixed)
1323       (inst sub count (fixnumize fixed)))))
1324
1325 ;;; Signal wrong argument count error if NARGS isn't equal to COUNT.
1326 (define-vop (verify-arg-count)
1327   (:policy :fast-safe)
1328   (:translate sb!c::%verify-arg-count)
1329   (:args (nargs :scs (any-reg)))
1330   (:arg-types positive-fixnum (:constant t))
1331   (:info count)
1332   (:vop-var vop)
1333   (:save-p :compute-only)
1334   (:generator 3
1335     (let ((err-lab
1336            (generate-error-code vop 'invalid-arg-count-error nargs)))
1337       (if (zerop count)
1338           (inst test nargs nargs)  ; smaller instruction
1339         (inst cmp nargs (fixnumize count)))
1340       (inst jmp :ne err-lab))))
1341
1342 ;;; Various other error signallers.
1343 (macrolet ((def (name error translate &rest args)
1344              `(define-vop (,name)
1345                 ,@(when translate
1346                     `((:policy :fast-safe)
1347                       (:translate ,translate)))
1348                 (:args ,@(mapcar (lambda (arg)
1349                                    `(,arg :scs (any-reg descriptor-reg)))
1350                                  args))
1351                 (:vop-var vop)
1352                 (:save-p :compute-only)
1353                 (:generator 1000
1354                   (error-call vop ',error ,@args)))))
1355   (def arg-count-error invalid-arg-count-error
1356     sb!c::%arg-count-error nargs)
1357   (def type-check-error object-not-type-error sb!c::%type-check-error
1358     object type)
1359   (def layout-invalid-error layout-invalid-error sb!c::%layout-invalid-error
1360     object layout)
1361   (def odd-key-args-error odd-key-args-error
1362     sb!c::%odd-key-args-error)
1363   (def unknown-key-arg-error unknown-key-arg-error
1364     sb!c::%unknown-key-arg-error key)
1365   (def nil-fun-returned-error nil-fun-returned-error nil fun))
1366
1367 ;;; Single-stepping
1368
1369 (defun emit-single-step-test ()
1370   ;; We use different ways of representing whether stepping is on on
1371   ;; +SB-THREAD / -SB-THREAD: on +SB-THREAD, we use a slot in the
1372   ;; thread structure. On -SB-THREAD we use the value of a static
1373   ;; symbol. Things are done this way, since reading a thread-local
1374   ;; slot from a symbol would require an extra register on +SB-THREAD,
1375   ;; and reading a slot from a thread structure would require an extra
1376   ;; register on -SB-THREAD. While this isn't critical for x86-64,
1377   ;; it's more serious for x86.
1378   #!+sb-thread
1379   (inst cmp (make-ea :qword
1380                      :base thread-base-tn
1381                      :disp (* thread-stepping-slot n-word-bytes))
1382         nil-value)
1383   #!-sb-thread
1384   (inst cmp (make-ea :qword
1385                      :disp (+ nil-value (static-symbol-offset
1386                                          'sb!impl::*stepping*)
1387                               (* symbol-value-slot n-word-bytes)
1388                               (- other-pointer-lowtag)))
1389         nil-value))
1390
1391 (define-vop (step-instrument-before-vop)
1392   (:policy :fast-safe)
1393   (:vop-var vop)
1394   (:generator 3
1395      (emit-single-step-test)
1396      (inst jmp :eq DONE)
1397      (inst break single-step-before-trap)
1398      DONE
1399      (note-this-location vop :step-before-vop)))