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