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