0.6.8.9:
[sbcl.git] / src / compiler / byte-comp.lisp
1 ;;;; that part of the byte compiler which exists not only in the
2 ;;;; target Lisp, but also in the cross-compilation host Lisp
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 ;;;; the fasl file format that we use
16 (defconstant byte-fasl-file-version 1)
17
18 ;;; ### remaining work:
19 ;;;
20 ;;; - add more inline operations.
21 ;;; - Breakpoints/debugging info.
22 \f
23 ;;;; stuff to emit noise
24
25 ;;; Note: We use the regular assembler, but we don't use any
26 ;;; ``instructions'' because there is no way to keep our byte-code
27 ;;; instructions separate from the instructions used by the native
28 ;;; backend. Besides, we don't want to do any scheduling or anything
29 ;;; like that, anyway.
30
31 #!-sb-fluid (declaim (inline output-byte))
32 (defun output-byte (segment byte)
33   (declare (type sb!assem:segment segment)
34            (type (unsigned-byte 8) byte))
35   (sb!assem:emit-byte segment byte))
36
37 ;;; Output OPERAND as 1 or 4 bytes, using #xFF as the extend code.
38 (defun output-extended-operand (segment operand)
39   (declare (type (unsigned-byte 24) operand))
40   (cond ((<= operand 254)
41          (output-byte segment operand))
42         (t
43          (output-byte segment #xFF)
44          (output-byte segment (ldb (byte 8 16) operand))
45          (output-byte segment (ldb (byte 8 8) operand))
46          (output-byte segment (ldb (byte 8 0) operand)))))
47
48 ;;; Output a byte, logior'ing in a 4 bit immediate constant. If that
49 ;;; immediate won't fit, then emit it as the next 1-4 bytes.
50 (defun output-byte-with-operand (segment byte operand)
51   (declare (type sb!assem:segment segment)
52            (type (unsigned-byte 8) byte)
53            (type (unsigned-byte 24) operand))
54   (cond ((<= operand 14)
55          (output-byte segment (logior byte operand)))
56         (t
57          (output-byte segment (logior byte 15))
58          (output-extended-operand segment operand)))
59   (values))
60
61 (defun output-label (segment label)
62   (declare (type sb!assem:segment segment)
63            (type sb!assem:label label))
64   (sb!assem:assemble (segment)
65     (sb!assem:emit-label label)))
66
67 ;;; Output a reference to LABEL.
68 (defun output-reference (segment label)
69   (declare (type sb!assem:segment segment)
70            (type sb!assem:label label))
71   (sb!assem:emit-back-patch
72    segment
73    3
74    #'(lambda (segment posn)
75        (declare (type sb!assem:segment segment)
76                 (ignore posn))
77        (let ((target (sb!assem:label-position label)))
78          (assert (<= 0 target (1- (ash 1 24))))
79          (output-byte segment (ldb (byte 8 16) target))
80          (output-byte segment (ldb (byte 8 8) target))
81          (output-byte segment (ldb (byte 8 0) target))))))
82
83 ;;; Output some branch byte-sequence.
84 (defun output-branch (segment kind label)
85   (declare (type sb!assem:segment segment)
86            (type (unsigned-byte 8) kind)
87            (type sb!assem:label label))
88   (sb!assem:emit-chooser
89    segment 4 1
90    #'(lambda (segment posn delta)
91        (when (<= (- (ash 1 7))
92                  (- (sb!assem:label-position label posn delta) posn 2)
93                  (1- (ash 1 7)))
94          (sb!assem:emit-chooser
95           segment 2 1
96           #'(lambda (segment posn delta)
97               (declare (ignore segment) (type index posn delta))
98               (when (zerop (- (sb!assem:label-position label posn delta)
99                               posn 2))
100                 ;; Don't emit anything, because the branch is to the following
101                 ;; instruction.
102                 t))
103           #'(lambda (segment posn)
104               ;; We know that we fit in one byte.
105               (declare (type sb!assem:segment segment)
106                        (type index posn))
107               (output-byte segment (logior kind 1))
108               (output-byte segment
109                            (ldb (byte 8 0)
110                                 (- (sb!assem:label-position label) posn 2)))))
111          t))
112    #'(lambda (segment posn)
113        (declare (type sb!assem:segment segment)
114                 (ignore posn))
115        (let ((target (sb!assem:label-position label)))
116          (assert (<= 0 target (1- (ash 1 24))))
117          (output-byte segment kind)
118          (output-byte segment (ldb (byte 8 16) target))
119          (output-byte segment (ldb (byte 8 8) target))
120          (output-byte segment (ldb (byte 8 0) target))))))
121 \f
122 ;;;; system constants, Xops, and inline functions
123
124 ;;; If (%FDEFINITION-MARKER% . NAME) is a key in the table, then the
125 ;;; corresponding value is the byte code fdefinition.
126 (eval-when (:compile-toplevel :load-toplevel :execute)
127   (defvar *system-constant-codes* (make-hash-table :test 'equal)))
128
129 (eval-when (:compile-toplevel :load-toplevel :execute)
130   (flet ((def-system-constant (index form)
131            (setf (gethash form *system-constant-codes*) index)))
132     (def-system-constant 0 nil)
133     (def-system-constant 1 t)
134     (def-system-constant 2 :start)
135     (def-system-constant 3 :end)
136     (def-system-constant 4 :test)
137     (def-system-constant 5 :count)
138     (def-system-constant 6 :test-not)
139     (def-system-constant 7 :key)
140     (def-system-constant 8 :from-end)
141     (def-system-constant 9 :type)
142     (def-system-constant 10 '(%fdefinition-marker% . error))
143     (def-system-constant 11 '(%fdefinition-marker% . format))
144     (def-system-constant 12 '(%fdefinition-marker% . %typep))
145     (def-system-constant 13 '(%fdefinition-marker% . eql))
146     (def-system-constant 14 '(%fdefinition-marker% . %negate))
147     (def-system-constant 15 '(%fdefinition-marker% . %%defun))
148     (def-system-constant 16 '(%fdefinition-marker% . %%defmacro))
149     (def-system-constant 17 '(%fdefinition-marker% . %%defconstant))
150     (def-system-constant 18 '(%fdefinition-marker% . length))
151     (def-system-constant 19 '(%fdefinition-marker% . equal))
152     (def-system-constant 20 '(%fdefinition-marker% . append))
153     (def-system-constant 21 '(%fdefinition-marker% . reverse))
154     (def-system-constant 22 '(%fdefinition-marker% . nreverse))
155     (def-system-constant 23 '(%fdefinition-marker% . nconc))
156     (def-system-constant 24 '(%fdefinition-marker% . list))
157     (def-system-constant 25 '(%fdefinition-marker% . list*))
158     (def-system-constant 26 '(%fdefinition-marker% . %coerce-name-to-function))
159     (def-system-constant 27 '(%fdefinition-marker% . values-list))))
160
161 (eval-when (#+sb-xc :compile-toplevel :load-toplevel :execute)
162
163 (defparameter *xop-names*
164   '(breakpoint; 0
165     dup; 1
166     type-check; 2
167     fdefn-function-or-lose; 3
168     default-unknown-values; 4
169     push-n-under; 5
170     xop6
171     xop7
172     merge-unknown-values
173     make-closure
174     throw
175     catch
176     breakup
177     return-from
178     tagbody
179     go
180     unwind-protect))
181
182 (defun xop-index-or-lose (name)
183   (or (position name *xop-names* :test #'eq)
184       (error "unknown XOP ~S" name)))
185
186 ) ; EVAL-WHEN
187
188 ;;; FIXME: The hardwired 32 here (found also in (MOD 32) above, and in
189 ;;; the number of bits tested in EXPAND-INTO-INLINES, and perhaps
190 ;;; elsewhere) is ugly. There should be some symbolic constant for the
191 ;;; number of bits devoted to coding byte-inline functions.
192 (eval-when (:compile-toplevel :load-toplevel :execute)
193
194   (defstruct inline-function-info
195     ;; the name of the function that we convert into calls to this
196     (function (required-argument) :type symbol)
197     ;; the name of the function that the interpreter should call to
198     ;; implement this. This may not be the same as the FUNCTION slot
199     ;; value if extra safety checks are required.
200     (interpreter-function (required-argument) :type symbol)
201     ;; the inline operation number, i.e. the byte value actually
202     ;; written into byte-compiled code
203     (number (required-argument) :type (mod 32))
204     ;; the type that calls must satisfy
205     (type (required-argument) :type function-type)
206     ;; Can we skip type checking of the arguments?
207     (safe (required-argument) :type boolean))
208
209   (defparameter *inline-functions* (make-array 32 :initial-element nil))
210   (defparameter *inline-function-table* (make-hash-table :test 'eq))
211   (let ((number 0))
212     (dolist (stuff
213              '((+ (fixnum fixnum) fixnum)
214                (- (fixnum fixnum) fixnum)
215                (make-value-cell (t) t)
216                (value-cell-ref (t) t)
217                (value-cell-setf (t t) (values))
218                (symbol-value (symbol) t
219                              :interpreter-function %byte-symbol-value)
220                (setf-symbol-value (t symbol) (values))
221                (%byte-special-bind (t symbol) (values))
222                (%byte-special-unbind () (values))
223                (cons-unique-tag () t)   ; obsolete...
224                (%negate (fixnum) fixnum)
225                (< (fixnum fixnum) t)
226                (> (fixnum fixnum) t)
227                (car (t) t :interpreter-function %byte-car :safe t)
228                (cdr (t) t :interpreter-function %byte-cdr :safe t)
229                (length (list) t)
230                (cons (t t) t)
231                (list (t t) t)
232                (list* (t t t) t)
233                (%instance-ref (t t) t)
234                (%setf-instance-ref (t t t) (values))))
235       (destructuring-bind
236           (name arg-types result-type
237                 &key (interpreter-function name) alias safe)
238           stuff
239         (let ((info
240                (make-inline-function-info
241                 :function name
242                 :number number
243                 :interpreter-function interpreter-function
244                 :type (specifier-type `(function ,arg-types ,result-type))
245                 :safe safe)))
246           (setf (svref *inline-functions* number) info)
247           (setf (gethash name *inline-function-table*) info))
248         (unless alias (incf number))))))
249
250 (defun inline-function-number-or-lose (function)
251   (let ((info (gethash function *inline-function-table*)))
252     (if info
253         (inline-function-info-number info)
254         (error "unknown inline function: ~S" function))))
255 \f
256 ;;;; transforms which are specific to byte code
257
258 ;;; It appears that the idea here is that in byte code, EQ is more
259 ;;; efficient than CHAR=. -- WHN 199910
260
261 (deftransform eql ((x y) ((or fixnum character) (or fixnum character))
262                    * :when :byte)
263   '(eq x y))
264
265 (deftransform char= ((x y) * * :when :byte)
266   '(eq x y))
267 \f
268 ;;;; annotations hung off the IR1 while compiling
269
270 (defstruct byte-component-info
271   (constants (make-array 10 :adjustable t :fill-pointer 0)))
272
273 (defstruct byte-lambda-info
274   (label nil :type (or null label))
275   (stack-size 0 :type index)
276   ;; FIXME: should be INTERESTING-P T :TYPE BOOLEAN
277   (interesting t :type (member t nil)))
278
279 (defun block-interesting (block)
280   (byte-lambda-info-interesting (lambda-info (block-home-lambda block))))
281
282 (defstruct byte-lambda-var-info
283   (argp nil :type (member t nil))
284   (offset 0 :type index))
285
286 (defstruct byte-nlx-info
287   (stack-slot nil :type (or null index))
288   (label (sb!assem:gen-label) :type sb!assem:label)
289   (duplicate nil :type (member t nil)))
290
291 (defstruct (byte-block-info
292             (:include block-annotation)
293             (:constructor make-byte-block-info
294                           (block &key produces produces-sset consumes
295                             total-consumes nlx-entries nlx-entry-p)))
296   (label (sb!assem:gen-label) :type sb!assem:label)
297   ;; A list of the CONTINUATIONs describing values that this block
298   ;; pushes onto the stack. Note: PRODUCES and CONSUMES can contain
299   ;; the keyword :NLX-ENTRY marking the place on the stack where a
300   ;; non-local-exit frame is added or removed. Since breaking up a NLX
301   ;; restores the stack, we don't have to about (and in fact must not)
302   ;; discard values underneath a :NLX-ENTRY marker evern though they
303   ;; appear to be dead (since they might not be.)
304   (produces nil :type list)
305   ;; An SSET of the produces for faster set manipulations. The
306   ;; elements are the BYTE-CONTINUATION-INFO objects. :NLX-ENTRY
307   ;; markers are not represented.
308   (produces-sset (make-sset) :type sset)
309   ;; A list of the continuations that this block pops from the stack.
310   ;; See PRODUCES.
311   (consumes nil :type list)
312   ;; The transitive closure of what this block and all its successors
313   ;; consume. After stack-analysis, that is.
314   (total-consumes (make-sset) :type sset)
315   ;; Set to T whenever the consumes lists of a successor changes and
316   ;; the block is queued for re-analysis so we can easily avoid
317   ;; queueing the same block several times.
318   (already-queued nil :type (member t nil))
319   ;; The continuations and :NLX-ENTRY markers on the stack (in order)
320   ;; when this block starts.
321   (start-stack :unknown :type (or (member :unknown) list))
322   ;; The continuations and :NLX-ENTRY markers on the stack (in order)
323   ;; when this block ends.
324   (end-stack nil :type list)
325   ;; List of ((nlx-info*) produces consumes) for each ENTRY in this
326   ;; block that is a NLX target.
327   (nlx-entries nil :type list)
328   ;; T if this is an %nlx-entry point, and we shouldn't just assume we
329   ;; know what is going to be on the stack.
330   (nlx-entry-p nil :type (member t nil)))
331
332 (defprinter (byte-block-info)
333   block)
334
335 (defstruct (byte-continuation-info
336             (:include sset-element)
337             (:constructor make-byte-continuation-info
338                           (continuation results placeholders)))
339   (continuation (required-argument) :type continuation)
340   (results (required-argument)
341            :type (or (member :fdefinition :eq-test :unknown) index))
342   ;; If the DEST is a local non-MV call, then we may need to push some
343   ;; number of placeholder args corresponding to deleted
344   ;; (unreferenced) args. If PLACEHOLDERS /= 0, then RESULTS is
345   ;; PLACEHOLDERS + 1.
346   (placeholders (required-argument) :type index))
347
348 (defprinter (byte-continuation-info)
349   continuation
350   results
351   (placeholders :test (/= placeholders 0)))
352 \f
353 ;;;; Annotate the IR1.
354
355 (defun annotate-continuation (cont results &optional (placeholders 0))
356   ;; For some reason, DO-NODES does the same return node multiple
357   ;; times, which causes ANNOTATE-CONTINUATION to be called multiple
358   ;; times on the same continuation. So we can't assert that we
359   ;; haven't done it.
360   #+nil
361   (assert (null (continuation-info cont)))
362   (setf (continuation-info cont)
363         (make-byte-continuation-info cont results placeholders))
364   (values))
365
366 (defun annotate-set (set)
367   ;; Annotate the value for one value.
368   (annotate-continuation (set-value set) 1))
369
370 ;;; We do different stack magic for non-MV and MV calls to figure out
371 ;;; how many values should be pushed during compilation of each arg.
372 ;;;
373 ;;; Since byte functions are directly caller by the interpreter (there
374 ;;; is no XEP), and it doesn't know which args are actually used, byte
375 ;;; functions must allow unused args to be passed. But this creates a
376 ;;; problem with local calls, because these unused args would not
377 ;;; otherwise be pushed (since the continuation has been deleted.) So,
378 ;;; in this function, we count up placeholders for any unused args
379 ;;; contiguously preceding this one. These placeholders are inserted
380 ;;; under the referenced arg by CHECKED-CANONICALIZE-VALUES.
381 ;;;
382 ;;; With MV calls, we try to figure out how many values are actually
383 ;;; generated. We allow initial args to supply a fixed number of
384 ;;; values, but everything after the first :unknown arg must also be
385 ;;; unknown. This picks off most of the standard uses (i.e. calls to
386 ;;; apply), but still is easy to implement.
387 (defun annotate-basic-combination-args (call)
388   (declare (type basic-combination call))
389   (etypecase call
390     (combination
391      (if (and (eq (basic-combination-kind call) :local)
392               (member (functional-kind (combination-lambda call))
393                       '(nil :optional :cleanup)))
394          (let ((placeholders 0))
395            (declare (type index placeholders))
396            (dolist (arg (combination-args call))
397              (cond (arg
398                     (annotate-continuation arg (1+ placeholders) placeholders)
399                     (setq placeholders 0))
400                    (t
401                     (incf placeholders)))))
402          (dolist (arg (combination-args call))
403            (when arg
404              (annotate-continuation arg 1)))))
405     (mv-combination
406      (labels
407          ((allow-fixed (remaining)
408             (when remaining
409               (let* ((cont (car remaining))
410                      (values (nth-value 1
411                                         (values-types
412                                          (continuation-derived-type cont)))))
413                 (cond ((eq values :unknown)
414                        (force-to-unknown remaining))
415                       (t
416                        (annotate-continuation cont values)
417                        (allow-fixed (cdr remaining)))))))
418           (force-to-unknown (remaining)
419             (when remaining
420               (let ((cont (car remaining)))
421                 (when cont
422                   (annotate-continuation cont :unknown)))
423               (force-to-unknown (cdr remaining)))))
424        (allow-fixed (mv-combination-args call)))))
425   (values))
426
427 (defun annotate-local-call (call)
428   (cond ((mv-combination-p call)
429          (annotate-continuation
430           (first (basic-combination-args call))
431           (length (lambda-vars (combination-lambda call)))))
432         (t
433          (annotate-basic-combination-args call)
434          (when (member (functional-kind (combination-lambda call))
435                        '(nil :optional :cleanup))
436            (dolist (arg (basic-combination-args call))
437              (when arg
438                (setf (continuation-%type-check arg) nil))))))
439   (annotate-continuation (basic-combination-fun call) 0)
440   (when (node-tail-p call)
441     (set-tail-local-call-successor call)))
442
443 ;;; Annotate the values for any :full combination. This includes
444 ;;; inline functions, multiple value calls & throw. If a real full
445 ;;; call or a safe inline operation, then clear any type-check
446 ;;; annotations. When we are done, remove jump to return for tail
447 ;;; calls.
448 ;;;
449 ;;; Also, we annotate slot accessors as inline if no type check is
450 ;;; needed and (for setters) no value needs to be left on the stack.
451 (defun annotate-full-call (call)
452   (let* ((fun (basic-combination-fun call))
453          (args (basic-combination-args call))
454          (name (continuation-function-name fun))
455          (info (gethash name *inline-function-table*)))
456     (flet ((annotate-args ()
457              (annotate-basic-combination-args call)
458              (dolist (arg args)
459                (when (continuation-type-check arg)
460                  (setf (continuation-%type-check arg) :deleted)))
461              (annotate-continuation
462               fun
463               (if (continuation-function-name fun) :fdefinition 1))))
464       (cond ((mv-combination-p call)
465              (cond ((eq name '%throw)
466                     (assert (= (length args) 2))
467                     (annotate-continuation (first args) 1)
468                     (annotate-continuation (second args) :unknown)
469                     (setf (node-tail-p call) nil)
470                     (annotate-continuation fun 0))
471                    (t
472                     (annotate-args))))
473             ((and info
474                   (valid-function-use call (inline-function-info-type info)))
475              (annotate-basic-combination-args call)
476              (setf (node-tail-p call) nil)
477              (setf (basic-combination-info call) info)
478              (annotate-continuation fun 0)
479              (when (inline-function-info-safe info)
480                (dolist (arg args)
481                  (when (continuation-type-check arg)
482                    (setf (continuation-%type-check arg) :deleted)))))
483             ((and name
484                   (let ((leaf (ref-leaf (continuation-use fun))))
485                     (and (slot-accessor-p leaf)
486                          (or (policy call (zerop safety))
487                              (not (find 't args
488                                         :key #'continuation-type-check)))
489                          (if (consp name)
490                              (not (continuation-dest (node-cont call)))
491                              t))))
492              (setf (basic-combination-info call)
493                    (gethash (if (consp name) '%setf-instance-ref '%instance-ref)
494                             *inline-function-table*))
495              (setf (node-tail-p call) nil)
496              (annotate-continuation fun 0)
497              (annotate-basic-combination-args call))
498             (t
499              (annotate-args)))))
500
501   ;; If this is (still) a tail-call, then blow away the return.
502   (when (node-tail-p call)
503     (node-ends-block call)
504     (let ((block (node-block call)))
505       (unlink-blocks block (first (block-succ block)))
506       (link-blocks block (component-tail (block-component block)))))
507
508   (values))
509
510 (defun annotate-known-call (call)
511   (annotate-basic-combination-args call)
512   (setf (node-tail-p call) nil)
513   (annotate-continuation (basic-combination-fun call) 0)
514   t)
515
516 (defun annotate-basic-combination (call)
517   ;; Annotate the function.
518   (let ((kind (basic-combination-kind call)))
519     (case kind
520       (:local
521        (annotate-local-call call))
522       (:full
523        (annotate-full-call call))
524       (:error
525        (setf (basic-combination-kind call) :full)
526        (annotate-full-call call))
527       (t
528        (unless (and (function-info-byte-compile kind)
529                     (funcall (or (function-info-byte-annotate kind)
530                                  #'annotate-known-call)
531                              call))
532          (setf (basic-combination-kind call) :full)
533          (annotate-full-call call)))))
534
535   (values))
536
537 (defun annotate-if (if)
538   ;; Annotate the test.
539   (let* ((cont (if-test if))
540          (use (continuation-use cont)))
541     (annotate-continuation
542      cont
543      (if (and (combination-p use)
544               (eq (continuation-function-name (combination-fun use)) 'eq)
545               (= (length (combination-args use)) 2))
546          ;; If the test is a call to EQ, then we can use branch-if-eq
547          ;; so don't need to actually funcall the test.
548          :eq-test
549          ;; Otherwise, funcall the test for 1 value.
550          1))))
551
552 (defun annotate-return (return)
553   (let ((cont (return-result return)))
554     (annotate-continuation
555      cont
556      (nth-value 1 (values-types (continuation-derived-type cont))))))
557
558 (defun annotate-exit (exit)
559   (let ((cont (exit-value exit)))
560     (when cont
561       (annotate-continuation cont :unknown))))
562
563 (defun annotate-block (block)
564   (do-nodes (node cont block)
565     (etypecase node
566       (bind)
567       (ref)
568       (cset (annotate-set node))
569       (basic-combination (annotate-basic-combination node))
570       (cif (annotate-if node))
571       (creturn (annotate-return node))
572       (entry)
573       (exit (annotate-exit node))))
574   (values))
575
576 (defun annotate-ir1 (component)
577   (do-blocks (block component)
578     (when (block-interesting block)
579       (annotate-block block)))
580   (values))
581 \f
582 ;;;; stack analysis
583
584 (defvar *byte-continuation-counter*)
585
586 ;;; Scan the nodes in BLOCK and compute the information that we will
587 ;;; need to do flow analysis and our stack simulation walk. We simulate
588 ;;; the stack within the block, reducing it to ordered lists
589 ;;; representing the values we remove from the top of the stack and
590 ;;; place on the stack (not considering values that are produced and
591 ;;; consumed within the block.) A NLX entry point is considered to
592 ;;; push a :NLX-ENTRY marker (can be though of as the run-time catch
593 ;;; frame.)
594 (defun compute-produces-and-consumes (block)
595   (let ((stack nil)
596         (consumes nil)
597         (total-consumes (make-sset))
598         (nlx-entries nil)
599         (nlx-entry-p nil))
600     (labels ((interesting (cont)
601                (and cont
602                     (let ((info (continuation-info cont)))
603                       (and info
604                            (not (member (byte-continuation-info-results info)
605                                         '(0 :eq-test)))))))
606              (consume (cont)
607                (cond ((not (or (eq cont :nlx-entry) (interesting cont))))
608                      (stack
609                       (assert (eq (car stack) cont))
610                       (pop stack))
611                      (t
612                       (adjoin-cont cont total-consumes)
613                       (push cont consumes))))
614              (adjoin-cont (cont sset)
615                (unless (eq cont :nlx-entry)
616                  (let ((info (continuation-info cont)))
617                    (unless (byte-continuation-info-number info)
618                      (setf (byte-continuation-info-number info)
619                            (incf *byte-continuation-counter*)))
620                    (sset-adjoin info sset)))))
621       (do-nodes (node cont block)
622         (etypecase node
623           (bind)
624           (ref)
625           (cset
626            (consume (set-value node)))
627           (basic-combination
628            (dolist (arg (reverse (basic-combination-args node)))
629              (when arg
630                (consume arg)))
631            (consume (basic-combination-fun node))
632            (case (continuation-function-name (basic-combination-fun node))
633              (%nlx-entry
634               (let ((nlx-info (continuation-value
635                                (first (basic-combination-args node)))))
636                 (ecase (cleanup-kind (nlx-info-cleanup nlx-info))
637                   ((:catch :unwind-protect)
638                    (consume :nlx-entry))
639                   ;; If for a lexical exit, we will see a breakup later, so
640                   ;; don't consume :NLX-ENTRY now.
641                   (:tagbody)
642                   (:block
643                    (let ((cont (nlx-info-continuation nlx-info)))
644                      (when (interesting cont)
645                        (push cont stack))))))
646               (setf nlx-entry-p t))
647              (%lexical-exit-breakup
648               (unless (byte-nlx-info-duplicate
649                        (nlx-info-info
650                         (continuation-value
651                          (first (basic-combination-args node)))))
652                 (consume :nlx-entry)))
653              ((%catch-breakup %unwind-protect-breakup)
654               (consume :nlx-entry))))
655           (cif
656            (consume (if-test node)))
657           (creturn
658            (consume (return-result node)))
659           (entry
660            (let* ((cup (entry-cleanup node))
661                   (nlx-info (cleanup-nlx-info cup)))
662              (when nlx-info
663                (push :nlx-entry stack)
664                (push (list nlx-info stack (reverse consumes))
665                      nlx-entries))))
666           (exit
667            (when (exit-value node)
668              (consume (exit-value node)))))
669         (when (and (not (exit-p node)) (interesting cont))
670           (push cont stack)))
671
672       (setf (block-info block)
673             (make-byte-block-info
674              block
675              :produces stack
676              :produces-sset (let ((res (make-sset)))
677                               (dolist (product stack)
678                                 (adjoin-cont product res))
679                               res)
680              :consumes (reverse consumes)
681              :total-consumes total-consumes
682              :nlx-entries nlx-entries
683              :nlx-entry-p nlx-entry-p))))
684
685   (values))
686
687 (defun walk-successors (block stack)
688   (let ((tail (component-tail (block-component block))))
689     (dolist (succ (block-succ block))
690       (unless (or (eq succ tail)
691                   (not (block-interesting succ))
692                   (byte-block-info-nlx-entry-p (block-info succ)))
693         (walk-block succ block stack)))))
694
695 ;;; Take a stack and a consumes list, and remove the appropriate
696 ;;; stuff. When we consume a :NLX-ENTRY, we just remove the top
697 ;;; marker, and leave any values on top intact. This represents the
698 ;;; desired effect of %CATCH-BREAKUP, etc., which don't affect any
699 ;;; values on the stack.
700 (defun consume-stuff (stack stuff)
701   (let ((new-stack stack))
702     (dolist (cont stuff)
703       (cond ((eq cont :nlx-entry)
704              (assert (find :nlx-entry new-stack))
705              (setq new-stack (remove :nlx-entry new-stack :count 1)))
706             (t
707              (assert (eq (car new-stack) cont))
708              (pop new-stack))))
709     new-stack))
710
711 ;;; NLX-INFOS is the list of NLX-INFO structures for this ENTRY note.
712 ;;; CONSUME and PRODUCE are the values from outside this block that
713 ;;; were consumed and produced by this block before the ENTRY node.
714 ;;; STACK is the globally simulated stack at the start of this block.
715 (defun walk-nlx-entry (nlx-infos stack produce consume)
716   (let ((stack (consume-stuff stack consume)))
717     (dolist (nlx-info nlx-infos)
718       (walk-block (nlx-info-target nlx-info) nil (append produce stack))))
719   (values))
720
721 ;;; Simulate the stack across block boundaries, discarding any values
722 ;;; that are dead. A :NLX-ENTRY marker prevents values live at a NLX
723 ;;; entry point from being discarded prematurely.
724 (defun walk-block (block pred stack)
725   ;; Pop everything off of stack that isn't live.
726   (let* ((info (block-info block))
727          (live (byte-block-info-total-consumes info)))
728     (collect ((pops))
729       (let ((fixed 0))
730         (flet ((flush-fixed ()
731                  (unless (zerop fixed)
732                    (pops `(%byte-pop-stack ,fixed))
733                    (setf fixed 0))))
734           (loop
735             (unless stack
736               (return))
737             (let ((cont (car stack)))
738               (when (or (eq cont :nlx-entry)
739                         (sset-member (continuation-info cont) live))
740                 (return))
741               (pop stack)
742               (let ((results
743                      (byte-continuation-info-results
744                       (continuation-info cont))))
745                 (case results
746                   (:unknown
747                    (flush-fixed)
748                    (pops `(%byte-pop-stack 0)))
749                   (:fdefinition
750                    (incf fixed))
751                   (t
752                    (incf fixed results))))))
753           (flush-fixed)))
754       (when (pops)
755         (assert pred)
756         (let ((cleanup-block
757                (insert-cleanup-code pred block
758                                     (continuation-next (block-start block))
759                                     `(progn ,@(pops)))))
760           (annotate-block cleanup-block))))
761
762     (cond ((eq (byte-block-info-start-stack info) :unknown)
763            ;; Record what the stack looked like at the start of this block.
764            (setf (byte-block-info-start-stack info) stack)
765            ;; Process any nlx entries that build off of our stack.
766            (dolist (stuff (byte-block-info-nlx-entries info))
767              (walk-nlx-entry (first stuff) stack (second stuff) (third stuff)))
768            ;; Remove whatever we consume.
769            (setq stack (consume-stuff stack (byte-block-info-consumes info)))
770            ;; Add whatever we produce.
771            (setf stack (append (byte-block-info-produces info) stack))
772            (setf (byte-block-info-end-stack info) stack)
773            ;; Pass that on to all our successors.
774            (walk-successors block stack))
775           (t
776            ;; We have already processed the successors of this block. Just
777            ;; make sure we thing the stack is the same now as before.
778            (assert (equal (byte-block-info-start-stack info) stack)))))
779   (values))
780
781 ;;; Do lifetime flow analysis on values pushed on the stack, then call
782 ;;; do the stack simulation walk to discard dead values. In addition
783 ;;; to considering the obvious inputs from a block's successors, we
784 ;;; must also consider %NLX-ENTRY targets to be successors in order to
785 ;;; ensure that any values only used in the NLX entry stay alive until
786 ;;; we reach the mess-up node. After then, we can keep the values from
787 ;;; being discarded by placing a marker on the simulated stack.
788 (defun byte-stack-analyze (component)
789   (let ((head nil))
790     (let ((*byte-continuation-counter* 0))
791       (do-blocks (block component)
792         (when (block-interesting block)
793           (compute-produces-and-consumes block)
794           (push block head)
795           (setf (byte-block-info-already-queued (block-info block)) t))))
796     (let ((tail (last head)))
797       (labels ((maybe-enqueue (block)
798                  (when (block-interesting block)
799                    (let ((info (block-info block)))
800                      (unless (byte-block-info-already-queued info)
801                        (setf (byte-block-info-already-queued info) t)
802                        (let ((new (list block)))
803                          (if head
804                              (setf (cdr tail) new)
805                              (setf head new))
806                          (setf tail new))))))
807                (maybe-enqueue-predecessors (block)
808                  (when (byte-block-info-nlx-entry-p (block-info block))
809                    (maybe-enqueue
810                     (node-block
811                      (cleanup-mess-up
812                       (nlx-info-cleanup
813                        (find block
814                              (environment-nlx-info (block-environment block))
815                              :key #'nlx-info-target))))))
816
817                  (dolist (pred (block-pred block))
818                    (unless (eq pred (component-head (block-component block)))
819                      (maybe-enqueue pred)))))
820         (loop
821           (unless head
822             (return))
823           (let* ((block (pop head))
824                  (info (block-info block))
825                  (total-consumes (byte-block-info-total-consumes info))
826                  (produces-sset (byte-block-info-produces-sset info))
827                  (did-anything nil))
828             (setf (byte-block-info-already-queued info) nil)
829             (dolist (succ (block-succ block))
830               (unless (eq succ (component-tail component))
831                 (let ((succ-info (block-info succ)))
832                   (when (sset-union-of-difference
833                          total-consumes
834                          (byte-block-info-total-consumes succ-info)
835                          produces-sset)
836                     (setf did-anything t)))))
837             (dolist (nlx-list (byte-block-info-nlx-entries info))
838               (dolist (nlx-info (first nlx-list))
839                 (when (sset-union-of-difference
840                        total-consumes
841                        (byte-block-info-total-consumes
842                         (block-info
843                          (nlx-info-target nlx-info)))
844                        produces-sset)
845                   (setf did-anything t))))
846             (when did-anything
847               (maybe-enqueue-predecessors block)))))))
848
849   (walk-successors (component-head component) nil)
850   (values))
851 \f
852 ;;;; Actually generate the byte code.
853
854 (defvar *byte-component-info*)
855
856 ;;; FIXME: These might as well be generated with DEFENUM, right?
857 ;;; It would also be nice to give them less ambiguous names, perhaps
858 ;;; with a "BYTEOP-" prefix instead of "BYTE-".
859 (defconstant byte-push-local           #b00000000)
860 (defconstant byte-push-arg             #b00010000)
861 (defconstant byte-push-constant        #b00100000)
862 (defconstant byte-push-system-constant #b00110000)
863 (defconstant byte-push-int             #b01000000)
864 (defconstant byte-push-neg-int         #b01010000)
865 (defconstant byte-pop-local            #b01100000)
866 (defconstant byte-pop-n                #b01110000)
867 (defconstant byte-call                 #b10000000)
868 (defconstant byte-tail-call            #b10010000)
869 (defconstant byte-multiple-call        #b10100000)
870 (defconstant byte-named                #b00001000)
871 (defconstant byte-local-call           #b10110000)
872 (defconstant byte-local-tail-call      #b10111000)
873 (defconstant byte-local-multiple-call  #b11000000)
874 (defconstant byte-return               #b11001000)
875 (defconstant byte-branch-always        #b11010000)
876 (defconstant byte-branch-if-true       #b11010010)
877 (defconstant byte-branch-if-false      #b11010100)
878 (defconstant byte-branch-if-eq         #b11010110)
879 (defconstant byte-xop                  #b11011000)
880 (defconstant byte-inline-function      #b11100000)
881
882 (defun output-push-int (segment int)
883   (declare (type sb!assem:segment segment)
884            (type (integer #.(- (ash 1 24)) #.(1- (ash 1 24)))))
885   (if (minusp int)
886       (output-byte-with-operand segment byte-push-neg-int (- (1+ int)))
887       (output-byte-with-operand segment byte-push-int int)))
888
889 (defun output-push-constant-leaf (segment constant)
890   (declare (type sb!assem:segment segment)
891            (type constant constant))
892   (let ((info (constant-info constant)))
893     (if info
894         (output-byte-with-operand segment
895                                   (ecase (car info)
896                                     (:system-constant
897                                      byte-push-system-constant)
898                                     (:local-constant
899                                      byte-push-constant))
900                                   (cdr info))
901         (let ((const (constant-value constant)))
902           (if (and (integerp const) (< (- (ash 1 24)) const (ash 1 24)))
903               ;; It can be represented as an immediate.
904               (output-push-int segment const)
905               ;; We need to store it in the constants pool.
906               (let* ((posn
907                       (unless (and (consp const)
908                                    (eq (car const) '%fdefinition-marker%))
909                         (gethash const *system-constant-codes*)))
910                      (new-info (if posn
911                                    (cons :system-constant posn)
912                                    (cons :local-constant
913                                          (vector-push-extend
914                                           constant
915                                           (byte-component-info-constants
916                                            *byte-component-info*))))))
917                 (setf (constant-info constant) new-info)
918                 (output-push-constant-leaf segment constant)))))))
919
920 (defun output-push-constant (segment value)
921   (if (and (integerp value)
922            (< (- (ash 1 24)) value (ash 1 24)))
923       (output-push-int segment value)
924       (output-push-constant-leaf segment (find-constant value))))
925
926 ;;; Return the offset of a load-time constant in the constant pool,
927 ;;; adding it if absent.
928 (defun byte-load-time-constant-index (kind datum)
929   (let ((constants (byte-component-info-constants *byte-component-info*)))
930     (or (position-if #'(lambda (x)
931                          (and (consp x)
932                               (eq (car x) kind)
933                               (typecase datum
934                                 (cons (equal (cdr x) datum))
935                                 (ctype (type= (cdr x) datum))
936                                 (t
937                                  (eq (cdr x) datum)))))
938                      constants)
939         (vector-push-extend (cons kind datum) constants))))
940
941 (defun output-push-load-time-constant (segment kind datum)
942   (output-byte-with-operand segment byte-push-constant
943                             (byte-load-time-constant-index kind datum))
944   (values))
945
946 (defun output-do-inline-function (segment function)
947   ;; Note: we don't annotate this as a call site, because it is used
948   ;; for internal stuff. Functions that get inlined have code
949   ;; locations added byte generate-byte-code-for-full-call below.
950   (output-byte segment
951                (logior byte-inline-function
952                        (inline-function-number-or-lose function))))
953
954 (defun output-do-xop (segment xop)
955   (let ((index (xop-index-or-lose xop)))
956     (cond ((< index 7)
957            (output-byte segment (logior byte-xop index)))
958           (t
959            (output-byte segment (logior byte-xop 7))
960            (output-byte segment index)))))
961
962 (defun closure-position (var env)
963   (or (position var (environment-closure env))
964       (error "Can't find ~S" var)))
965
966 (defun output-ref-lambda-var (segment var env
967                                      &optional (indirect-value-cells t))
968   (declare (type sb!assem:segment segment)
969            (type lambda-var var)
970            (type environment env))
971   (if (eq (lambda-environment (lambda-var-home var)) env)
972       (let ((info (leaf-info var)))
973         (output-byte-with-operand segment
974                                   (if (byte-lambda-var-info-argp info)
975                                       byte-push-arg
976                                       byte-push-local)
977                                   (byte-lambda-var-info-offset info)))
978       (output-byte-with-operand segment
979                                 byte-push-arg
980                                 (closure-position var env)))
981   (when (and indirect-value-cells (lambda-var-indirect var))
982     (output-do-inline-function segment 'value-cell-ref)))
983
984 (defun output-ref-nlx-info (segment info env)
985   (if (eq (node-environment (cleanup-mess-up (nlx-info-cleanup info))) env)
986       (output-byte-with-operand segment
987                                 byte-push-local
988                                 (byte-nlx-info-stack-slot
989                                  (nlx-info-info info)))
990       (output-byte-with-operand segment
991                                 byte-push-arg
992                                 (closure-position info env))))
993
994 (defun output-set-lambda-var (segment var env &optional make-value-cells)
995   (declare (type sb!assem:segment segment)
996            (type lambda-var var)
997            (type environment env))
998   (let ((indirect (lambda-var-indirect var)))
999     (cond ((not (eq (lambda-environment (lambda-var-home var)) env))
1000            ;; This is not this guy's home environment. So we need to
1001            ;; get it the value cell out of the closure, and fill it in.
1002            (assert indirect)
1003            (assert (not make-value-cells))
1004            (output-byte-with-operand segment byte-push-arg
1005                                      (closure-position var env))
1006            (output-do-inline-function segment 'value-cell-setf))
1007           (t
1008            (let* ((pushp (and indirect (not make-value-cells)))
1009                   (byte-code (if pushp byte-push-local byte-pop-local))
1010                   (info (leaf-info var)))
1011              (assert (not (byte-lambda-var-info-argp info)))
1012              (when (and indirect make-value-cells)
1013                ;; Replace the stack top with a value cell holding the
1014                ;; stack top.
1015                (output-do-inline-function segment 'make-value-cell))
1016              (output-byte-with-operand segment byte-code
1017                                        (byte-lambda-var-info-offset info))
1018              (when pushp
1019                (output-do-inline-function segment 'value-cell-setf)))))))
1020
1021 ;;; Output whatever noise is necessary to canonicalize the values on
1022 ;;; the top of the stack. DESIRED is the number we want, and SUPPLIED
1023 ;;; is the number we have. Either push NIL or pop-n to make them
1024 ;;; balanced. Note: either desired or supplied can be :unknown, in
1025 ;;; which case it means use the ``unknown-values'' convention (which
1026 ;;; is the stack values followed by the number of values).
1027 (defun canonicalize-values (segment desired supplied)
1028   (declare (type sb!assem:segment segment)
1029            (type (or (member :unknown) index) desired supplied))
1030   (cond ((eq desired :unknown)
1031          (unless (eq supplied :unknown)
1032            (output-byte-with-operand segment byte-push-int supplied)))
1033         ((eq supplied :unknown)
1034          (unless (eq desired :unknown)
1035            (output-push-int segment desired)
1036            (output-do-xop segment 'default-unknown-values)))
1037         ((< supplied desired)
1038          (dotimes (i (- desired supplied))
1039            (output-push-constant segment nil)))
1040         ((> supplied desired)
1041          (output-byte-with-operand segment byte-pop-n (- supplied desired))))
1042   (values))
1043
1044 (defparameter *byte-type-weakenings*
1045   (mapcar #'specifier-type
1046           '(fixnum single-float double-float simple-vector simple-bit-vector
1047                    bit-vector)))
1048
1049 ;;; Emit byte code to check that the value on top of the stack is of
1050 ;;; the specified TYPE. NODE is used for policy information. We weaken
1051 ;;; or entirely omit the type check whether speed is more important
1052 ;;; than safety.
1053 (defun byte-generate-type-check (segment type node)
1054   (declare (type ctype type) (type node node))
1055   (unless (or (policy node (zerop safety))
1056               (csubtypep *universal-type* type))
1057     (let ((type (if (policy node (> speed safety))
1058                     (dolist (super *byte-type-weakenings* type)
1059                       (when (csubtypep type super) (return super)))
1060                     type)))
1061       (output-do-xop segment 'type-check)
1062       (output-extended-operand
1063        segment
1064        (byte-load-time-constant-index :type-predicate type)))))
1065
1066 ;;; This function is used when we are generating code which delivers
1067 ;;; values to a continuation. If this continuation needs a type check,
1068 ;;; and has a single value, then we do a type check. We also
1069 ;;; CANONICALIZE-VALUES for the continuation's desired number of
1070 ;;; values (w/o the placeholders.)
1071 ;;;
1072 ;;; Somewhat unrelatedly, we also push placeholders for deleted
1073 ;;; arguments to local calls. Although we check first, the actual
1074 ;;; PUSH-N-UNDER is done afterward, since then the single value we
1075 ;;; want is stack top.
1076 (defun checked-canonicalize-values (segment cont supplied)
1077   (let ((info (continuation-info cont)))
1078     (if info
1079         (let ((desired (byte-continuation-info-results info))
1080               (placeholders (byte-continuation-info-placeholders info)))
1081           (unless (zerop placeholders)
1082             (assert (eql desired (1+ placeholders)))
1083             (setq desired 1))
1084
1085           (flet ((do-check ()
1086                    (byte-generate-type-check
1087                     segment
1088                     (single-value-type (continuation-asserted-type cont))
1089                     (continuation-dest cont))))
1090             (cond
1091              ((member (continuation-type-check cont) '(nil :deleted))
1092               (canonicalize-values segment desired supplied))
1093              ((eql supplied 1)
1094               (do-check)
1095               (canonicalize-values segment desired supplied))
1096              ((eql desired 1)
1097               (canonicalize-values segment desired supplied)
1098               (do-check))
1099              (t
1100               (canonicalize-values segment desired supplied))))
1101
1102           (unless (zerop placeholders)
1103             (output-do-xop segment 'push-n-under)
1104             (output-extended-operand segment placeholders)))
1105
1106         (canonicalize-values segment 0 supplied))))
1107
1108 ;;; Emit prologue for non-LET functions. Assigned arguments must be
1109 ;;; copied into locals, and argument type checking may need to be done.
1110 (defun generate-byte-code-for-bind (segment bind cont)
1111   (declare (type sb!assem:segment segment) (type bind bind)
1112            (ignore cont))
1113   (let ((lambda (bind-lambda bind))
1114         (env (node-environment bind)))
1115     (ecase (lambda-kind lambda)
1116       ((nil :top-level :escape :cleanup :optional)
1117        (let* ((info (lambda-info lambda))
1118               (type-check (policy (lambda-bind lambda) (not (zerop safety))))
1119               (frame-size (byte-lambda-info-stack-size info)))
1120          (cond ((< frame-size (* 255 2))
1121                 (output-byte segment (ceiling frame-size 2)))
1122                (t
1123                 (output-byte segment 255)
1124                 (output-byte segment (ldb (byte 8 16) frame-size))
1125                 (output-byte segment (ldb (byte 8 8) frame-size))
1126                 (output-byte segment (ldb (byte 8 0) frame-size))))
1127
1128          (do ((argnum (1- (+ (length (lambda-vars lambda))
1129                              (length (environment-closure
1130                                       (lambda-environment lambda)))))
1131                       (1- argnum))
1132               (vars (lambda-vars lambda) (cdr vars))
1133               (pops 0))
1134              ((null vars)
1135               (unless (zerop pops)
1136                 (output-byte-with-operand segment byte-pop-n pops)))
1137            (declare (fixnum argnum pops))
1138            (let* ((var (car vars))
1139                   (info (lambda-var-info var))
1140                   (type (leaf-type var)))
1141              (cond ((not info))
1142                    ((byte-lambda-var-info-argp info)
1143                     (when (and type-check
1144                                (not (csubtypep *universal-type* type)))
1145                       (output-byte-with-operand segment byte-push-arg argnum)
1146                       (byte-generate-type-check segment type bind)
1147                       (incf pops)))
1148                    (t
1149                     (output-byte-with-operand segment byte-push-arg argnum)
1150                     (when type-check
1151                       (byte-generate-type-check segment type bind))
1152                     (output-set-lambda-var segment var env t)))))))
1153
1154       ;; Everything has been taken care of in the combination node.
1155       ((:let :mv-let :assignment))))
1156   (values))
1157
1158 ;;; This hashtable translates from n-ary function names to the
1159 ;;; two-arg-specific versions which we call to avoid &REST-arg consing.
1160 (defvar *two-arg-functions* (make-hash-table :test 'eq))
1161
1162 (dolist (fun '((sb!kernel:two-arg-ior  logior)
1163                (sb!kernel:two-arg-*  *)
1164                (sb!kernel:two-arg-+  +)
1165                (sb!kernel:two-arg-/  /)
1166                (sb!kernel:two-arg--  -)
1167                (sb!kernel:two-arg->  >)
1168                (sb!kernel:two-arg-<  <)
1169                (sb!kernel:two-arg-=  =)
1170                (sb!kernel:two-arg-lcm  lcm)
1171                (sb!kernel:two-arg-and  logand)
1172                (sb!kernel:two-arg-gcd  gcd)
1173                (sb!kernel:two-arg-xor  logxor)
1174
1175                (two-arg-char= char=)
1176                (two-arg-char< char<)
1177                (two-arg-char> char>)
1178                (two-arg-char-equal char-equal)
1179                (two-arg-char-lessp char-lessp)
1180                (two-arg-char-greaterp char-greaterp)
1181                (two-arg-string= string=)
1182                (two-arg-string< string<)
1183                (two-arg-string> string>)))
1184
1185   (setf (gethash (second fun) *two-arg-functions*) (first fun)))
1186
1187 ;;; If a system constant, push that, otherwise use a load-time constant.
1188 (defun output-push-fdefinition (segment name)
1189   (let ((offset (gethash `(%fdefinition-marker% . ,name)
1190                          *system-constant-codes*)))
1191     (if offset
1192         (output-byte-with-operand segment byte-push-system-constant
1193                                   offset)
1194         (output-push-load-time-constant segment :fdefinition name))))
1195
1196 (defun generate-byte-code-for-ref (segment ref cont)
1197   (declare (type sb!assem:segment segment) (type ref ref)
1198            (type continuation cont))
1199   (let ((info (continuation-info cont)))
1200     ;; If there is no info, then nobody wants the result.
1201     (when info
1202       (let ((values (byte-continuation-info-results info))
1203             (leaf (ref-leaf ref)))
1204         (cond
1205          ((eq values :fdefinition)
1206           (assert (and (global-var-p leaf)
1207                        (eq (global-var-kind leaf)
1208                            :global-function)))
1209           (let* ((name (global-var-name leaf))
1210                  (found (gethash name *two-arg-functions*)))
1211             (output-push-fdefinition
1212              segment
1213              (if (and found
1214                       (= (length (combination-args (continuation-dest cont)))
1215                          2))
1216                  found
1217                  name))))
1218          ((eql values 0)
1219           ;; really easy!
1220           nil)
1221          (t
1222           (etypecase leaf
1223             (constant
1224              (output-push-constant-leaf segment leaf))
1225             (clambda
1226              (let* ((refered-env (lambda-environment leaf))
1227                     (closure (environment-closure refered-env)))
1228                (if (null closure)
1229                    (output-push-load-time-constant segment :entry leaf)
1230                    (let ((my-env (node-environment ref)))
1231                      (output-push-load-time-constant segment :entry leaf)
1232                      (dolist (thing closure)
1233                        (etypecase thing
1234                          (lambda-var
1235                           (output-ref-lambda-var segment thing my-env nil))
1236                          (nlx-info
1237                           (output-ref-nlx-info segment thing my-env))))
1238                      (output-push-int segment (length closure))
1239                      (output-do-xop segment 'make-closure)))))
1240             (functional
1241              (output-push-load-time-constant segment :entry leaf))
1242             (lambda-var
1243              (output-ref-lambda-var segment leaf (node-environment ref)))
1244             (global-var
1245              (ecase (global-var-kind leaf)
1246                ((:special :global :constant)
1247                 (output-push-constant segment (global-var-name leaf))
1248                 (output-do-inline-function segment 'symbol-value))
1249                (:global-function
1250                 (output-push-fdefinition segment (global-var-name leaf))
1251                 (output-do-xop segment 'fdefn-function-or-lose)))))
1252           (checked-canonicalize-values segment cont 1))))))
1253   (values))
1254
1255 (defun generate-byte-code-for-set (segment set cont)
1256   (declare (type sb!assem:segment segment) (type cset set)
1257            (type continuation cont))
1258   (let* ((leaf (set-var set))
1259          (info (continuation-info cont))
1260          (values (if info
1261                      (byte-continuation-info-results info)
1262                      0)))
1263     (unless (eql values 0)
1264       ;; Someone wants the value, so copy it.
1265       (output-do-xop segment 'dup))
1266     (etypecase leaf
1267       (global-var
1268        (ecase (global-var-kind leaf)
1269          ((:special :global)
1270           (output-push-constant segment (global-var-name leaf))
1271           (output-do-inline-function segment 'setf-symbol-value))))
1272       (lambda-var
1273        (output-set-lambda-var segment leaf (node-environment set))))
1274     (unless (eql values 0)
1275       (checked-canonicalize-values segment cont 1)))
1276   (values))
1277
1278 (defun generate-byte-code-for-local-call (segment call cont num-args)
1279   (let* ((lambda (combination-lambda call))
1280          (vars (lambda-vars lambda))
1281          (env (lambda-environment lambda)))
1282     (ecase (functional-kind lambda)
1283       ((:let :assignment)
1284        (dolist (var (reverse vars))
1285          (when (lambda-var-refs var)
1286            (output-set-lambda-var segment var env t))))
1287       (:mv-let
1288        (let ((do-check (member (continuation-type-check
1289                                 (first (basic-combination-args call)))
1290                                '(t :error))))
1291          (dolist (var (reverse vars))
1292            (when do-check
1293              (byte-generate-type-check segment (leaf-type var) call))
1294            (output-set-lambda-var segment var env t))))
1295       ((nil :optional :cleanup)
1296        ;; We got us a local call.
1297        (assert (not (eq num-args :unknown)))
1298        ;; Push any trailing placeholder args...
1299        (dolist (x (reverse (basic-combination-args call)))
1300          (when x (return))
1301          (output-push-int segment 0))
1302        ;; Then push closure vars.
1303        (let ((closure (environment-closure env)))
1304          (when closure
1305            (let ((my-env (node-environment call)))
1306              (dolist (thing (reverse closure))
1307                (etypecase thing
1308                  (lambda-var
1309                   (output-ref-lambda-var segment thing my-env nil))
1310                  (nlx-info
1311                   (output-ref-nlx-info segment thing my-env)))))
1312            (incf num-args (length closure))))
1313        (let ((results
1314               (let ((info (continuation-info cont)))
1315                 (if info
1316                     (byte-continuation-info-results info)
1317                     0))))
1318          ;; Emit the op for whatever flavor of call we are using.
1319          (let ((operand
1320                 (cond ((> num-args 6)
1321                        (output-push-int segment num-args)
1322                        7)
1323                       (t
1324                        num-args))))
1325            (multiple-value-bind (opcode ret-vals)
1326                (cond ((node-tail-p call)
1327                       (values byte-local-tail-call 0))
1328                      ((member results '(0 1))
1329                       (values byte-local-call 1))
1330                      (t
1331                       (values byte-local-multiple-call :unknown)))
1332              ;; ### :call-site
1333              (output-byte segment (logior opcode operand))
1334              ;; Emit a reference to the label.
1335              (output-reference segment
1336                                (byte-lambda-info-label (lambda-info lambda)))
1337              ;; ### :unknown-return
1338              ;; Fix up the results.
1339              (unless (node-tail-p call)
1340                (checked-canonicalize-values segment cont ret-vals))))))))
1341   (values))
1342
1343 (defun generate-byte-code-for-full-call (segment call cont num-args)
1344   (let ((info (basic-combination-info call))
1345         (results
1346          (let ((info (continuation-info cont)))
1347            (if info
1348                (byte-continuation-info-results info)
1349                0))))
1350     (cond
1351      (info
1352       ;; It's an inline function.
1353       (assert (not (node-tail-p call)))
1354       (let* ((type (inline-function-info-type info))
1355              (desired-args (function-type-nargs type))
1356              (supplied-results
1357               (nth-value 1
1358                          (values-types (function-type-returns type))))
1359              (leaf (ref-leaf (continuation-use (basic-combination-fun call)))))
1360         (cond ((slot-accessor-p leaf)
1361                (assert (= num-args (1- desired-args)))
1362                (output-push-int segment (dsd-index (slot-accessor-slot leaf))))
1363               (t
1364                (canonicalize-values segment desired-args num-args)))
1365         ;; ### :call-site
1366         (output-byte segment (logior byte-inline-function
1367                                      (inline-function-info-number info)))
1368         ;; ### :known-return
1369         (checked-canonicalize-values segment cont supplied-results)))
1370      (t
1371       (let ((operand
1372              (cond ((eq num-args :unknown)
1373                     7)
1374                    ((> num-args 6)
1375                     (output-push-int segment num-args)
1376                     7)
1377                    (t
1378                     num-args))))
1379         (when (eq (byte-continuation-info-results
1380                    (continuation-info
1381                     (basic-combination-fun call)))
1382                   :fdefinition)
1383           (setf operand (logior operand byte-named)))
1384         ;; ### :call-site
1385         (cond
1386          ((node-tail-p call)
1387           (output-byte segment (logior byte-tail-call operand)))
1388          (t
1389           (multiple-value-bind (opcode ret-vals)
1390               (case results
1391                 (:unknown (values byte-multiple-call :unknown))
1392                 ((0 1) (values byte-call 1))
1393                 (t (values byte-multiple-call :unknown)))
1394           (output-byte segment (logior opcode operand))
1395           ;; ### :unknown-return
1396           (checked-canonicalize-values segment cont ret-vals)))))))))
1397
1398 (defun generate-byte-code-for-known-call (segment call cont num-args)
1399   (block nil
1400     (catch 'give-up-ir1-transform
1401       (funcall (function-info-byte-compile (basic-combination-kind call)) call
1402                (let ((info (continuation-info cont)))
1403                  (if info
1404                      (byte-continuation-info-results info)
1405                      0))
1406                num-args segment)
1407       (return))
1408     (assert (member (byte-continuation-info-results
1409                      (continuation-info
1410                       (basic-combination-fun call)))
1411                     '(1 :fdefinition)))
1412     (generate-byte-code-for-full-call segment call cont num-args))
1413   (values))
1414
1415 (defun generate-byte-code-for-generic-combination (segment call cont)
1416   (declare (type sb!assem:segment segment) (type basic-combination call)
1417            (type continuation cont))
1418   (labels ((examine (args num-fixed)
1419              (cond
1420               ((null args)
1421                ;; None of the arugments supply :UNKNOWN values, so
1422                ;; we know exactly how many there are.
1423                num-fixed)
1424               (t
1425                (let* ((vals
1426                        (byte-continuation-info-results
1427                         (continuation-info (car args)))))
1428                  (cond
1429                   ((eq vals :unknown)
1430                    (unless (null (cdr args))
1431                      ;; There are (LENGTH ARGS) :UNKNOWN value blocks on
1432                      ;; the top of the stack. We need to combine them.
1433                      (output-push-int segment (length args))
1434                      (output-do-xop segment 'merge-unknown-values))
1435                    (unless (zerop num-fixed)
1436                      ;; There are num-fixed fixed args above the unknown
1437                      ;; values block that want in on the action also.
1438                      ;; So add num-fixed to the count.
1439                      (output-push-int segment num-fixed)
1440                      (output-do-inline-function segment '+))
1441                    :unknown)
1442                   (t
1443                    (examine (cdr args) (+ num-fixed vals)))))))))
1444     (let* ((args (basic-combination-args call))
1445            (kind (basic-combination-kind call))
1446            (num-args (if (and (eq kind :local)
1447                               (combination-p call))
1448                          (length args)
1449                          (examine args 0))))
1450       (case kind
1451         (:local
1452          (generate-byte-code-for-local-call segment call cont num-args))
1453         (:full
1454          (generate-byte-code-for-full-call segment call cont num-args))
1455         (t
1456          (generate-byte-code-for-known-call segment call cont num-args))))))
1457
1458 (defun generate-byte-code-for-basic-combination (segment call cont)
1459   (cond ((and (mv-combination-p call)
1460               (eq (continuation-function-name (basic-combination-fun call))
1461                   '%throw))
1462          ;; ### :internal-error
1463          (output-do-xop segment 'throw))
1464         (t
1465          (generate-byte-code-for-generic-combination segment call cont))))
1466
1467 (defun generate-byte-code-for-if (segment if cont)
1468   (declare (type sb!assem:segment segment) (type cif if)
1469            (ignore cont))
1470   (let* ((next-info (byte-block-info-next (block-info (node-block if))))
1471          (consequent-info (block-info (if-consequent if)))
1472          (alternate-info (block-info (if-alternative if))))
1473     (cond ((eq (byte-continuation-info-results
1474                 (continuation-info (if-test if)))
1475                :eq-test)
1476            (output-branch segment
1477                           byte-branch-if-eq
1478                           (byte-block-info-label consequent-info))
1479            (unless (eq next-info alternate-info)
1480              (output-branch segment
1481                             byte-branch-always
1482                             (byte-block-info-label alternate-info))))
1483           ((eq next-info consequent-info)
1484            (output-branch segment
1485                           byte-branch-if-false
1486                           (byte-block-info-label alternate-info)))
1487           (t
1488            (output-branch segment
1489                           byte-branch-if-true
1490                           (byte-block-info-label consequent-info))
1491            (unless (eq next-info alternate-info)
1492              (output-branch segment
1493                             byte-branch-always
1494                             (byte-block-info-label alternate-info)))))))
1495
1496 (defun generate-byte-code-for-return (segment return cont)
1497   (declare (type sb!assem:segment segment) (type creturn return)
1498            (ignore cont))
1499   (let* ((result (return-result return))
1500          (info (continuation-info result))
1501          (results (byte-continuation-info-results info)))
1502     (cond ((eq results :unknown)
1503            (setf results 7))
1504           ((> results 6)
1505            (output-byte-with-operand segment byte-push-int results)
1506            (setf results 7)))
1507     (output-byte segment (logior byte-return results)))
1508   (values))
1509
1510 (defun generate-byte-code-for-entry (segment entry cont)
1511   (declare (type sb!assem:segment segment) (type entry entry)
1512            (ignore cont))
1513   (dolist (exit (entry-exits entry))
1514     (let ((nlx-info (find-nlx-info entry (node-cont exit))))
1515       (when nlx-info
1516         (let ((kind (cleanup-kind (nlx-info-cleanup nlx-info))))
1517           (when (member kind '(:block :tagbody))
1518             ;; Generate a unique tag.
1519             (output-push-constant
1520              segment
1521              (format nil
1522                      "tag for ~A"
1523                      (component-name *component-being-compiled*)))
1524             (output-push-constant segment nil)
1525             (output-do-inline-function segment 'cons)
1526             ;; Save it so people can close over it.
1527             (output-do-xop segment 'dup)
1528             (output-byte-with-operand segment
1529                                       byte-pop-local
1530                                       (byte-nlx-info-stack-slot
1531                                        (nlx-info-info nlx-info)))
1532             ;; Now do the actual XOP.
1533             (ecase kind
1534               (:block
1535                (output-do-xop segment 'catch)
1536                (output-reference segment
1537                                  (byte-nlx-info-label
1538                                   (nlx-info-info nlx-info))))
1539               (:tagbody
1540                (output-do-xop segment 'tagbody)))
1541             (return))))))
1542   (values))
1543
1544 (defun generate-byte-code-for-exit (segment exit cont)
1545   (declare (ignore cont))
1546   (let ((nlx-info (find-nlx-info (exit-entry exit) (node-cont exit))))
1547     (output-byte-with-operand segment
1548                               byte-push-arg
1549                               (closure-position nlx-info
1550                                                 (node-environment exit)))
1551     (ecase (cleanup-kind (nlx-info-cleanup nlx-info))
1552       (:block
1553        ;; ### :internal-error
1554        (output-do-xop segment 'return-from))
1555       (:tagbody
1556        ;; ### :internal-error
1557        (output-do-xop segment 'go)
1558        (output-reference segment
1559                          (byte-nlx-info-label (nlx-info-info nlx-info)))))))
1560
1561 (defun generate-byte-code (segment component)
1562   (let ((*byte-component-info* (component-info component)))
1563     (do* ((info (byte-block-info-next (block-info (component-head component)))
1564                 next)
1565           (block (byte-block-info-block info) (byte-block-info-block info))
1566           (next (byte-block-info-next info) (byte-block-info-next info)))
1567          ((eq block (component-tail component)))
1568       (when (block-interesting block)
1569         (output-label segment (byte-block-info-label info))
1570         (do-nodes (node cont block)
1571           (etypecase node
1572             (bind (generate-byte-code-for-bind segment node cont))
1573             (ref (generate-byte-code-for-ref segment node cont))
1574             (cset (generate-byte-code-for-set segment node cont))
1575             (basic-combination
1576              (generate-byte-code-for-basic-combination
1577               segment node cont))
1578             (cif (generate-byte-code-for-if segment node cont))
1579             (creturn (generate-byte-code-for-return segment node cont))
1580             (entry (generate-byte-code-for-entry segment node cont))
1581             (exit
1582              (when (exit-entry node)
1583                (generate-byte-code-for-exit segment node cont)))))
1584         (let* ((succ (block-succ block))
1585                (first-succ (car succ))
1586                (last (block-last block)))
1587           (unless (or (cdr succ)
1588                       (eq (byte-block-info-block next) first-succ)
1589                       (eq (component-tail component) first-succ)
1590                       (and (basic-combination-p last)
1591                            (node-tail-p last)
1592                            ;; Tail local calls that have been
1593                            ;; converted to an assignment need the
1594                            ;; branch.
1595                            (not (and (eq (basic-combination-kind last) :local)
1596                                      (member (functional-kind
1597                                               (combination-lambda last))
1598                                              '(:let :assignment))))))
1599             (output-branch segment
1600                            byte-branch-always
1601                            (byte-block-info-label
1602                             (block-info first-succ))))))))
1603   (values))
1604 \f
1605 ;;;; special purpose annotate/compile optimizers
1606
1607 (defoptimizer (eq byte-annotate) ((this that) node)
1608   (declare (ignore this that))
1609   (when (if-p (continuation-dest (node-cont node)))
1610     (annotate-known-call node)
1611     t))
1612
1613 (defoptimizer (eq byte-compile) ((this that) call results num-args segment)
1614   (progn segment) ; ignorable.
1615   ;; We don't have to do anything, because everything is handled by
1616   ;; the IF byte-generator.
1617   (assert (eq results :eq-test))
1618   (assert (eql num-args 2))
1619   (values))
1620
1621 (defoptimizer (values byte-compile)
1622               ((&rest values) node results num-args segment)
1623   (canonicalize-values segment results num-args))
1624
1625 (defknown %byte-pop-stack (index) (values))
1626
1627 (defoptimizer (%byte-pop-stack byte-annotate) ((count) node)
1628   (assert (constant-continuation-p count))
1629   (annotate-continuation count 0)
1630   (annotate-continuation (basic-combination-fun node) 0)
1631   (setf (node-tail-p node) nil)
1632   t)
1633
1634 (defoptimizer (%byte-pop-stack byte-compile)
1635               ((count) node results num-args segment)
1636   (assert (and (zerop num-args) (zerop results)))
1637   (output-byte-with-operand segment byte-pop-n (continuation-value count)))
1638
1639 (defoptimizer (%special-bind byte-annotate) ((var value) node)
1640   (annotate-continuation var 0)
1641   (annotate-continuation value 1)
1642   (annotate-continuation (basic-combination-fun node) 0)
1643   (setf (node-tail-p node) nil)
1644   t)
1645
1646 (defoptimizer (%special-bind byte-compile)
1647               ((var value) node results num-args segment)
1648   (assert (and (eql num-args 1) (zerop results)))
1649   (output-push-constant segment (leaf-name (continuation-value var)))
1650   (output-do-inline-function segment '%byte-special-bind))
1651
1652 (defoptimizer (%special-unbind byte-annotate) ((var) node)
1653   (annotate-continuation var 0)
1654   (annotate-continuation (basic-combination-fun node) 0)
1655   (setf (node-tail-p node) nil)
1656   t)
1657
1658 (defoptimizer (%special-unbind byte-compile)
1659               ((var) node results num-args segment)
1660   (assert (and (zerop num-args) (zerop results)))
1661   (output-do-inline-function segment '%byte-special-unbind))
1662
1663 (defoptimizer (%catch byte-annotate) ((nlx-info tag) node)
1664   (annotate-continuation nlx-info 0)
1665   (annotate-continuation tag 1)
1666   (annotate-continuation (basic-combination-fun node) 0)
1667   (setf (node-tail-p node) nil)
1668   t)
1669
1670 (defoptimizer (%catch byte-compile)
1671               ((nlx-info tag) node results num-args segment)
1672   (progn node) ; ignore
1673   (assert (and (= num-args 1) (zerop results)))
1674   (output-do-xop segment 'catch)
1675   (let ((info (nlx-info-info (continuation-value nlx-info))))
1676     (output-reference segment (byte-nlx-info-label info))))
1677
1678 (defoptimizer (%cleanup-point byte-compile) (() node results num-args segment)
1679   (progn node segment) ; ignore
1680   (assert (and (zerop num-args) (zerop results))))
1681
1682 (defoptimizer (%catch-breakup byte-compile) (() node results num-args segment)
1683   (progn node) ; ignore
1684   (assert (and (zerop num-args) (zerop results)))
1685   (output-do-xop segment 'breakup))
1686
1687 (defoptimizer (%lexical-exit-breakup byte-annotate) ((nlx-info) node)
1688   (annotate-continuation nlx-info 0)
1689   (annotate-continuation (basic-combination-fun node) 0)
1690   (setf (node-tail-p node) nil)
1691   t)
1692
1693 (defoptimizer (%lexical-exit-breakup byte-compile)
1694               ((nlx-info) node results num-args segment)
1695   (assert (and (zerop num-args) (zerop results)))
1696   (let ((nlx-info (continuation-value nlx-info)))
1697     (when (ecase (cleanup-kind (nlx-info-cleanup nlx-info))
1698             (:block
1699              ;; We only want to do this for the fall-though case.
1700              (not (eq (car (block-pred (node-block node)))
1701                       (nlx-info-target nlx-info))))
1702             (:tagbody
1703              ;; Only want to do it once per tagbody.
1704              (not (byte-nlx-info-duplicate (nlx-info-info nlx-info)))))
1705       (output-do-xop segment 'breakup))))
1706
1707 (defoptimizer (%nlx-entry byte-annotate) ((nlx-info) node)
1708   (annotate-continuation nlx-info 0)
1709   (annotate-continuation (basic-combination-fun node) 0)
1710   (setf (node-tail-p node) nil)
1711   t)
1712
1713 (defoptimizer (%nlx-entry byte-compile)
1714               ((nlx-info) node results num-args segment)
1715   (progn node results) ; ignore
1716   (assert (eql num-args 0))
1717   (let* ((info (continuation-value nlx-info))
1718          (byte-info (nlx-info-info info)))
1719     (output-label segment (byte-nlx-info-label byte-info))
1720     ;; ### :non-local-entry
1721     (ecase (cleanup-kind (nlx-info-cleanup info))
1722       ((:catch :block)
1723        (checked-canonicalize-values segment
1724                                     (nlx-info-continuation info)
1725                                     :unknown))
1726       ((:tagbody :unwind-protect)))))
1727
1728 (defoptimizer (%unwind-protect byte-annotate)
1729               ((nlx-info cleanup-fun) node)
1730   (annotate-continuation nlx-info 0)
1731   (annotate-continuation cleanup-fun 0)
1732   (annotate-continuation (basic-combination-fun node) 0)
1733   (setf (node-tail-p node) nil)
1734   t)
1735
1736 (defoptimizer (%unwind-protect byte-compile)
1737               ((nlx-info cleanup-fun) node results num-args segment)
1738   (assert (and (zerop num-args) (zerop results)))
1739   (output-do-xop segment 'unwind-protect)
1740   (output-reference segment
1741                     (byte-nlx-info-label
1742                      (nlx-info-info
1743                       (continuation-value nlx-info)))))
1744
1745 (defoptimizer (%unwind-protect-breakup byte-compile)
1746               (() node results num-args segment)
1747   (progn node) ; ignore
1748   (assert (and (zerop num-args) (zerop results)))
1749   (output-do-xop segment 'breakup))
1750
1751 (defoptimizer (%continue-unwind byte-annotate) ((a b c) node)
1752   (annotate-continuation a 0)
1753   (annotate-continuation b 0)
1754   (annotate-continuation c 0)
1755   (annotate-continuation (basic-combination-fun node) 0)
1756   (setf (node-tail-p node) nil)
1757   t)
1758
1759 (defoptimizer (%continue-unwind byte-compile)
1760               ((a b c) node results num-args segment)
1761   (progn node) ; ignore
1762   (assert (member results '(0 nil)))
1763   (assert (eql num-args 0))
1764   (output-do-xop segment 'breakup))
1765
1766 (defoptimizer (%load-time-value byte-annotate) ((handle) node)
1767   (annotate-continuation handle 0)
1768   (annotate-continuation (basic-combination-fun node) 0)
1769   (setf (node-tail-p node) nil)
1770   t)
1771
1772 (defoptimizer (%load-time-value byte-compile)
1773               ((handle) node results num-args segment)
1774   (progn node) ; ignore
1775   (assert (zerop num-args))
1776   (output-push-load-time-constant segment :load-time-value
1777                                   (continuation-value handle))
1778   (canonicalize-values segment results 1))
1779 \f
1780 ;;; Make a byte-function for LAMBDA.
1781 (defun make-xep-for (lambda)
1782   (flet ((entry-point-for (entry)
1783            (let ((info (lambda-info entry)))
1784              (assert (byte-lambda-info-interesting info))
1785              (sb!assem:label-position (byte-lambda-info-label info)))))
1786     (let ((entry (lambda-entry-function lambda)))
1787       (etypecase entry
1788         (optional-dispatch
1789          (let ((rest-arg-p nil)
1790                (num-more 0))
1791            (declare (type index num-more))
1792            (collect ((keywords))
1793              (dolist (var (nthcdr (optional-dispatch-max-args entry)
1794                                   (optional-dispatch-arglist entry)))
1795                (let ((arg-info (lambda-var-arg-info var)))
1796                  (assert arg-info)
1797                  (ecase (arg-info-kind arg-info)
1798                    (:rest
1799                     (assert (not rest-arg-p))
1800                     (incf num-more)
1801                     (setf rest-arg-p t))
1802                    (:keyword
1803                     (let ((s-p (arg-info-supplied-p arg-info))
1804                           (default (arg-info-default arg-info)))
1805                       (incf num-more (if s-p 2 1))
1806                       (keywords (list (arg-info-keyword arg-info)
1807                                       (if (constantp default)
1808                                           (eval default)
1809                                           nil)
1810                                       (if s-p t nil))))))))
1811              (make-hairy-byte-function
1812               :name (leaf-name entry)
1813               :min-args (optional-dispatch-min-args entry)
1814               :max-args (optional-dispatch-max-args entry)
1815               :entry-points
1816               (mapcar #'entry-point-for (optional-dispatch-entry-points entry))
1817               :more-args-entry-point
1818               (entry-point-for (optional-dispatch-main-entry entry))
1819               :num-more-args num-more
1820               :rest-arg-p rest-arg-p
1821               :keywords-p
1822               (if (optional-dispatch-keyp entry)
1823                   (if (optional-dispatch-allowp entry)
1824                       :allow-others t))
1825               :keywords (keywords)))))
1826         (clambda
1827          (let ((args (length (lambda-vars entry))))
1828            (make-simple-byte-function
1829             :name (leaf-name entry)
1830             :num-args args
1831             :entry-point (entry-point-for entry))))))))
1832
1833 (defun generate-xeps (component)
1834   (let ((xeps nil))
1835     (dolist (lambda (component-lambdas component))
1836       (when (member (lambda-kind lambda) '(:external :top-level))
1837         (push (cons lambda (make-xep-for lambda)) xeps)))
1838     xeps))
1839 \f
1840 ;;;; noise to actually do the compile
1841
1842 (defun assign-locals (component)
1843   ;; Process all of the lambdas in component, and assign stack frame
1844   ;; locations for all the locals.
1845   (dolist (lambda (component-lambdas component))
1846     ;; We don't generate any code for :external lambdas, so we don't need
1847     ;; to allocate stack space. Also, we don't use the ``more'' entry,
1848     ;; so we don't need code for it.
1849     (cond
1850      ((or (eq (lambda-kind lambda) :external)
1851           (and (eq (lambda-kind lambda) :optional)
1852                (eq (optional-dispatch-more-entry
1853                     (lambda-optional-dispatch lambda))
1854                    lambda)))
1855       (setf (lambda-info lambda)
1856             (make-byte-lambda-info :interesting nil)))
1857      (t
1858       (let ((num-locals 0))
1859         (let* ((vars (lambda-vars lambda))
1860                (arg-num (+ (length vars)
1861                            (length (environment-closure
1862                                     (lambda-environment lambda))))))
1863           (dolist (var vars)
1864             (decf arg-num)
1865             (cond ((or (lambda-var-sets var) (lambda-var-indirect var))
1866                    (setf (leaf-info var)
1867                          (make-byte-lambda-var-info :offset num-locals))
1868                    (incf num-locals))
1869                   ((leaf-refs var)
1870                    (setf (leaf-info var)
1871                          (make-byte-lambda-var-info :argp t
1872                                                     :offset arg-num))))))
1873         (dolist (let (lambda-lets lambda))
1874           (dolist (var (lambda-vars let))
1875             (setf (leaf-info var)
1876                   (make-byte-lambda-var-info :offset num-locals))
1877             (incf num-locals)))
1878         (let ((entry-nodes-already-done nil))
1879           (dolist (nlx-info (environment-nlx-info (lambda-environment lambda)))
1880             (ecase (cleanup-kind (nlx-info-cleanup nlx-info))
1881               (:block
1882                (setf (nlx-info-info nlx-info)
1883                      (make-byte-nlx-info :stack-slot num-locals))
1884                (incf num-locals))
1885               (:tagbody
1886                (let* ((entry (cleanup-mess-up (nlx-info-cleanup nlx-info)))
1887                       (cruft (assoc entry entry-nodes-already-done)))
1888                  (cond (cruft
1889                         (setf (nlx-info-info nlx-info)
1890                               (make-byte-nlx-info :stack-slot (cdr cruft)
1891                                                   :duplicate t)))
1892                        (t
1893                         (push (cons entry num-locals) entry-nodes-already-done)
1894                         (setf (nlx-info-info nlx-info)
1895                               (make-byte-nlx-info :stack-slot num-locals))
1896                         (incf num-locals)))))
1897               ((:catch :unwind-protect)
1898                (setf (nlx-info-info nlx-info) (make-byte-nlx-info))))))
1899         (setf (lambda-info lambda)
1900               (make-byte-lambda-info :stack-size num-locals))))))
1901
1902   (values))
1903
1904 (defun byte-compile-component (component)
1905   (setf (component-info component) (make-byte-component-info))
1906   (maybe-mumble "ByteAnn ")
1907
1908   ;; Assign offsets for all the locals, and figure out which args can
1909   ;; stay in the argument area and which need to be moved into locals.
1910   (assign-locals component)
1911
1912   ;; Annotate every continuation with information about how we want the
1913   ;; values.
1914   (annotate-ir1 component)
1915
1916   ;; Determine what stack values are dead, and emit cleanup code to pop
1917   ;; them.
1918   (byte-stack-analyze component)
1919
1920   ;; Make sure any newly added blocks have a block-number.
1921   (dfo-as-needed component)
1922
1923   ;; Assign an ordering of the blocks.
1924   (control-analyze component #'make-byte-block-info)
1925
1926   ;; Find the start labels for the lambdas.
1927   (dolist (lambda (component-lambdas component))
1928     (let ((info (lambda-info lambda)))
1929       (when (byte-lambda-info-interesting info)
1930         (setf (byte-lambda-info-label info)
1931               (byte-block-info-label
1932                (block-info (node-block (lambda-bind lambda))))))))
1933
1934   ;; Delete any blocks that we are not going to emit from the emit order.
1935   (do-blocks (block component)
1936     (unless (block-interesting block)
1937       (let* ((info (block-info block))
1938              (prev (byte-block-info-prev info))
1939              (next (byte-block-info-next info)))
1940         (setf (byte-block-info-next prev) next)
1941         (setf (byte-block-info-prev next) prev))))
1942
1943   (maybe-mumble "ByteGen ")
1944   (let ((segment nil))
1945     (unwind-protect
1946         (progn
1947           (setf segment (sb!assem:make-segment :name "Byte Output"))
1948           (generate-byte-code segment component)
1949           (let ((code-length (sb!assem:finalize-segment segment))
1950                 (xeps (generate-xeps component))
1951                 (constants (byte-component-info-constants
1952                             (component-info component))))
1953             #!+sb-show
1954             (when *compiler-trace-output*
1955               (describe-component component *compiler-trace-output*)
1956               (describe-byte-component component xeps segment
1957                                        *compiler-trace-output*))
1958             (etypecase *compile-object*
1959               (fasl-file
1960                (maybe-mumble "FASL")
1961                (fasl-dump-byte-component segment code-length constants xeps
1962                                          *compile-object*))
1963               (core-object
1964                (maybe-mumble "Core")
1965                (make-core-byte-component segment code-length constants xeps
1966                                          *compile-object*))
1967               (null))))))
1968   (values))
1969 \f
1970 ;;;; extra stuff for debugging
1971
1972 #!+sb-show
1973 (defun dump-stack-info (component)
1974   (do-blocks (block component)
1975      (when (block-interesting block)
1976        (print-nodes block)
1977        (let ((info (block-info block)))
1978          (cond
1979           (info
1980            (format t
1981            "start-stack ~S~%consume ~S~%produce ~S~%end-stack ~S~%~
1982             total-consume ~S~%~@[nlx-entries ~S~%~]~@[nlx-entry-p ~S~%~]"
1983            (byte-block-info-start-stack info)
1984            (byte-block-info-consumes info)
1985            (byte-block-info-produces info)
1986            (byte-block-info-end-stack info)
1987            (byte-block-info-total-consumes info)
1988            (byte-block-info-nlx-entries info)
1989            (byte-block-info-nlx-entry-p info)))
1990           (t
1991            (format t "no info~%")))))))