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