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