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