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