Defer some sanity checks to after testing for value refence to inline functions
[sbcl.git] / src / compiler / ir2tran.lisp
1 ;;;; This file contains the virtual-machine-independent parts of the
2 ;;;; code which does the actual translation of nodes to VOPs.
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!C")
14 \f
15 ;;;; moves and type checks
16
17 ;;; Move X to Y unless they are EQ.
18 (defun emit-move (node block x y)
19   (declare (type node node) (type ir2-block block) (type tn x y))
20   (unless (eq x y)
21     (vop move node block x y))
22   (values))
23
24 ;;; Determine whether we should emit a single-stepper breakpoint
25 ;;; around a call / before a vop.
26 (defun emit-step-p (node)
27   (if (and (policy node (> insert-step-conditions 1))
28            (typep node 'combination))
29       (combination-step-info node)
30       nil))
31
32 ;;; If there is any CHECK-xxx template for TYPE, then return it,
33 ;;; otherwise return NIL.
34 ;;; The second value is T if the template needs TYPE to be passed
35 (defun type-check-template (type)
36   (declare (type ctype type))
37   (multiple-value-bind (check-ptype exact) (primitive-type type)
38     (if exact
39         (primitive-type-check check-ptype)
40         (multiple-value-bind (name type-needed)
41             (hairy-type-check-template-name type)
42           (if name
43               (values (template-or-lose name) type-needed)
44               nil)))))
45
46 ;;; Emit code in BLOCK to check that VALUE is of the specified TYPE,
47 ;;; yielding the checked result in RESULT. VALUE and result may be of
48 ;;; any primitive type. There must be CHECK-xxx VOP for TYPE. Any
49 ;;; other type checks should have been converted to an explicit type
50 ;;; test.
51 (defun emit-type-check (node block value result type)
52   (declare (type tn value result) (type node node) (type ir2-block block)
53            (type ctype type))
54   (multiple-value-bind (template type-needed) (type-check-template type)
55    (if type-needed
56        (emit-load-template node block template value result (list type))
57        (emit-move-template node block template value result)))
58   (values))
59
60 ;;; Allocate an indirect value cell.
61 (defevent make-value-cell-event "Allocate heap value cell for lexical var.")
62 (defun emit-make-value-cell (node block value res)
63   (event make-value-cell-event node)
64   (vop make-value-cell node block value nil res))
65 \f
66 ;;;; leaf reference
67
68 ;;; Return the TN that holds the value of THING in the environment ENV.
69 (declaim (ftype (function ((or nlx-info lambda-var clambda) physenv) tn)
70                 find-in-physenv))
71 (defun find-in-physenv (thing physenv)
72   (or (cdr (assoc thing (ir2-physenv-closure (physenv-info physenv))))
73       (etypecase thing
74         (lambda-var
75          ;; I think that a failure of this assertion means that we're
76          ;; trying to access a variable which was improperly closed
77          ;; over. The PHYSENV describes a physical environment. Every
78          ;; variable that a form refers to should either be in its
79          ;; physical environment directly, or grabbed from a
80          ;; surrounding physical environment when it was closed over.
81          ;; The ASSOC expression above finds closed-over variables, so
82          ;; if we fell through the ASSOC expression, it wasn't closed
83          ;; over. Therefore, it must be in our physical environment
84          ;; directly. If instead it is in some other physical
85          ;; environment, then it's bogus for us to reference it here
86          ;; without it being closed over. -- WHN 2001-09-29
87          (aver (eq physenv (lambda-physenv (lambda-var-home thing))))
88          (leaf-info thing))
89         (nlx-info
90          (aver (eq physenv (block-physenv (nlx-info-target thing))))
91          (ir2-nlx-info-home (nlx-info-info thing)))
92         (clambda
93          (aver (xep-p thing))
94          (entry-info-closure-tn (lambda-info thing))))
95       (bug "~@<~2I~_~S ~_not found in ~_~S~:>" thing physenv)))
96
97 ;;; If LEAF already has a constant TN, return that, otherwise make a
98 ;;; TN for it.
99 (defun constant-tn (leaf boxedp)
100   (declare (type constant leaf))
101   ;; When convenient we can have both a boxed and unboxed TN for
102   ;; constant.
103   (if boxedp
104       (or (constant-boxed-tn leaf)
105           (setf (constant-boxed-tn leaf) (make-constant-tn leaf t)))
106       (or (leaf-info leaf)
107           (setf (leaf-info leaf) (make-constant-tn leaf nil)))))
108
109 ;;; Return a TN that represents the value of LEAF, or NIL if LEAF
110 ;;; isn't directly represented by a TN. ENV is the environment that
111 ;;; the reference is done in.
112 (defun leaf-tn (leaf env boxedp)
113   (declare (type leaf leaf) (type physenv env))
114   (typecase leaf
115     (lambda-var
116      (unless (lambda-var-indirect leaf)
117        (find-in-physenv leaf env)))
118     (constant (constant-tn leaf boxedp))
119     (t nil)))
120
121 ;;; This is used to conveniently get a handle on a constant TN during
122 ;;; IR2 conversion. It returns a constant TN representing the Lisp
123 ;;; object VALUE.
124 (defun emit-constant (value)
125   (constant-tn (find-constant value) t))
126
127 (defun boxed-ref-p (ref)
128   (let ((dest (lvar-dest (ref-lvar ref))))
129     (cond ((and (basic-combination-p dest) (eq :full (basic-combination-kind dest)))
130            t)
131           ;; Other cases?
132           (t
133            nil))))
134
135 ;;; Convert a REF node. The reference must not be delayed.
136 (defun ir2-convert-ref (node block)
137   (declare (type ref node) (type ir2-block block))
138   (let* ((lvar (node-lvar node))
139          (leaf (ref-leaf node))
140          (locs (lvar-result-tns
141                 lvar (list (primitive-type (leaf-type leaf)))))
142          (res (first locs)))
143     (etypecase leaf
144       (lambda-var
145        (let ((tn (find-in-physenv leaf (node-physenv node)))
146              (indirect (lambda-var-indirect leaf))
147              (explicit (lambda-var-explicit-value-cell leaf)))
148          (cond
149           ((and indirect explicit)
150            (vop value-cell-ref node block tn res))
151           ((and indirect
152                 (not (eq (node-physenv node)
153                          (lambda-physenv (lambda-var-home leaf)))))
154            (let ((reffer (third (primitive-type-indirect-cell-type
155                                  (primitive-type (leaf-type leaf))))))
156              (if reffer
157                  (funcall reffer node block tn (leaf-info leaf) res)
158                  (vop ancestor-frame-ref node block tn (leaf-info leaf) res))))
159           (t (emit-move node block tn res)))))
160       (constant
161        (emit-move node block (constant-tn leaf (boxed-ref-p node)) res))
162       (functional
163        (ir2-convert-closure node block leaf res))
164       (global-var
165        (ir2-convert-global-var node block leaf res)))
166     (move-lvar-result node block locs lvar))
167   (values))
168
169 (defun ir2-convert-global-var (node block leaf res)
170   (let ((unsafe (policy node (zerop safety)))
171         (name (leaf-source-name leaf)))
172     (ecase (global-var-kind leaf)
173       ((:special :unknown)
174        (aver (symbolp name))
175        (let ((name-tn (emit-constant name)))
176          (if (or unsafe (info :variable :always-bound name))
177              (vop fast-symbol-value node block name-tn res)
178              (vop symbol-value node block name-tn res))))
179       (:global
180        (aver (symbolp name))
181        (let ((name-tn (emit-constant name)))
182          (if (or unsafe (info :variable :always-bound name))
183              (vop fast-symbol-global-value node block name-tn res)
184              (vop symbol-global-value node block name-tn res))))
185       (:global-function
186        (cond #-sb-xc-host
187              ((and (info :function :definition name)
188                    (info :function :info name))
189               ;; Known functions can be saved without going through fdefns,
190               ;; except during cross-compilation
191               (emit-move node block (make-load-time-constant-tn :known-fun name)
192                          res))
193              (t
194               (let ((fdefn-tn (make-load-time-constant-tn :fdefinition name)))
195                 (if unsafe
196                     (vop fdefn-fun node block fdefn-tn res)
197                     (vop safe-fdefn-fun node block fdefn-tn res)))))))))
198
199 ;;; some sanity checks for a CLAMBDA passed to IR2-CONVERT-CLOSURE
200 (defun assertions-on-ir2-converted-clambda (clambda)
201   ;; This assertion was sort of an experiment. It would be nice and
202   ;; sane and easier to understand things if it were *always* true,
203   ;; but experimentally I observe that it's only *almost* always
204   ;; true. -- WHN 2001-01-02
205   #+nil
206   (aver (eql (lambda-component clambda)
207              (block-component (ir2-block-block ir2-block))))
208   ;; Check for some weirdness which came up in bug
209   ;; 138, 2002-01-02.
210   ;;
211   ;; The MAKE-LOAD-TIME-CONSTANT-TN call above puts an :ENTRY record
212   ;; into the IR2-COMPONENT-CONSTANTS table. The dump-a-COMPONENT
213   ;; code
214   ;;   * treats every HANDLEless :ENTRY record into a
215   ;;     patch, and
216   ;;   * expects every patch to correspond to an
217   ;;     IR2-COMPONENT-ENTRIES record.
218   ;; The IR2-COMPONENT-ENTRIES records are set by ENTRY-ANALYZE
219   ;; walking over COMPONENT-LAMBDAS. Bug 138b arose because there
220   ;; was a HANDLEless :ENTRY record which didn't correspond to an
221   ;; IR2-COMPONENT-ENTRIES record. That problem is hard to debug
222   ;; when it's caught at dump time, so this assertion tries to catch
223   ;; it here.
224   (aver (member clambda
225                 (component-lambdas (lambda-component clambda))))
226   ;; another bug-138-related issue: COMPONENT-NEW-FUNCTIONALS is
227   ;; used as a queue for stuff pending to do in IR1, and now that
228   ;; we're doing IR2 it should've been completely flushed (but
229   ;; wasn't).
230   (aver (null (component-new-functionals (lambda-component clambda))))
231   (values))
232
233 ;;; Emit code to load a function object implementing FUNCTIONAL into
234 ;;; RES. This gets interesting when the referenced function is a
235 ;;; closure: we must make the closure and move the closed-over values
236 ;;; into it.
237 ;;;
238 ;;; FUNCTIONAL is either a :TOPLEVEL-XEP functional or the XEP lambda
239 ;;; for the called function, since local call analysis converts all
240 ;;; closure references. If a :TOPLEVEL-XEP, we know it is not a
241 ;;; closure.
242 ;;;
243 ;;; If a closed-over LAMBDA-VAR has no refs (is deleted), then we
244 ;;; don't initialize that slot. This can happen with closures over
245 ;;; top level variables, where optimization of the closure deleted the
246 ;;; variable. Since we committed to the closure format when we
247 ;;; pre-analyzed the top level code, we just leave an empty slot.
248 (defun ir2-convert-closure (ref ir2-block functional res)
249   (declare (type ref ref)
250            (type ir2-block ir2-block)
251            (type functional functional)
252            (type tn res))
253   (flet ((prepare ()
254            (aver (not (eql (functional-kind functional) :deleted)))
255            (unless (leaf-info functional)
256              (setf (leaf-info functional)
257                    (make-entry-info :name
258                                     (functional-debug-name functional))))))
259     (let ((closure (etypecase functional
260                      (clambda
261                       (assertions-on-ir2-converted-clambda functional)
262                       (physenv-closure (get-lambda-physenv functional)))
263                      (functional
264                       (aver (eq (functional-kind functional) :toplevel-xep))
265                       nil)))
266           global-var)
267       (cond (closure
268              (prepare)
269              (let* ((physenv (node-physenv ref))
270                     (tn (find-in-physenv functional physenv)))
271                (emit-move ref ir2-block tn res)))
272             ;; we're about to emit a reference to a "closure" that's actually
273             ;; an inlinable global function.
274             ((and (global-var-p (setf global-var
275                                       (functional-inline-expanded functional)))
276                   (eq :global-function (global-var-kind global-var)))
277              (ir2-convert-global-var ref ir2-block global-var res))
278             (t
279              ;; if we're here, we should have either a toplevel-xep (some
280              ;; global scope function in a different component) or an external
281              ;; reference to the "closure"'s body.
282              (prepare)
283              (aver (memq (functional-kind functional) '(:external :toplevel-xep)))
284              (let ((entry (make-load-time-constant-tn :entry functional)))
285                (emit-move ref ir2-block entry res))))))
286   (values))
287
288 (defun closure-initial-value (what this-env current-fp)
289   (declare (type (or nlx-info lambda-var clambda) what)
290            (type physenv this-env)
291            (type (or tn null) current-fp))
292   ;; If we have an indirect LAMBDA-VAR that does not require an
293   ;; EXPLICIT-VALUE-CELL, and is from this environment (not from being
294   ;; closed over), we need to store the current frame pointer.
295   (if (and (lambda-var-p what)
296            (lambda-var-indirect what)
297            (not (lambda-var-explicit-value-cell what))
298            (eq (lambda-physenv (lambda-var-home what))
299                this-env))
300     current-fp
301     (find-in-physenv what this-env)))
302
303 (defoptimizer (%allocate-closures ltn-annotate) ((leaves) node ltn-policy)
304   ltn-policy ; a hack to effectively (DECLARE (IGNORE LTN-POLICY))
305   (when (lvar-dynamic-extent leaves)
306     (let ((info (make-ir2-lvar *backend-t-primitive-type*)))
307       (setf (ir2-lvar-kind info) :delayed)
308       (setf (lvar-info leaves) info)
309       (setf (ir2-lvar-stack-pointer info)
310             (make-stack-pointer-tn)))))
311
312 (defoptimizer (%allocate-closures ir2-convert) ((leaves) call 2block)
313   (let ((dx-p (lvar-dynamic-extent leaves)))
314     (collect ((delayed))
315       (when dx-p
316         (vop current-stack-pointer call 2block
317              (ir2-lvar-stack-pointer (lvar-info leaves))))
318       (dolist (leaf (lvar-value leaves))
319         (binding* ((xep (awhen (functional-entry-fun leaf)
320                           ;; if the xep's been deleted then we can skip it
321                           (if (eq (functional-kind it) :deleted)
322                               nil it))
323                         :exit-if-null)
324                    (nil (aver (xep-p xep)))
325                    (entry-info (lambda-info xep) :exit-if-null)
326                    (tn (entry-info-closure-tn entry-info) :exit-if-null)
327                    (closure (physenv-closure (get-lambda-physenv xep)))
328                    (entry (make-load-time-constant-tn :entry xep)))
329           (let ((this-env (node-physenv call))
330                 (leaf-dx-p (and dx-p (leaf-dynamic-extent leaf))))
331             (vop make-closure call 2block entry (length closure)
332                  leaf-dx-p tn)
333             (loop for what in closure and n from 0 do
334                   (unless (and (lambda-var-p what)
335                                (null (leaf-refs what)))
336                     ;; In LABELS a closure may refer to another closure
337                     ;; in the same group, so we must be sure that we
338                     ;; store a closure only after its creation.
339                     ;;
340                     ;; TODO: Here is a simple solution: we postpone
341                     ;; putting of all closures after all creations
342                     ;; (though it may require more registers).
343                     (if (lambda-p what)
344                       (delayed (list tn (find-in-physenv what this-env) n))
345                       (let ((initial-value (closure-initial-value
346                                             what this-env nil)))
347                         (if initial-value
348                           (vop closure-init call 2block
349                                tn initial-value n)
350                           ;; An initial-value of NIL means to stash
351                           ;; the frame pointer... which requires a
352                           ;; different VOP.
353                           (vop closure-init-from-fp call 2block tn n)))))))))
354       (loop for (tn what n) in (delayed)
355             do (vop closure-init call 2block
356                     tn what n))))
357   (values))
358
359 ;;; Convert a SET node. If the NODE's LVAR is annotated, then we also
360 ;;; deliver the value to that lvar. If the var is a lexical variable
361 ;;; with no refs, then we don't actually set anything, since the
362 ;;; variable has been deleted.
363 (defun ir2-convert-set (node block)
364   (declare (type cset node) (type ir2-block block))
365   (let* ((lvar (node-lvar node))
366          (leaf (set-var node))
367          (val (lvar-tn node block (set-value node)))
368          (locs (if lvar
369                    (lvar-result-tns
370                     lvar (list (primitive-type (leaf-type leaf))))
371                    nil)))
372     (etypecase leaf
373       (lambda-var
374        (when (leaf-refs leaf)
375          (let ((tn (find-in-physenv leaf (node-physenv node)))
376                (indirect (lambda-var-indirect leaf))
377                (explicit (lambda-var-explicit-value-cell leaf)))
378            (cond
379             ((and indirect explicit)
380              (vop value-cell-set node block tn val))
381             ((and indirect
382                   (not (eq (node-physenv node)
383                            (lambda-physenv (lambda-var-home leaf)))))
384              (let ((setter (fourth (primitive-type-indirect-cell-type
385                                     (primitive-type (leaf-type leaf))))))
386              (if setter
387                  (funcall setter node block tn val (leaf-info leaf))
388                  (vop ancestor-frame-set node block tn val (leaf-info leaf)))))
389             (t (emit-move node block val tn))))))
390       (global-var
391        (aver (symbolp (leaf-source-name leaf)))
392        (ecase (global-var-kind leaf)
393          ((:special)
394           (vop set node block (emit-constant (leaf-source-name leaf)) val))
395          ((:global)
396           (vop %set-symbol-global-value node
397                block (emit-constant (leaf-source-name leaf)) val)))))
398     (when locs
399       (emit-move node block val (first locs))
400       (move-lvar-result node block locs lvar)))
401   (values))
402 \f
403 ;;;; utilities for receiving fixed values
404
405 ;;; Return a TN that can be referenced to get the value of LVAR. LVAR
406 ;;; must be LTN-ANNOTATED either as a delayed leaf ref or as a fixed,
407 ;;; single-value lvar.
408 ;;;
409 ;;; The primitive-type of the result will always be the same as the
410 ;;; IR2-LVAR-PRIMITIVE-TYPE, ensuring that VOPs are always called with
411 ;;; TNs that satisfy the operand primitive-type restriction. We may
412 ;;; have to make a temporary of the desired type and move the actual
413 ;;; lvar TN into it. This happens when we delete a type check in
414 ;;; unsafe code or when we locally know something about the type of an
415 ;;; argument variable.
416 (defun lvar-tn (node block lvar)
417   (declare (type node node) (type ir2-block block) (type lvar lvar))
418   (let* ((2lvar (lvar-info lvar))
419          (lvar-tn
420           (ecase (ir2-lvar-kind 2lvar)
421             (:delayed
422              (let ((ref (lvar-uses lvar)))
423                (leaf-tn (ref-leaf ref) (node-physenv ref) (boxed-ref-p ref))))
424             (:fixed
425              (aver (= (length (ir2-lvar-locs 2lvar)) 1))
426              (first (ir2-lvar-locs 2lvar)))))
427          (ptype (ir2-lvar-primitive-type 2lvar)))
428
429     (cond ((eq (tn-primitive-type lvar-tn) ptype) lvar-tn)
430           (t
431            (let ((temp (make-normal-tn ptype)))
432              (emit-move node block lvar-tn temp)
433              temp)))))
434
435 ;;; This is similar to LVAR-TN, but hacks multiple values. We return
436 ;;; TNs holding the values of LVAR with PTYPES as their primitive
437 ;;; types. LVAR must be annotated for the same number of fixed values
438 ;;; are there are PTYPES.
439 ;;;
440 ;;; If the lvar has a type check, check the values into temps and
441 ;;; return the temps. When we have more values than assertions, we
442 ;;; move the extra values with no check.
443 (defun lvar-tns (node block lvar ptypes)
444   (declare (type node node) (type ir2-block block)
445            (type lvar lvar) (list ptypes))
446   (let* ((locs (ir2-lvar-locs (lvar-info lvar)))
447          (nlocs (length locs)))
448     (aver (= nlocs (length ptypes)))
449
450     (mapcar (lambda (from to-type)
451               (if (eq (tn-primitive-type from) to-type)
452                   from
453                   (let ((temp (make-normal-tn to-type)))
454                     (emit-move node block from temp)
455                     temp)))
456             locs
457             ptypes)))
458 \f
459 ;;;; utilities for delivering values to lvars
460
461 ;;; Return a list of TNs with the specifier TYPES that can be used as
462 ;;; result TNs to evaluate an expression into LVAR. This is used
463 ;;; together with MOVE-LVAR-RESULT to deliver fixed values to
464 ;;; an lvar.
465 ;;;
466 ;;; If the lvar isn't annotated (meaning the values are discarded) or
467 ;;; is unknown-values, then we make temporaries for each supplied
468 ;;; value, providing a place to compute the result in until we decide
469 ;;; what to do with it (if anything.)
470 ;;;
471 ;;; If the lvar is fixed-values, and wants the same number of values
472 ;;; as the user wants to deliver, then we just return the
473 ;;; IR2-LVAR-LOCS. Otherwise we make a new list padded as necessary by
474 ;;; discarded TNs. We always return a TN of the specified type, using
475 ;;; the lvar locs only when they are of the correct type.
476 (defun lvar-result-tns (lvar types)
477   (declare (type (or lvar null) lvar) (type list types))
478   (if (not lvar)
479       (mapcar #'make-normal-tn types)
480       (let ((2lvar (lvar-info lvar)))
481         (ecase (ir2-lvar-kind 2lvar)
482           (:fixed
483            (let* ((locs (ir2-lvar-locs 2lvar))
484                   (nlocs (length locs))
485                   (ntypes (length types)))
486              (if (and (= nlocs ntypes)
487                       (do ((loc locs (cdr loc))
488                            (type types (cdr type)))
489                           ((null loc) t)
490                         (unless (eq (tn-primitive-type (car loc)) (car type))
491                           (return nil))))
492                  locs
493                  (mapcar (lambda (loc type)
494                            (if (eq (tn-primitive-type loc) type)
495                                loc
496                                (make-normal-tn type)))
497                          (if (< nlocs ntypes)
498                              (append locs
499                                      (mapcar #'make-normal-tn
500                                              (subseq types nlocs)))
501                              locs)
502                          types))))
503           (:unknown
504            (mapcar #'make-normal-tn types))))))
505
506 ;;; Make the first N standard value TNs, returning them in a list.
507 (defun make-standard-value-tns (n)
508   (declare (type unsigned-byte n))
509   (collect ((res))
510     (dotimes (i n)
511       (res (standard-arg-location i)))
512     (res)))
513
514 ;;; Return a list of TNs wired to the standard value passing
515 ;;; conventions that can be used to receive values according to the
516 ;;; unknown-values convention. This is used together with
517 ;;; MOVE-LVAR-RESULT for delivering unknown values to a fixed values
518 ;;; lvar.
519 ;;;
520 ;;; If the lvar isn't annotated, then we treat as 0-values, returning
521 ;;; an empty list of temporaries.
522 ;;;
523 ;;; If the lvar is annotated, then it must be :FIXED.
524 (defun standard-result-tns (lvar)
525   (declare (type (or lvar null) lvar))
526   (if lvar
527       (let ((2lvar (lvar-info lvar)))
528         (ecase (ir2-lvar-kind 2lvar)
529           (:fixed
530            (make-standard-value-tns (length (ir2-lvar-locs 2lvar))))))
531       nil))
532
533 ;;; Just move each SRC TN into the corresponding DEST TN, defaulting
534 ;;; any unsupplied source values to NIL. We let EMIT-MOVE worry about
535 ;;; doing the appropriate coercions.
536 (defun move-results-coerced (node block src dest)
537   (declare (type node node) (type ir2-block block) (list src dest))
538   (let ((nsrc (length src))
539         (ndest (length dest)))
540     (mapc (lambda (from to)
541             (unless (eq from to)
542               (emit-move node block from to)))
543           (if (> ndest nsrc)
544               (append src (make-list (- ndest nsrc)
545                                      :initial-element (emit-constant nil)))
546               src)
547           dest))
548   (values))
549
550 ;;; Move each SRC TN into the corresponding DEST TN, checking types
551 ;;; and defaulting any unsupplied source values to NIL
552 (defun move-results-checked (node block src dest types)
553   (declare (type node node) (type ir2-block block) (list src dest types))
554   (let ((nsrc (length src))
555         (ndest (length dest))
556         (ntypes (length types)))
557     (mapc (lambda (from to type)
558             (if type
559                 (emit-type-check node block from to type)
560                 (emit-move node block from to)))
561           (if (> ndest nsrc)
562               (append src (make-list (- ndest nsrc)
563                                      :initial-element (emit-constant nil)))
564               src)
565           dest
566           (if (> ndest ntypes)
567               (append types (make-list (- ndest ntypes)))
568               types)))
569   (values))
570
571 ;;; If necessary, emit coercion code needed to deliver the RESULTS to
572 ;;; the specified lvar. NODE and BLOCK provide context for emitting
573 ;;; code. Although usually obtained from STANDARD-RESULT-TNs or
574 ;;; LVAR-RESULT-TNs, RESULTS may be a list of any type or
575 ;;; number of TNs.
576 ;;;
577 ;;; If the lvar is fixed values, then move the results into the lvar
578 ;;; locations. If the lvar is unknown values, then do the moves into
579 ;;; the standard value locations, and use PUSH-VALUES to put the
580 ;;; values on the stack.
581 (defun move-lvar-result (node block results lvar)
582   (declare (type node node) (type ir2-block block)
583            (list results) (type (or lvar null) lvar))
584   (when lvar
585     (let ((2lvar (lvar-info lvar)))
586       (ecase (ir2-lvar-kind 2lvar)
587         (:fixed
588          (let ((locs (ir2-lvar-locs 2lvar)))
589            (unless (eq locs results)
590              (move-results-coerced node block results locs))))
591         (:unknown
592          (let* ((nvals (length results))
593                 (locs (make-standard-value-tns nvals)))
594            (move-results-coerced node block results locs)
595            (vop* push-values node block
596                  ((reference-tn-list locs nil))
597                  ((reference-tn-list (ir2-lvar-locs 2lvar) t))
598                  nvals))))))
599   (values))
600
601 ;;; CAST
602 (defun ir2-convert-cast (node block)
603   (declare (type cast node)
604            (type ir2-block block))
605   (binding* ((lvar (node-lvar node) :exit-if-null)
606              (2lvar (lvar-info lvar))
607              (value (cast-value node))
608              (2value (lvar-info value)))
609     (cond ((eq (ir2-lvar-kind 2lvar) :unused))
610           ((eq (ir2-lvar-kind 2lvar) :unknown)
611            (aver (eq (ir2-lvar-kind 2value) :unknown))
612            (aver (not (cast-type-check node)))
613            (move-results-coerced node block
614                                  (ir2-lvar-locs 2value)
615                                  (ir2-lvar-locs 2lvar)))
616           ((eq (ir2-lvar-kind 2lvar) :fixed)
617            (aver (eq (ir2-lvar-kind 2value) :fixed))
618            (if (cast-type-check node)
619                (move-results-checked node block
620                                      (ir2-lvar-locs 2value)
621                                      (ir2-lvar-locs 2lvar)
622                                      (multiple-value-bind (check types)
623                                          (cast-check-types node nil)
624                                        (aver (eq check :simple))
625                                        types))
626                (move-results-coerced node block
627                                      (ir2-lvar-locs 2value)
628                                      (ir2-lvar-locs 2lvar))))
629           (t (bug "CAST cannot be :DELAYED.")))))
630 \f
631 ;;;; template conversion
632
633 ;;; Build a TN-REFS list that represents access to the values of the
634 ;;; specified list of lvars ARGS for TEMPLATE. Any :CONSTANT arguments
635 ;;; are returned in the second value as a list rather than being
636 ;;; accessed as a normal argument. NODE and BLOCK provide the context
637 ;;; for emitting any necessary type-checking code.
638 (defun reference-args (node block args template)
639   (declare (type node node) (type ir2-block block) (list args)
640            (type template template))
641   (collect ((info-args))
642     (let ((last nil)
643           (first nil))
644       (do ((args args (cdr args))
645            (types (template-arg-types template) (cdr types)))
646           ((null args))
647         (let ((type (first types))
648               (arg (first args)))
649           (if (and (consp type) (eq (car type) ':constant))
650               (info-args (lvar-value arg))
651               (let ((ref (reference-tn (lvar-tn node block arg) nil)))
652                 (if last
653                     (setf (tn-ref-across last) ref)
654                     (setf first ref))
655                 (setq last ref)))))
656
657       (values (the (or tn-ref null) first) (info-args)))))
658
659 ;;; Convert a conditional template. We try to exploit any
660 ;;; drop-through, but emit an unconditional branch afterward if we
661 ;;; fail. NOT-P is true if the sense of the TEMPLATE's test should be
662 ;;; negated.
663 (defun ir2-convert-conditional (node block template args info-args if not-p)
664   (declare (type node node) (type ir2-block block)
665            (type template template) (type (or tn-ref null) args)
666            (list info-args) (type cif if) (type boolean not-p))
667   (let ((consequent (if-consequent if))
668         (alternative (if-alternative if))
669         (flags       (and (consp (template-result-types template))
670                           (rest (template-result-types template)))))
671     (aver (= (template-info-arg-count template)
672              (+ (length info-args)
673                 (if flags 0 2))))
674     (when not-p
675       (rotatef consequent alternative)
676       (setf not-p nil))
677     (when (drop-thru-p if consequent)
678       (rotatef consequent alternative)
679       (setf not-p t))
680     (cond ((not flags)
681            (emit-template node block template args nil
682                           (list* (block-label consequent) not-p
683                                  info-args))
684            (if (drop-thru-p if alternative)
685                (register-drop-thru alternative)
686                (vop branch node block (block-label alternative))))
687           (t
688            (emit-template node block template args nil info-args)
689            (vop branch-if node block (block-label consequent) flags not-p)
690            (if (drop-thru-p if alternative)
691                (register-drop-thru alternative)
692                (vop branch node block (block-label alternative)))))))
693
694 ;;; Convert an IF that isn't the DEST of a conditional template.
695 (defun ir2-convert-if (node block)
696   (declare (type ir2-block block) (type cif node))
697   (let* ((test (if-test node))
698          (test-ref (reference-tn (lvar-tn node block test) nil))
699          (nil-ref (reference-tn (emit-constant nil) nil)))
700     (setf (tn-ref-across test-ref) nil-ref)
701     (ir2-convert-conditional node block (template-or-lose 'if-eq)
702                              test-ref () node t)))
703
704 ;;; Return a list of primitive-types that we can pass to LVAR-RESULT-TNS
705 ;;; describing the result types we want for a template call. We are really
706 ;;; only interested in the number of results required: in normal case
707 ;;; TEMPLATE-RESULTS-OK has already checked them.
708 (defun find-template-result-types (call rtypes)
709   (let* ((type (node-derived-type call))
710          (types
711           (mapcar #'primitive-type
712                   (if (args-type-p type)
713                       (append (args-type-required type)
714                               (args-type-optional type))
715                       (list type))))
716          (primitive-t *backend-t-primitive-type*))
717     (loop for rtype in rtypes
718           for type = (or (pop types) primitive-t)
719           collect type)))
720
721 ;;; Return a list of TNs usable in a CALL to TEMPLATE delivering values to
722 ;;; LVAR. As an efficiency hack, we pick off the common case where the LVAR is
723 ;;; fixed values and has locations that satisfy the result restrictions. This
724 ;;; can fail when there is a type check or a values count mismatch.
725 (defun make-template-result-tns (call lvar rtypes)
726   (declare (type combination call) (type (or lvar null) lvar)
727            (list rtypes))
728   (let ((2lvar (when lvar (lvar-info lvar))))
729     (if (and 2lvar (eq (ir2-lvar-kind 2lvar) :fixed))
730         (let ((locs (ir2-lvar-locs 2lvar)))
731           (if (and (= (length rtypes) (length locs))
732                    (do ((loc locs (cdr loc))
733                         (rtypes rtypes (cdr rtypes)))
734                        ((null loc) t)
735                      (unless (operand-restriction-ok
736                               (car rtypes)
737                               (tn-primitive-type (car loc))
738                               :t-ok nil)
739                        (return nil))))
740               locs
741               (lvar-result-tns
742                lvar
743                (find-template-result-types call rtypes))))
744         (lvar-result-tns
745          lvar
746          (find-template-result-types call rtypes)))))
747
748 ;;; Get the operands into TNs, make TN-REFs for them, and then call
749 ;;; the template emit function.
750 (defun ir2-convert-template (call block)
751   (declare (type combination call) (type ir2-block block))
752   (let* ((template (combination-info call))
753          (lvar (node-lvar call))
754          (rtypes (template-result-types template)))
755     (multiple-value-bind (args info-args)
756         (reference-args call block (combination-args call) template)
757       (aver (not (template-more-results-type template)))
758       (if (template-conditional-p template)
759           (ir2-convert-conditional call block template args info-args
760                                    (lvar-dest lvar) nil)
761           (let* ((results (make-template-result-tns call lvar rtypes))
762                  (r-refs (reference-tn-list results t)))
763             (aver (= (length info-args)
764                      (template-info-arg-count template)))
765             (when (and lvar (lvar-dynamic-extent lvar))
766               (vop current-stack-pointer call block
767                    (ir2-lvar-stack-pointer (lvar-info lvar))))
768             (when (emit-step-p call)
769               (vop sb!vm::step-instrument-before-vop call block))
770             (if info-args
771                 (emit-template call block template args r-refs info-args)
772                 (emit-template call block template args r-refs))
773             (move-lvar-result call block results lvar)))))
774   (values))
775
776 ;;; We don't have to do much because operand count checking is done by
777 ;;; IR1 conversion. The only difference between this and the function
778 ;;; case of IR2-CONVERT-TEMPLATE is that there can be codegen-info
779 ;;; arguments.
780 (defoptimizer (%%primitive ir2-convert) ((template info &rest args) call block)
781   (let* ((template (lvar-value template))
782          (info (lvar-value info))
783          (lvar (node-lvar call))
784          (rtypes (template-result-types template))
785          (results (make-template-result-tns call lvar rtypes))
786          (r-refs (reference-tn-list results t)))
787     (multiple-value-bind (args info-args)
788         (reference-args call block (cddr (combination-args call)) template)
789       (aver (not (template-more-results-type template)))
790       (aver (not (template-conditional-p template)))
791       (aver (null info-args))
792
793       (if info
794           (emit-template call block template args r-refs info)
795           (emit-template call block template args r-refs))
796
797       (move-lvar-result call block results lvar)))
798   (values))
799
800 (defoptimizer (%%primitive derive-type) ((template info &rest args))
801   (let ((type (template-type (lvar-value template))))
802     (if (fun-type-p type)
803         (fun-type-returns type)
804         *wild-type*)))
805 \f
806 ;;;; local call
807
808 ;;; Convert a LET by moving the argument values into the variables.
809 ;;; Since a LET doesn't have any passing locations, we move the
810 ;;; arguments directly into the variables. We must also allocate any
811 ;;; indirect value cells, since there is no function prologue to do
812 ;;; this.
813 (defun ir2-convert-let (node block fun)
814   (declare (type combination node) (type ir2-block block) (type clambda fun))
815   (mapc (lambda (var arg)
816           (when arg
817             (let ((src (lvar-tn node block arg))
818                   (dest (leaf-info var)))
819               (if (and (lambda-var-indirect var)
820                        (lambda-var-explicit-value-cell var))
821                   (emit-make-value-cell node block src dest)
822                   (emit-move node block src dest)))))
823         (lambda-vars fun) (basic-combination-args node))
824   (values))
825
826 ;;; Emit any necessary moves into assignment temps for a local call to
827 ;;; FUN. We return two lists of TNs: TNs holding the actual argument
828 ;;; values, and (possibly EQ) TNs that are the actual destination of
829 ;;; the arguments. When necessary, we allocate temporaries for
830 ;;; arguments to preserve parallel assignment semantics. These lists
831 ;;; exclude unused arguments and include implicit environment
832 ;;; arguments, i.e. they exactly correspond to the arguments passed.
833 ;;;
834 ;;; OLD-FP is the TN currently holding the value we want to pass as
835 ;;; OLD-FP. If null, then the call is to the same environment (an
836 ;;; :ASSIGNMENT), so we only move the arguments, and leave the
837 ;;; environment alone.
838 ;;;
839 ;;; CLOSURE-FP is for calling a closure that has "implicit" value
840 ;;; cells (stored in the allocating stack frame), and is the frame
841 ;;; pointer TN to use for values allocated in the outbound stack
842 ;;; frame.  This is distinct from OLD-FP for the specific case of a
843 ;;; tail-local-call.
844 (defun emit-psetq-moves (node block fun old-fp &optional (closure-fp old-fp))
845   (declare (type combination node) (type ir2-block block) (type clambda fun)
846            (type (or tn null) old-fp closure-fp))
847   (let ((actuals (mapcar (lambda (x)
848                            (when x
849                              (lvar-tn node block x)))
850                          (combination-args node))))
851     (collect ((temps)
852               (locs))
853       (dolist (var (lambda-vars fun))
854         (let ((actual (pop actuals))
855               (loc (leaf-info var)))
856           (when actual
857             (cond
858              ((and (lambda-var-indirect var)
859                    (lambda-var-explicit-value-cell var))
860               (let ((temp
861                      (make-normal-tn *backend-t-primitive-type*)))
862                 (emit-make-value-cell node block actual temp)
863                 (temps temp)))
864              ((member actual (locs))
865               (let ((temp (make-normal-tn (tn-primitive-type loc))))
866                 (emit-move node block actual temp)
867                 (temps temp)))
868              (t
869               (temps actual)))
870             (locs loc))))
871
872       (when old-fp
873         (let ((this-1env (node-physenv node))
874               (called-env (physenv-info (lambda-physenv fun))))
875           (dolist (thing (ir2-physenv-closure called-env))
876             (temps (closure-initial-value (car thing) this-1env closure-fp))
877             (locs (cdr thing)))
878           (temps old-fp)
879           (locs (ir2-physenv-old-fp called-env))))
880
881       (values (temps) (locs)))))
882
883 ;;; A tail-recursive local call is done by emitting moves of stuff
884 ;;; into the appropriate passing locations. After setting up the args
885 ;;; and environment, we just move our return-pc into the called
886 ;;; function's passing location.
887 (defun ir2-convert-tail-local-call (node block fun)
888   (declare (type combination node) (type ir2-block block) (type clambda fun))
889   (let ((this-env (physenv-info (node-physenv node)))
890         (current-fp (make-stack-pointer-tn)))
891     (multiple-value-bind (temps locs)
892         (emit-psetq-moves node block fun
893                           (ir2-physenv-old-fp this-env) current-fp)
894
895       ;; If we're about to emit a move from CURRENT-FP then we need to
896       ;; initialize it.
897       (when (find current-fp temps)
898         (vop current-fp node block current-fp))
899
900       (mapc (lambda (temp loc)
901               (emit-move node block temp loc))
902             temps locs))
903
904     (emit-move node block
905                (ir2-physenv-return-pc this-env)
906                (ir2-physenv-return-pc-pass
907                 (physenv-info
908                  (lambda-physenv fun)))))
909
910   (values))
911
912 ;;; Convert an :ASSIGNMENT call. This is just like a tail local call,
913 ;;; except that the caller and callee environment are the same, so we
914 ;;; don't need to mess with the environment locations, return PC, etc.
915 (defun ir2-convert-assignment (node block fun)
916   (declare (type combination node) (type ir2-block block) (type clambda fun))
917     (multiple-value-bind (temps locs) (emit-psetq-moves node block fun nil)
918
919       (mapc (lambda (temp loc)
920               (emit-move node block temp loc))
921             temps locs))
922   (values))
923
924 ;;; Do stuff to set up the arguments to a non-tail local call
925 ;;; (including implicit environment args.) We allocate a frame
926 ;;; (returning the FP and NFP), and also compute the TN-REFS list for
927 ;;; the values to pass and the list of passing location TNs.
928 (defun ir2-convert-local-call-args (node block fun)
929   (declare (type combination node) (type ir2-block block) (type clambda fun))
930   (let ((fp (make-stack-pointer-tn))
931         (nfp (make-number-stack-pointer-tn))
932         (old-fp (make-stack-pointer-tn)))
933     (multiple-value-bind (temps locs)
934         (emit-psetq-moves node block fun old-fp)
935       (vop current-fp node block old-fp)
936       (vop allocate-frame node block
937            (physenv-info (lambda-physenv fun))
938            fp nfp)
939       (values fp nfp temps (mapcar #'make-alias-tn locs)))))
940
941 ;;; Handle a non-TR known-values local call. We emit the call, then
942 ;;; move the results to the lvar's destination.
943 (defun ir2-convert-local-known-call (node block fun returns lvar start)
944   (declare (type node node) (type ir2-block block) (type clambda fun)
945            (type return-info returns) (type (or lvar null) lvar)
946            (type label start))
947   (multiple-value-bind (fp nfp temps arg-locs)
948       (ir2-convert-local-call-args node block fun)
949     (let ((locs (return-info-locations returns)))
950       (vop* known-call-local node block
951             (fp nfp (reference-tn-list temps nil))
952             ((reference-tn-list locs t))
953             arg-locs (physenv-info (lambda-physenv fun)) start)
954       (move-lvar-result node block locs lvar)))
955   (values))
956
957 ;;; Handle a non-TR unknown-values local call. We do different things
958 ;;; depending on what kind of values the lvar wants.
959 ;;;
960 ;;; If LVAR is :UNKNOWN, then we use the "multiple-" variant, directly
961 ;;; specifying the lvar's LOCS as the VOP results so that we don't
962 ;;; have to do anything after the call.
963 ;;;
964 ;;; Otherwise, we use STANDARD-RESULT-TNS to get wired result TNs, and
965 ;;; then call MOVE-LVAR-RESULT to do any necessary type checks or
966 ;;; coercions.
967 (defun ir2-convert-local-unknown-call (node block fun lvar start)
968   (declare (type node node) (type ir2-block block) (type clambda fun)
969            (type (or lvar null) lvar) (type label start))
970   (multiple-value-bind (fp nfp temps arg-locs)
971       (ir2-convert-local-call-args node block fun)
972     (let ((2lvar (and lvar (lvar-info lvar)))
973           (env (physenv-info (lambda-physenv fun)))
974           (temp-refs (reference-tn-list temps nil)))
975       (if (and 2lvar (eq (ir2-lvar-kind 2lvar) :unknown))
976           (vop* multiple-call-local node block (fp nfp temp-refs)
977                 ((reference-tn-list (ir2-lvar-locs 2lvar) t))
978                 arg-locs env start)
979           (let ((locs (standard-result-tns lvar)))
980             (vop* call-local node block
981                   (fp nfp temp-refs)
982                   ((reference-tn-list locs t))
983                   arg-locs env start (length locs))
984             (move-lvar-result node block locs lvar)))))
985   (values))
986
987 ;;; Dispatch to the appropriate function, depending on whether we have
988 ;;; a let, tail or normal call. If the function doesn't return, call
989 ;;; it using the unknown-value convention. We could compile it as a
990 ;;; tail call, but that might seem confusing in the debugger.
991 (defun ir2-convert-local-call (node block)
992   (declare (type combination node) (type ir2-block block))
993   (let* ((fun (ref-leaf (lvar-uses (basic-combination-fun node))))
994          (kind (functional-kind fun)))
995     (cond ((eq kind :let)
996            (ir2-convert-let node block fun))
997           ((eq kind :assignment)
998            (ir2-convert-assignment node block fun))
999           ((node-tail-p node)
1000            (ir2-convert-tail-local-call node block fun))
1001           (t
1002            (let ((start (block-trampoline (lambda-block fun)))
1003                  (returns (tail-set-info (lambda-tail-set fun)))
1004                  (lvar (node-lvar node)))
1005              (ecase (if returns
1006                         (return-info-kind returns)
1007                         :unknown)
1008                (:unknown
1009                 (ir2-convert-local-unknown-call node block fun lvar start))
1010                (:fixed
1011                 (ir2-convert-local-known-call node block fun returns
1012                                               lvar start)))))))
1013   (values))
1014 \f
1015 ;;;; full call
1016
1017 ;;; Given a function lvar FUN, return (VALUES TN-TO-CALL NAMED-P),
1018 ;;; where TN-TO-CALL is a TN holding the thing that we call NAMED-P is
1019 ;;; true if the thing is named (false if it is a function).
1020 ;;;
1021 ;;; There are two interesting non-named cases:
1022 ;;;   -- We know it's a function. No check needed: return the
1023 ;;;      lvar LOC.
1024 ;;;   -- We don't know what it is.
1025 (defun fun-lvar-tn (node block lvar)
1026   (declare (ignore node block))
1027   (declare (type lvar lvar))
1028   (let ((2lvar (lvar-info lvar)))
1029     (if (eq (ir2-lvar-kind 2lvar) :delayed)
1030         (let ((name (lvar-fun-name lvar t)))
1031           (aver name)
1032           (values (make-load-time-constant-tn :fdefinition name) t))
1033         (let* ((locs (ir2-lvar-locs 2lvar))
1034                (loc (first locs))
1035                (function-ptype (primitive-type-or-lose 'function)))
1036           (aver (and (eq (ir2-lvar-kind 2lvar) :fixed)
1037                      (= (length locs) 1)))
1038           (aver (eq (tn-primitive-type loc) function-ptype))
1039           (values loc nil)))))
1040
1041 ;;; Set up the args to NODE in the current frame, and return a TN-REF
1042 ;;; list for the passing locations.
1043 (defun move-tail-full-call-args (node block)
1044   (declare (type combination node) (type ir2-block block))
1045   (let ((args (basic-combination-args node))
1046         (last nil)
1047         (first nil))
1048     (dotimes (num (length args))
1049       (let ((loc (standard-arg-location num)))
1050         (emit-move node block (lvar-tn node block (elt args num)) loc)
1051         (let ((ref (reference-tn loc nil)))
1052           (if last
1053               (setf (tn-ref-across last) ref)
1054               (setf first ref))
1055           (setq last ref))))
1056       first))
1057
1058 ;;; Move the arguments into the passing locations and do a (possibly
1059 ;;; named) tail call.
1060 (defun ir2-convert-tail-full-call (node block)
1061   (declare (type combination node) (type ir2-block block))
1062   (let* ((env (physenv-info (node-physenv node)))
1063          (args (basic-combination-args node))
1064          (nargs (length args))
1065          (pass-refs (move-tail-full-call-args node block))
1066          (old-fp (ir2-physenv-old-fp env))
1067          (return-pc (ir2-physenv-return-pc env)))
1068
1069     (multiple-value-bind (fun-tn named)
1070         (fun-lvar-tn node block (basic-combination-fun node))
1071       (if named
1072           (vop* tail-call-named node block
1073                 (fun-tn old-fp return-pc pass-refs)
1074                 (nil)
1075                 nargs
1076                 (emit-step-p node))
1077           (vop* tail-call node block
1078                 (fun-tn old-fp return-pc pass-refs)
1079                 (nil)
1080                 nargs
1081                 (emit-step-p node)))))
1082
1083   (values))
1084
1085 ;;; like IR2-CONVERT-LOCAL-CALL-ARGS, only different
1086 (defun ir2-convert-full-call-args (node block)
1087   (declare (type combination node) (type ir2-block block))
1088   (let* ((args (basic-combination-args node))
1089          (fp (make-stack-pointer-tn))
1090          (nargs (length args)))
1091     (vop allocate-full-call-frame node block nargs fp)
1092     (collect ((locs))
1093       (let ((last nil)
1094             (first nil))
1095         (dotimes (num nargs)
1096           (locs (standard-arg-location num))
1097           (let ((ref (reference-tn (lvar-tn node block (elt args num))
1098                                    nil)))
1099             (if last
1100                 (setf (tn-ref-across last) ref)
1101                 (setf first ref))
1102             (setq last ref)))
1103
1104         (values fp first (locs) nargs)))))
1105
1106 ;;; Do full call when a fixed number of values are desired. We make
1107 ;;; STANDARD-RESULT-TNS for our lvar, then deliver the result using
1108 ;;; MOVE-LVAR-RESULT. We do named or normal call, as appropriate.
1109 (defun ir2-convert-fixed-full-call (node block)
1110   (declare (type combination node) (type ir2-block block))
1111   (multiple-value-bind (fp args arg-locs nargs)
1112       (ir2-convert-full-call-args node block)
1113     (let* ((lvar (node-lvar node))
1114            (locs (standard-result-tns lvar))
1115            (loc-refs (reference-tn-list locs t))
1116            (nvals (length locs)))
1117       (multiple-value-bind (fun-tn named)
1118           (fun-lvar-tn node block (basic-combination-fun node))
1119         (if named
1120             (vop* call-named node block (fp fun-tn args) (loc-refs)
1121                   arg-locs nargs nvals (emit-step-p node))
1122             (vop* call node block (fp fun-tn args) (loc-refs)
1123                   arg-locs nargs nvals (emit-step-p node)))
1124         (move-lvar-result node block locs lvar))))
1125   (values))
1126
1127 ;;; Do full call when unknown values are desired.
1128 (defun ir2-convert-multiple-full-call (node block)
1129   (declare (type combination node) (type ir2-block block))
1130   (multiple-value-bind (fp args arg-locs nargs)
1131       (ir2-convert-full-call-args node block)
1132     (let* ((lvar (node-lvar node))
1133            (locs (ir2-lvar-locs (lvar-info lvar)))
1134            (loc-refs (reference-tn-list locs t)))
1135       (multiple-value-bind (fun-tn named)
1136           (fun-lvar-tn node block (basic-combination-fun node))
1137         (if named
1138             (vop* multiple-call-named node block (fp fun-tn args) (loc-refs)
1139                   arg-locs nargs (emit-step-p node))
1140             (vop* multiple-call node block (fp fun-tn args) (loc-refs)
1141                   arg-locs nargs (emit-step-p node))))))
1142   (values))
1143
1144 ;;; stuff to check in PONDER-FULL-CALL
1145 ;;;
1146 ;;; These came in handy when troubleshooting cold boot after making
1147 ;;; major changes in the package structure: various transforms and
1148 ;;; VOPs and stuff got attached to the wrong symbol, so that
1149 ;;; references to the right symbol were bogusly translated as full
1150 ;;; calls instead of primitives, sending the system off into infinite
1151 ;;; space. Having a report on all full calls generated makes it easier
1152 ;;; to figure out what form caused the problem this time.
1153 #!+sb-show (defvar *show-full-called-fnames-p* nil)
1154 #!+sb-show (defvar *full-called-fnames* (make-hash-table :test 'equal))
1155
1156 ;;; Do some checks (and store some notes relevant for future checks)
1157 ;;; on a full call:
1158 ;;;   * Is this a full call to something we have reason to know should
1159 ;;;     never be full called? (Except as of sbcl-0.7.18 or so, we no
1160 ;;;     longer try to ensure this behavior when *FAILURE-P* has already
1161 ;;;     been detected.)
1162 ;;;   * Is this a full call to (SETF FOO) which might conflict with
1163 ;;;     a DEFSETF or some such thing elsewhere in the program?
1164 (defun ponder-full-call (node)
1165   (let* ((lvar (basic-combination-fun node))
1166          (fname (lvar-fun-name lvar t)))
1167     (declare (type (or symbol cons) fname))
1168
1169     #!+sb-show (unless (gethash fname *full-called-fnames*)
1170                  (setf (gethash fname *full-called-fnames*) t))
1171     #!+sb-show (when *show-full-called-fnames-p*
1172                  (/show "converting full call to named function" fname)
1173                  (/show (basic-combination-args node))
1174                  (/show (policy node speed) (policy node safety))
1175                  (/show (policy node compilation-speed))
1176                  (let ((arg-types (mapcar (lambda (lvar)
1177                                             (when lvar
1178                                               (type-specifier
1179                                                (lvar-type lvar))))
1180                                           (basic-combination-args node))))
1181                    (/show arg-types)))
1182
1183     ;; When illegal code is compiled, all sorts of perverse paths
1184     ;; through the compiler can be taken, and it's much harder -- and
1185     ;; probably pointless -- to guarantee that always-optimized-away
1186     ;; functions are actually optimized away. Thus, we skip the check
1187     ;; in that case.
1188     (unless *failure-p*
1189       ;; check to see if we know anything about the function
1190       (let ((info (info :function :info fname)))
1191         ;; if we know something, check to see if the full call was valid
1192         (when (and info (ir1-attributep (fun-info-attributes info)
1193                                         always-translatable))
1194           (/show (policy node speed) (policy node safety))
1195           (/show (policy node compilation-speed))
1196           (bug "full call to ~S" fname))))
1197
1198     (when (consp fname)
1199       (aver (legal-fun-name-p fname))
1200       (destructuring-bind (setfoid &rest stem) fname
1201         (when (eq setfoid 'setf)
1202           (setf (gethash (car stem) *setf-assumed-fboundp*) t))))))
1203
1204 ;;; If the call is in a tail recursive position and the return
1205 ;;; convention is standard, then do a tail full call. If one or fewer
1206 ;;; values are desired, then use a single-value call, otherwise use a
1207 ;;; multiple-values call.
1208 (defun ir2-convert-full-call (node block)
1209   (declare (type combination node) (type ir2-block block))
1210   (ponder-full-call node)
1211   (cond ((node-tail-p node)
1212          (ir2-convert-tail-full-call node block))
1213         ((let ((lvar (node-lvar node)))
1214            (and lvar
1215                 (eq (ir2-lvar-kind (lvar-info lvar)) :unknown)))
1216          (ir2-convert-multiple-full-call node block))
1217         (t
1218          (ir2-convert-fixed-full-call node block)))
1219   (values))
1220 \f
1221 ;;;; entering functions
1222
1223 ;;; Do all the stuff that needs to be done on XEP entry:
1224 ;;; -- Create frame.
1225 ;;; -- Copy any more arg.
1226 ;;; -- Set up the environment, accessing any closure variables.
1227 ;;; -- Move args from the standard passing locations to their internal
1228 ;;;    locations.
1229 (defun init-xep-environment (node block fun)
1230   (declare (type bind node) (type ir2-block block) (type clambda fun))
1231   (let ((start-label (entry-info-offset (leaf-info fun)))
1232         (env (physenv-info (node-physenv node))))
1233     (let ((ef (functional-entry-fun fun)))
1234       (cond ((and (optional-dispatch-p ef) (optional-dispatch-more-entry ef))
1235              ;; Special case the xep-allocate-frame + copy-more-arg case.
1236              (vop xep-allocate-frame node block start-label t)
1237              (vop copy-more-arg node block (optional-dispatch-max-args ef)))
1238             (t
1239              ;; No more args, so normal entry.
1240              (vop xep-allocate-frame node block start-label nil)))
1241       (if (ir2-physenv-closure env)
1242           (let ((closure (make-normal-tn *backend-t-primitive-type*)))
1243             (vop setup-closure-environment node block start-label closure)
1244             (let ((n -1))
1245               (dolist (loc (ir2-physenv-closure env))
1246                 (vop closure-ref node block closure (incf n) (cdr loc)))))
1247           (vop setup-environment node block start-label)))
1248
1249     (unless (eq (functional-kind fun) :toplevel)
1250       (let ((vars (lambda-vars fun))
1251             (n 0))
1252         (when (leaf-refs (first vars))
1253           (emit-move node block (make-arg-count-location)
1254                      (leaf-info (first vars))))
1255         (dolist (arg (rest vars))
1256           (when (leaf-refs arg)
1257             (let ((pass (standard-arg-location n))
1258                   (home (leaf-info arg)))
1259               (if (and (lambda-var-indirect arg)
1260                        (lambda-var-explicit-value-cell arg))
1261                   (emit-make-value-cell node block pass home)
1262                   (emit-move node block pass home))))
1263           (incf n))))
1264
1265     (emit-move node block (make-old-fp-passing-location t)
1266                (ir2-physenv-old-fp env)))
1267
1268   (values))
1269
1270 ;;; Emit function prolog code. This is only called on bind nodes for
1271 ;;; functions that allocate environments. All semantics of let calls
1272 ;;; are handled by IR2-CONVERT-LET.
1273 ;;;
1274 ;;; If not an XEP, all we do is move the return PC from its passing
1275 ;;; location, since in a local call, the caller allocates the frame
1276 ;;; and sets up the arguments.
1277 (defun ir2-convert-bind (node block)
1278   (declare (type bind node) (type ir2-block block))
1279   (let* ((fun (bind-lambda node))
1280          (env (physenv-info (lambda-physenv fun))))
1281     (aver (member (functional-kind fun)
1282                   '(nil :external :optional :toplevel :cleanup)))
1283
1284     (when (xep-p fun)
1285       (init-xep-environment node block fun)
1286       #!+sb-dyncount
1287       (when *collect-dynamic-statistics*
1288         (vop count-me node block *dynamic-counts-tn*
1289              (block-number (ir2-block-block block)))))
1290
1291     (emit-move node
1292                block
1293                (ir2-physenv-return-pc-pass env)
1294                (ir2-physenv-return-pc env))
1295
1296     #!+unwind-to-frame-and-call-vop
1297     (when (and (lambda-allow-instrumenting fun)
1298                (not (lambda-inline-expanded fun))
1299                (lambda-return fun)
1300                (policy fun (>= insert-debug-catch 2)))
1301       (vop sb!vm::bind-sentinel node block))
1302
1303     (let ((lab (gen-label)))
1304       (setf (ir2-physenv-environment-start env) lab)
1305       (vop note-environment-start node block lab)
1306       #!+sb-safepoint
1307       (unless (policy fun (>= inhibit-safepoints 2))
1308         (vop sb!vm::insert-safepoint node block))))
1309
1310   (values))
1311 \f
1312 ;;;; function return
1313
1314 ;;; Do stuff to return from a function with the specified values and
1315 ;;; convention. If the return convention is :FIXED and we aren't
1316 ;;; returning from an XEP, then we do a known return (letting
1317 ;;; representation selection insert the correct move-arg VOPs.)
1318 ;;; Otherwise, we use the unknown-values convention. If there is a
1319 ;;; fixed number of return values, then use RETURN, otherwise use
1320 ;;; RETURN-MULTIPLE.
1321 (defun ir2-convert-return (node block)
1322   (declare (type creturn node) (type ir2-block block))
1323   (let* ((lvar (return-result node))
1324          (2lvar (lvar-info lvar))
1325          (lvar-kind (ir2-lvar-kind 2lvar))
1326          (fun (return-lambda node))
1327          (env (physenv-info (lambda-physenv fun)))
1328          (old-fp (ir2-physenv-old-fp env))
1329          (return-pc (ir2-physenv-return-pc env))
1330          (returns (tail-set-info (lambda-tail-set fun))))
1331     #!+unwind-to-frame-and-call-vop
1332     (when (and (lambda-allow-instrumenting fun)
1333                (not (lambda-inline-expanded fun))
1334                (policy fun (>= insert-debug-catch 2)))
1335       (vop sb!vm::unbind-sentinel node block))
1336     (cond
1337      ((and (eq (return-info-kind returns) :fixed)
1338            (not (xep-p fun)))
1339       (let ((locs (lvar-tns node block lvar
1340                                     (return-info-types returns))))
1341         (vop* known-return node block
1342               (old-fp return-pc (reference-tn-list locs nil))
1343               (nil)
1344               (return-info-locations returns))))
1345      ((eq lvar-kind :fixed)
1346       (let* ((types (mapcar #'tn-primitive-type (ir2-lvar-locs 2lvar)))
1347              (lvar-locs (lvar-tns node block lvar types))
1348              (nvals (length lvar-locs))
1349              (locs (make-standard-value-tns nvals)))
1350         (mapc (lambda (val loc)
1351                 (emit-move node block val loc))
1352               lvar-locs
1353               locs)
1354         (if (= nvals 1)
1355             (vop return-single node block old-fp return-pc (car locs))
1356             (vop* return node block
1357                   (old-fp return-pc (reference-tn-list locs nil))
1358                   (nil)
1359                   nvals))))
1360      (t
1361       (aver (eq lvar-kind :unknown))
1362       (vop* return-multiple node block
1363             (old-fp return-pc
1364                     (reference-tn-list (ir2-lvar-locs 2lvar) nil))
1365             (nil)))))
1366
1367   (values))
1368 \f
1369 ;;;; debugger hooks
1370 ;;;;
1371 ;;;; These are used by the debugger to find the top function on the
1372 ;;;; stack. They return the OLD-FP and RETURN-PC for the current
1373 ;;;; function as multiple values.
1374
1375 (defoptimizer (%caller-frame ir2-convert) (() node block)
1376   (let ((ir2-physenv (physenv-info (node-physenv node))))
1377     (move-lvar-result node block
1378                       (list (ir2-physenv-old-fp ir2-physenv))
1379                       (node-lvar node))))
1380
1381 (defoptimizer (%caller-pc ir2-convert) (() node block)
1382   (let ((ir2-physenv (physenv-info (node-physenv node))))
1383     (move-lvar-result node block
1384                       (list (ir2-physenv-return-pc ir2-physenv))
1385                       (node-lvar node))))
1386 \f
1387 ;;;; multiple values
1388
1389 ;;; This is almost identical to IR2-CONVERT-LET. Since LTN annotates
1390 ;;; the lvar for the correct number of values (with the lvar user
1391 ;;; responsible for defaulting), we can just pick them up from the
1392 ;;; lvar.
1393 (defun ir2-convert-mv-bind (node block)
1394   (declare (type mv-combination node) (type ir2-block block))
1395   (let* ((lvar (first (basic-combination-args node)))
1396          (fun (ref-leaf (lvar-uses (basic-combination-fun node))))
1397          (vars (lambda-vars fun)))
1398     (aver (eq (functional-kind fun) :mv-let))
1399     (mapc (lambda (src var)
1400             (when (leaf-refs var)
1401               (let ((dest (leaf-info var)))
1402                 (if (and (lambda-var-indirect var)
1403                          (lambda-var-explicit-value-cell var))
1404                     (emit-make-value-cell node block src dest)
1405                     (emit-move node block src dest)))))
1406           (lvar-tns node block lvar
1407                             (mapcar (lambda (x)
1408                                       (primitive-type (leaf-type x)))
1409                                     vars))
1410           vars))
1411   (values))
1412
1413 ;;; Emit the appropriate fixed value, unknown value or tail variant of
1414 ;;; CALL-VARIABLE. Note that we only need to pass the values start for
1415 ;;; the first argument: all the other argument lvar TNs are
1416 ;;; ignored. This is because we require all of the values globs to be
1417 ;;; contiguous and on stack top.
1418 (defun ir2-convert-mv-call (node block)
1419   (declare (type mv-combination node) (type ir2-block block))
1420   (aver (basic-combination-args node))
1421   (let* ((start-lvar (lvar-info (first (basic-combination-args node))))
1422          (start (first (ir2-lvar-locs start-lvar)))
1423          (tails (and (node-tail-p node)
1424                      (lambda-tail-set (node-home-lambda node))))
1425          (lvar (node-lvar node))
1426          (2lvar (and lvar (lvar-info lvar))))
1427     (multiple-value-bind (fun named)
1428         (fun-lvar-tn node block (basic-combination-fun node))
1429       (aver (and (not named)
1430                  (eq (ir2-lvar-kind start-lvar) :unknown)))
1431       (cond
1432        (tails
1433         (let ((env (physenv-info (node-physenv node))))
1434           (vop tail-call-variable node block start fun
1435                (ir2-physenv-old-fp env)
1436                (ir2-physenv-return-pc env))))
1437        ((and 2lvar
1438              (eq (ir2-lvar-kind 2lvar) :unknown))
1439         (vop* multiple-call-variable node block (start fun nil)
1440               ((reference-tn-list (ir2-lvar-locs 2lvar) t))
1441               (emit-step-p node)))
1442        (t
1443         (let ((locs (standard-result-tns lvar)))
1444           (vop* call-variable node block (start fun nil)
1445                 ((reference-tn-list locs t)) (length locs)
1446                 (emit-step-p node))
1447           (move-lvar-result node block locs lvar)))))))
1448
1449 ;;; Reset the stack pointer to the start of the specified
1450 ;;; unknown-values lvar (discarding it and all values globs on top of
1451 ;;; it.)
1452 (defoptimizer (%pop-values ir2-convert) ((%lvar) node block)
1453   (let* ((lvar (lvar-value %lvar))
1454          (2lvar (lvar-info lvar)))
1455     (cond ((eq (ir2-lvar-kind 2lvar) :unknown)
1456            (vop reset-stack-pointer node block
1457                 (first (ir2-lvar-locs 2lvar))))
1458           ((lvar-dynamic-extent lvar)
1459            (vop reset-stack-pointer node block
1460                 (ir2-lvar-stack-pointer 2lvar)))
1461           (t (bug "Trying to pop a not stack-allocated LVAR ~S."
1462                   lvar)))))
1463
1464 (defoptimizer (%nip-values ir2-convert) ((last-nipped last-preserved
1465                                                       &rest moved)
1466                                          node block)
1467   (let* ( ;; pointer immediately after the nipped block
1468          (after (lvar-value last-nipped))
1469          (2after (lvar-info after))
1470          ;; pointer to the first nipped word
1471          (first (lvar-value last-preserved))
1472          (2first (lvar-info first))
1473
1474          (moved-tns (loop for lvar-ref in moved
1475                           for lvar = (lvar-value lvar-ref)
1476                           for 2lvar = (lvar-info lvar)
1477                                         ;when 2lvar
1478                           collect (first (ir2-lvar-locs 2lvar)))))
1479     (aver (or (eq (ir2-lvar-kind 2after) :unknown)
1480               (lvar-dynamic-extent after)))
1481     (aver (eq (ir2-lvar-kind 2first) :unknown))
1482     (when *check-consistency*
1483       ;; we cannot move stack-allocated DX objects
1484       (dolist (moved-lvar moved)
1485         (aver (eq (ir2-lvar-kind (lvar-info (lvar-value moved-lvar)))
1486                   :unknown))))
1487     (flet ((nip-aligned (nipped)
1488              (vop* %%nip-values node block
1489                    (nipped
1490                     (first (ir2-lvar-locs 2first))
1491                     (reference-tn-list moved-tns nil))
1492                    ((reference-tn-list moved-tns t)))))
1493       (cond ((eq (ir2-lvar-kind 2after) :unknown)
1494              (nip-aligned (first (ir2-lvar-locs 2after))))
1495             ((lvar-dynamic-extent after)
1496              (nip-aligned (ir2-lvar-stack-pointer 2after)))
1497             (t
1498              (bug "Trying to nip a not stack-allocated LVAR ~S." after))))))
1499
1500 ;;; Deliver the values TNs to LVAR using MOVE-LVAR-RESULT.
1501 (defoptimizer (values ir2-convert) ((&rest values) node block)
1502   (let ((tns (mapcar (lambda (x)
1503                        (lvar-tn node block x))
1504                      values)))
1505     (move-lvar-result node block tns (node-lvar node))))
1506
1507 ;;; In the normal case where unknown values are desired, we use the
1508 ;;; VALUES-LIST VOP. In the relatively unimportant case of VALUES-LIST
1509 ;;; for a fixed number of values, we punt by doing a full call to the
1510 ;;; VALUES-LIST function. This gets the full call VOP to deal with
1511 ;;; defaulting any unsupplied values. It seems unworthwhile to
1512 ;;; optimize this case.
1513 (defoptimizer (values-list ir2-convert) ((list) node block)
1514   (let* ((lvar (node-lvar node))
1515          (2lvar (and lvar (lvar-info lvar))))
1516     (cond ((and 2lvar
1517                 (eq (ir2-lvar-kind 2lvar) :unknown))
1518            (let ((locs (ir2-lvar-locs 2lvar)))
1519              (vop* values-list node block
1520                    ((lvar-tn node block list) nil)
1521                    ((reference-tn-list locs t)))))
1522           (t (aver (or (not 2lvar) ; i.e. we want to check the argument
1523                        (eq (ir2-lvar-kind 2lvar) :fixed)))
1524              (ir2-convert-full-call node block)))))
1525
1526 (defoptimizer (%more-arg-values ir2-convert) ((context start count) node block)
1527   (binding* ((lvar (node-lvar node) :exit-if-null)
1528              (2lvar (lvar-info lvar)))
1529     (ecase (ir2-lvar-kind 2lvar)
1530       (:fixed
1531        ;; KLUDGE: this is very much unsafe, and can leak random stack values.
1532        ;; OTOH, I think the :FIXED case can only happen with (safety 0) in the
1533        ;; first place.
1534        ;;  -PK
1535        (loop for loc in (ir2-lvar-locs 2lvar)
1536              for idx upfrom 0
1537              do (vop sb!vm::more-arg node block
1538                      (lvar-tn node block context)
1539                      (emit-constant idx)
1540                      loc)))
1541       (:unknown
1542        (let ((locs (ir2-lvar-locs 2lvar)))
1543          (vop* %more-arg-values node block
1544                ((lvar-tn node block context)
1545                 (lvar-tn node block start)
1546                 (lvar-tn node block count)
1547                 nil)
1548                ((reference-tn-list locs t))))))))
1549 \f
1550 ;;;; special binding
1551
1552 ;;; This is trivial, given our assumption of a shallow-binding
1553 ;;; implementation.
1554 (defoptimizer (%special-bind ir2-convert) ((var value) node block)
1555   (let ((name (leaf-source-name (lvar-value var))))
1556     (vop bind node block (lvar-tn node block value)
1557          (emit-constant name))))
1558 (defoptimizer (%special-unbind ir2-convert) ((var) node block)
1559   (vop unbind node block))
1560
1561 ;;; ### It's not clear that this really belongs in this file, or
1562 ;;; should really be done this way, but this is the least violation of
1563 ;;; abstraction in the current setup. We don't want to wire
1564 ;;; shallow-binding assumptions into IR1tran.
1565 (def-ir1-translator progv
1566     ((vars vals &body body) start next result)
1567   (ir1-convert
1568    start next result
1569    (with-unique-names (bind unbind)
1570      (once-only ((n-save-bs '(%primitive current-binding-pointer)))
1571        `(unwind-protect
1572              (progn
1573                (labels ((,unbind (vars)
1574                           (declare (optimize (speed 2) (debug 0)))
1575                           (let ((unbound-marker (%primitive make-unbound-marker)))
1576                             (dolist (var vars)
1577                               ;; CLHS says "bound and then made to have no value" -- user
1578                               ;; should not be able to tell the difference between that and this.
1579                               (about-to-modify-symbol-value var 'progv)
1580                               (%primitive bind unbound-marker var))))
1581                         (,bind (vars vals)
1582                           (declare (optimize (speed 2) (debug 0)
1583                                              (insert-debug-catch 0)))
1584                           (cond ((null vars))
1585                                 ((null vals) (,unbind vars))
1586                                 (t
1587                                  (let ((val (car vals))
1588                                        (var (car vars)))
1589                                    (about-to-modify-symbol-value var 'progv val t)
1590                                    (%primitive bind val var))
1591                                  (,bind (cdr vars) (cdr vals))))))
1592                  (,bind ,vars ,vals))
1593                nil
1594                ,@body)
1595           ;; Technically ANSI CL doesn't allow declarations at the
1596           ;; start of the cleanup form. SBCL happens to allow for
1597           ;; them, due to the way the UNWIND-PROTECT ir1 translation
1598           ;; is implemented; the cleanup forms are directly spliced
1599           ;; into an FLET definition body. And a declaration here
1600           ;; actually has exactly the right scope for what we need
1601           ;; (ensure that debug instrumentation is not emitted for the
1602           ;; cleanup function). -- JES, 2007-06-16
1603           (declare (optimize (insert-debug-catch 0)))
1604           (%primitive unbind-to-here ,n-save-bs))))))
1605 \f
1606 ;;;; non-local exit
1607
1608 ;;; Convert a non-local lexical exit. First find the NLX-INFO in our
1609 ;;; environment. Note that this is never called on the escape exits
1610 ;;; for CATCH and UNWIND-PROTECT, since the escape functions aren't
1611 ;;; IR2 converted.
1612 (defun ir2-convert-exit (node block)
1613   (declare (type exit node) (type ir2-block block))
1614   (let* ((nlx (exit-nlx-info node))
1615          (loc (find-in-physenv nlx (node-physenv node)))
1616          (temp (make-stack-pointer-tn))
1617          (value (exit-value node)))
1618     (if (nlx-info-safe-p nlx)
1619         (vop value-cell-ref node block loc temp)
1620         (emit-move node block loc temp))
1621     (if value
1622         (let ((locs (ir2-lvar-locs (lvar-info value))))
1623           (vop unwind node block temp (first locs) (second locs)))
1624         (let ((0-tn (emit-constant 0)))
1625           (vop unwind node block temp 0-tn 0-tn))))
1626
1627   (values))
1628
1629 ;;; %CLEANUP-POINT doesn't do anything except prevent the body from
1630 ;;; being entirely deleted.
1631 (defoptimizer (%cleanup-point ir2-convert) (() node block) node block)
1632
1633 ;;; This function invalidates a lexical exit on exiting from the
1634 ;;; dynamic extent. This is done by storing 0 into the indirect value
1635 ;;; cell that holds the closed unwind block.
1636 (defoptimizer (%lexical-exit-breakup ir2-convert) ((info) node block)
1637   (let ((nlx (lvar-value info)))
1638     (when (nlx-info-safe-p nlx)
1639       (vop value-cell-set node block
1640            (find-in-physenv nlx (node-physenv node))
1641            (emit-constant 0)))))
1642
1643 ;;; We have to do a spurious move of no values to the result lvar so
1644 ;;; that lifetime analysis won't get confused.
1645 (defun ir2-convert-throw (node block)
1646   (declare (type mv-combination node) (type ir2-block block))
1647   (let ((args (basic-combination-args node)))
1648     (check-catch-tag-type (first args))
1649     (vop* throw node block
1650           ((lvar-tn node block (first args))
1651            (reference-tn-list
1652             (ir2-lvar-locs (lvar-info (second args)))
1653             nil))
1654           (nil)))
1655   (move-lvar-result node block () (node-lvar node))
1656   (values))
1657
1658 ;;; Emit code to set up a non-local exit. INFO is the NLX-INFO for the
1659 ;;; exit, and TAG is the lvar for the catch tag (if any.) We get at
1660 ;;; the target PC by passing in the label to the vop. The vop is
1661 ;;; responsible for building a return-PC object.
1662 (defun emit-nlx-start (node block info tag)
1663   (declare (type node node) (type ir2-block block) (type nlx-info info)
1664            (type (or lvar null) tag))
1665   (let* ((2info (nlx-info-info info))
1666          (kind (cleanup-kind (nlx-info-cleanup info)))
1667          (block-tn (physenv-live-tn
1668                     (make-normal-tn (primitive-type-or-lose 'catch-block))
1669                     (node-physenv node)))
1670          (res (make-stack-pointer-tn))
1671          (target-label (ir2-nlx-info-target 2info)))
1672
1673     (vop current-binding-pointer node block
1674          (car (ir2-nlx-info-dynamic-state 2info)))
1675     (vop* save-dynamic-state node block
1676           (nil)
1677           ((reference-tn-list (cdr (ir2-nlx-info-dynamic-state 2info)) t)))
1678     (vop current-stack-pointer node block (ir2-nlx-info-save-sp 2info))
1679
1680     (ecase kind
1681       (:catch
1682        (vop make-catch-block node block block-tn
1683             (lvar-tn node block tag) target-label res))
1684       ((:unwind-protect :block :tagbody)
1685        (vop make-unwind-block node block block-tn target-label res)))
1686
1687     (ecase kind
1688       ((:block :tagbody)
1689        (if (nlx-info-safe-p info)
1690            (emit-make-value-cell node block res (ir2-nlx-info-home 2info))
1691            (emit-move node block res (ir2-nlx-info-home 2info))))
1692       (:unwind-protect
1693        (vop set-unwind-protect node block block-tn))
1694       (:catch)))
1695
1696   (values))
1697
1698 ;;; Scan each of ENTRY's exits, setting up the exit for each lexical exit.
1699 (defun ir2-convert-entry (node block)
1700   (declare (type entry node) (type ir2-block block))
1701   (let ((nlxes '()))
1702     (dolist (exit (entry-exits node))
1703       (let ((info (exit-nlx-info exit)))
1704         (when (and info
1705                    (not (memq info nlxes))
1706                    (member (cleanup-kind (nlx-info-cleanup info))
1707                            '(:block :tagbody)))
1708           (push info nlxes)
1709           (emit-nlx-start node block info nil)))))
1710   (values))
1711
1712 ;;; Set up the unwind block for these guys.
1713 (defoptimizer (%catch ir2-convert) ((info-lvar tag) node block)
1714   (check-catch-tag-type tag)
1715   (emit-nlx-start node block (lvar-value info-lvar) tag))
1716 (defoptimizer (%unwind-protect ir2-convert) ((info-lvar cleanup) node block)
1717   (emit-nlx-start node block (lvar-value info-lvar) nil))
1718
1719 ;;; Emit the entry code for a non-local exit. We receive values and
1720 ;;; restore dynamic state.
1721 ;;;
1722 ;;; In the case of a lexical exit or CATCH, we look at the exit lvar's
1723 ;;; kind to determine which flavor of entry VOP to emit. If unknown
1724 ;;; values, emit the xxx-MULTIPLE variant to the lvar locs. If fixed
1725 ;;; values, make the appropriate number of temps in the standard
1726 ;;; values locations and use the other variant, delivering the temps
1727 ;;; to the lvar using MOVE-LVAR-RESULT.
1728 ;;;
1729 ;;; In the UNWIND-PROTECT case, we deliver the first register
1730 ;;; argument, the argument count and the argument pointer to our lvar
1731 ;;; as multiple values. These values are the block exited to and the
1732 ;;; values start and count.
1733 ;;;
1734 ;;; After receiving values, we restore dynamic state. Except in the
1735 ;;; UNWIND-PROTECT case, the values receiving restores the stack
1736 ;;; pointer. In an UNWIND-PROTECT cleanup, we want to leave the stack
1737 ;;; pointer alone, since the thrown values are still out there.
1738 (defoptimizer (%nlx-entry ir2-convert) ((info-lvar) node block)
1739   (let* ((info (lvar-value info-lvar))
1740          (lvar (node-lvar node))
1741          (2info (nlx-info-info info))
1742          (top-loc (ir2-nlx-info-save-sp 2info))
1743          (start-loc (make-nlx-entry-arg-start-location))
1744          (count-loc (make-arg-count-location))
1745          (target (ir2-nlx-info-target 2info)))
1746
1747     (ecase (cleanup-kind (nlx-info-cleanup info))
1748       ((:catch :block :tagbody)
1749        (let ((2lvar (and lvar (lvar-info lvar))))
1750          (if (and 2lvar (eq (ir2-lvar-kind 2lvar) :unknown))
1751              (vop* nlx-entry-multiple node block
1752                    (top-loc start-loc count-loc nil)
1753                    ((reference-tn-list (ir2-lvar-locs 2lvar) t))
1754                    target)
1755              (let ((locs (standard-result-tns lvar)))
1756                (vop* nlx-entry node block
1757                      (top-loc start-loc count-loc nil)
1758                      ((reference-tn-list locs t))
1759                      target
1760                      (length locs))
1761                (move-lvar-result node block locs lvar)))))
1762       (:unwind-protect
1763        (let ((block-loc (standard-arg-location 0)))
1764          (vop uwp-entry node block target block-loc start-loc count-loc)
1765          (move-lvar-result
1766           node block
1767           (list block-loc start-loc count-loc)
1768           lvar))))
1769
1770     #!+sb-dyncount
1771     (when *collect-dynamic-statistics*
1772       (vop count-me node block *dynamic-counts-tn*
1773            (block-number (ir2-block-block block))))
1774
1775     (vop* restore-dynamic-state node block
1776           ((reference-tn-list (cdr (ir2-nlx-info-dynamic-state 2info)) nil))
1777           (nil))
1778     (vop unbind-to-here node block
1779          (car (ir2-nlx-info-dynamic-state 2info)))))
1780 \f
1781 ;;;; n-argument functions
1782
1783 (macrolet ((def (name)
1784              `(defoptimizer (,name ir2-convert) ((&rest args) node block)
1785                 (let* ((refs (move-tail-full-call-args node block))
1786                        (lvar (node-lvar node))
1787                        (res (lvar-result-tns
1788                              lvar
1789                              (list (primitive-type (specifier-type 'list))))))
1790                   (when (and lvar (lvar-dynamic-extent lvar))
1791                     (vop current-stack-pointer node block
1792                          (ir2-lvar-stack-pointer (lvar-info lvar))))
1793                   (vop* ,name node block (refs) ((first res) nil)
1794                         (length args))
1795                   (move-lvar-result node block res lvar)))))
1796   (def list)
1797   (def list*))
1798
1799 \f
1800 (defoptimizer (mask-signed-field ir2-convert) ((width x) node block)
1801   (block nil
1802     (when (constant-lvar-p width)
1803       (case (lvar-value width)
1804         (#.(- sb!vm:n-word-bits sb!vm:n-fixnum-tag-bits)
1805          (when (or (csubtypep (lvar-type x)
1806                               (specifier-type 'word))
1807                    (csubtypep (lvar-type x)
1808                               (specifier-type 'sb!vm:signed-word)))
1809            (let* ((lvar (node-lvar node))
1810                   (temp (make-normal-tn
1811                          (if (csubtypep (lvar-type x)
1812                                         (specifier-type 'word))
1813                              (primitive-type-of most-positive-word)
1814                              (primitive-type-of
1815                               (- (ash most-positive-word -1))))))
1816                   (results (lvar-result-tns
1817                             lvar
1818                             (list (primitive-type-or-lose 'fixnum)))))
1819              (emit-move node block (lvar-tn node block x) temp)
1820              (vop sb!vm::move-from-word/fixnum node block
1821                   temp (first results))
1822              (move-lvar-result node block results lvar)
1823              (return))))
1824         (#.sb!vm:n-word-bits
1825          (when (csubtypep (lvar-type x) (specifier-type 'word))
1826            (let* ((lvar (node-lvar node))
1827                   (temp (make-normal-tn
1828                          (primitive-type-of most-positive-word)))
1829                   (results (lvar-result-tns
1830                             lvar
1831                             (list (primitive-type
1832                                    (specifier-type 'sb!vm:signed-word))))))
1833              (emit-move node block (lvar-tn node block x) temp)
1834              (vop sb!vm::word-move node block
1835                   temp (first results))
1836              (move-lvar-result node block results lvar)
1837              (return))))))
1838     (if (template-p (basic-combination-info node))
1839         (ir2-convert-template node block)
1840         (ir2-convert-full-call node block))))
1841 \f
1842 ;;; Convert the code in a component into VOPs.
1843 (defun ir2-convert (component)
1844   (declare (type component component))
1845   (let (#!+sb-dyncount
1846         (*dynamic-counts-tn*
1847          (when *collect-dynamic-statistics*
1848            (let* ((blocks
1849                    (block-number (block-next (component-head component))))
1850                   (counts (make-array blocks
1851                                       :element-type '(unsigned-byte 32)
1852                                       :initial-element 0))
1853                   (info (make-dyncount-info
1854                          :for (component-name component)
1855                          :costs (make-array blocks
1856                                             :element-type '(unsigned-byte 32)
1857                                             :initial-element 0)
1858                          :counts counts)))
1859              (setf (ir2-component-dyncount-info (component-info component))
1860                    info)
1861              (emit-constant info)
1862              (emit-constant counts)))))
1863     (let ((num 0))
1864       (declare (type index num))
1865       (do-ir2-blocks (2block component)
1866         (let ((block (ir2-block-block 2block)))
1867           (when (block-start block)
1868             (setf (block-number block) num)
1869             #!+sb-dyncount
1870             (when *collect-dynamic-statistics*
1871               (let ((first-node (block-start-node block)))
1872                 (unless (or (and (bind-p first-node)
1873                                  (xep-p (bind-lambda first-node)))
1874                             (eq (lvar-fun-name
1875                                  (node-lvar first-node))
1876                                 '%nlx-entry))
1877                   (vop count-me
1878                        first-node
1879                        2block
1880                        #!+sb-dyncount *dynamic-counts-tn* #!-sb-dyncount nil
1881                        num))))
1882               #!+sb-safepoint
1883               (let ((first-node (block-start-node block)))
1884                 (unless (or (and (bind-p first-node)
1885                                  (xep-p (bind-lambda first-node)))
1886                             (and (valued-node-p first-node)
1887                                  (node-lvar first-node)
1888                                  (eq (lvar-fun-name
1889                                       (node-lvar first-node))
1890                                      '%nlx-entry)))
1891                   (when (and (rest (block-pred block))
1892                              (block-loop block)
1893                              (member (loop-kind (block-loop block))
1894                                      '(:natural :strange))
1895                              (eq block (loop-head (block-loop block)))
1896                              (policy first-node (< inhibit-safepoints 2)))
1897                     (vop sb!vm::insert-safepoint first-node 2block))))
1898             (ir2-convert-block block)
1899             (incf num))))))
1900   (values))
1901
1902 ;;; If necessary, emit a terminal unconditional branch to go to the
1903 ;;; successor block. If the successor is the component tail, then
1904 ;;; there isn't really any successor, but if the end is a non-tail
1905 ;;; call to a function that's not *known* to never return, then we
1906 ;;; emit an error trap just in case the function really does return.
1907 ;;;
1908 ;;; Trapping after known calls makes it easier to understand type
1909 ;;; derivation bugs at runtime: they show up as nil-fun-returned-error,
1910 ;;; rather than the execution of arbitrary code or error traps.
1911 (defun finish-ir2-block (block)
1912   (declare (type cblock block))
1913   (let* ((2block (block-info block))
1914          (last (block-last block))
1915          (succ (block-succ block)))
1916     (unless (if-p last)
1917       (aver (singleton-p succ))
1918       (let ((target (first succ)))
1919         (cond ((eq target (component-tail (block-component block)))
1920                (when (and (basic-combination-p last)
1921                           (or (eq (basic-combination-kind last) :full)
1922                               (and (eq (basic-combination-kind last) :known)
1923                                    (eq (basic-combination-info last) :full))))
1924                  (let* ((fun (basic-combination-fun last))
1925                         (use (lvar-uses fun))
1926                         (name (and (ref-p use)
1927                                    (leaf-has-source-name-p (ref-leaf use))
1928                                    (leaf-source-name (ref-leaf use))))
1929                         (ftype (and (info :function :info name) ; only use the FTYPE if
1930                                     (info :function :type name)))) ; NAME was DEFKNOWN
1931                    (unless (or (node-tail-p last)
1932                                (policy last (zerop safety))
1933                                (and (fun-type-p ftype)
1934                                     (eq *empty-type* (fun-type-returns ftype))))
1935                      (vop nil-fun-returned-error last 2block
1936                           (if name
1937                               (emit-constant name)
1938                               (multiple-value-bind (tn named)
1939                                   (fun-lvar-tn last 2block fun)
1940                                 (aver (not named))
1941                                 tn)))))))
1942               ((not (eq (ir2-block-next 2block) (block-info target)))
1943                (vop branch last 2block (block-label target)))
1944               (t
1945                (register-drop-thru target))))))
1946
1947   (values))
1948
1949 ;;; Convert the code in a block into VOPs.
1950 (defun ir2-convert-block (block)
1951   (declare (type cblock block))
1952   (let ((2block (block-info block)))
1953     (do-nodes (node lvar block)
1954       (etypecase node
1955         (ref
1956          (when lvar
1957            (let ((2lvar (lvar-info lvar)))
1958              ;; function REF in a local call is not annotated
1959              (when (and 2lvar (not (eq (ir2-lvar-kind 2lvar) :delayed)))
1960                (ir2-convert-ref node 2block)))))
1961         (combination
1962          (let ((kind (basic-combination-kind node)))
1963            (ecase kind
1964              (:local
1965               (ir2-convert-local-call node 2block))
1966              (:full
1967               (ir2-convert-full-call node 2block))
1968              (:known
1969               (let* ((info (basic-combination-fun-info node))
1970                      (fun (fun-info-ir2-convert info)))
1971                 (cond (fun
1972                        (funcall fun node 2block))
1973                       ((eq (basic-combination-info node) :full)
1974                        (ir2-convert-full-call node 2block))
1975                       (t
1976                        (ir2-convert-template node 2block))))))))
1977         (cif
1978          (when (lvar-info (if-test node))
1979            (ir2-convert-if node 2block)))
1980         (bind
1981          (let ((fun (bind-lambda node)))
1982            (when (eq (lambda-home fun) fun)
1983              (ir2-convert-bind node 2block))))
1984         (creturn
1985          (ir2-convert-return node 2block))
1986         (cset
1987          (ir2-convert-set node 2block))
1988         (cast
1989          (ir2-convert-cast node 2block))
1990         (mv-combination
1991          (cond
1992            ((eq (basic-combination-kind node) :local)
1993             (ir2-convert-mv-bind node 2block))
1994            ((eq (lvar-fun-name (basic-combination-fun node))
1995                 '%throw)
1996             (ir2-convert-throw node 2block))
1997            (t
1998             (ir2-convert-mv-call node 2block))))
1999         (exit
2000          (when (exit-entry node)
2001            (ir2-convert-exit node 2block)))
2002         (entry
2003          (ir2-convert-entry node 2block)))))
2004
2005   (finish-ir2-block block)
2006
2007   (values))