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