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