79b992ab5bacbc7fb73b135d29d79dddec656a99
[sbcl.git] / src / compiler / assem.lisp
1 ;;;; scheduling assembler
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!ASSEM")
13 \f
14 ;;;; assembly control parameters
15
16 (defvar *assem-scheduler-p* nil)
17 (declaim (type boolean *assem-scheduler-p*))
18
19 (defvar *assem-instructions* (make-hash-table :test 'equal))
20 (declaim (type hash-table *assem-instructions*))
21
22 (defvar *assem-max-locations* 0)
23 (declaim (type index *assem-max-locations*))
24 \f
25 ;;;; the SEGMENT structure
26
27 ;;; This structure holds the state of the assembler.
28 (defstruct (segment (:copier nil))
29   ;; the name of this segment (for debugging output and stuff)
30   (name "Unnamed" :type simple-base-string)
31   ;; Ordinarily this is a vector where instructions are written. If
32   ;; the segment is made invalid (e.g. by APPEND-SEGMENT) then the
33   ;; vector can be replaced by NIL.
34   (buffer (make-array 0
35                       :fill-pointer 0
36                       :adjustable t
37                       :element-type 'assembly-unit)
38           :type (or null (vector assembly-unit)))
39   ;; whether or not to run the scheduler. Note: if the instruction
40   ;; definitions were not compiled with the scheduler turned on, this
41   ;; has no effect.
42   (run-scheduler nil)
43   ;; If a function, then this is funcalled for each inst emitted with
44   ;; the segment, the VOP, the name of the inst (as a string), and the
45   ;; inst arguments.
46   (inst-hook nil :type (or function null))
47   ;; what position does this correspond to? Initially, positions and
48   ;; indexes are the same, but after we start collapsing choosers,
49   ;; positions can change while indexes stay the same.
50   (current-posn 0 :type index)
51   ;; a list of all the annotations that have been output to this segment
52   (annotations nil :type list)
53   ;; a pointer to the last cons cell in the annotations list. This is
54   ;; so we can quickly add things to the end of the annotations list.
55   (last-annotation nil :type list)
56   ;; the number of bits of alignment at the last time we synchronized
57   (alignment max-alignment :type alignment)
58   ;; the position the last time we synchronized
59   (sync-posn 0 :type index)
60   ;; The posn and index everything ends at. This is not maintained
61   ;; while the data is being generated, but is filled in after.
62   ;; Basically, we copy current-posn and current-index so that we can
63   ;; trash them while processing choosers and back-patches.
64   (final-posn 0 :type index)
65   (final-index 0 :type index)
66   ;; *** State used by the scheduler during instruction queueing.
67   ;;
68   ;; a list of postits. These are accumulated between instructions.
69   (postits nil :type list)
70   ;; ``Number'' for last instruction queued. Used only to supply insts
71   ;; with unique sset-element-number's.
72   (inst-number 0 :type index)
73   ;; SIMPLE-VECTORs mapping locations to the instruction that reads them and
74   ;; instructions that write them
75   (readers (make-array *assem-max-locations* :initial-element nil)
76            :type simple-vector)
77   (writers (make-array *assem-max-locations* :initial-element nil)
78            :type simple-vector)
79   ;; The number of additional cycles before the next control transfer,
80   ;; or NIL if a control transfer hasn't been queued. When a delayed
81   ;; branch is queued, this slot is set to the delay count.
82   (branch-countdown nil :type (or null (and fixnum unsigned-byte)))
83   ;; *** These two slots are used both by the queuing noise and the
84   ;; scheduling noise.
85   ;;
86   ;; All the instructions that are pending and don't have any
87   ;; unresolved dependents. We don't list branches here even if they
88   ;; would otherwise qualify. They are listed above.
89   (emittable-insts-sset (make-sset) :type sset)
90   ;; list of queued branches. We handle these specially, because they
91   ;; have to be emitted at a specific place (e.g. one slot before the
92   ;; end of the block).
93   (queued-branches nil :type list)
94   ;; *** state used by the scheduler during instruction scheduling.
95   ;;
96   ;; the instructions who would have had a read dependent removed if
97   ;; it were not for a delay slot. This is a list of lists. Each
98   ;; element in the top level list corresponds to yet another cycle of
99   ;; delay. Each element in the second level lists is a dotted pair,
100   ;; holding the dependency instruction and the dependent to remove.
101   (delayed nil :type list)
102   ;; The emittable insts again, except this time as a list sorted by depth.
103   (emittable-insts-queue nil :type list)
104   ;; Whether or not to collect dynamic statistics. This is just the same as
105   ;; *COLLECT-DYNAMIC-STATISTICS* but is faster to reference.
106   #!+sb-dyncount
107   (collect-dynamic-statistics nil))
108 (sb!c::defprinter (segment)
109   name)
110
111 ;;; where the next byte of output goes
112 #!-sb-fluid (declaim (inline segment-current-index))
113 (defun segment-current-index (segment)
114   (fill-pointer (segment-buffer segment)))
115 (defun (setf segment-current-index) (new-value segment)
116   (let ((buffer (segment-buffer segment)))
117     ;; Make sure that the array is big enough.
118     (do ()
119         ((>= (array-dimension buffer 0) new-value))
120       ;; When we have to increase the size of the array, we want to
121       ;; roughly double the vector length: that way growing the array
122       ;; to size N conses only O(N) bytes in total. But just doubling
123       ;; the length would leave a zero-length vector unchanged. Hence,
124       ;; take the MAX with 1..
125       (adjust-array buffer (max 1 (* 2 (array-dimension buffer 0)))))
126     ;; Now that the array has the intended next free byte, we can point to it.
127     (setf (fill-pointer buffer) new-value)))
128 \f
129 ;;;; structures/types used by the scheduler
130
131 (sb!c:def-boolean-attribute instruction
132   ;; This attribute is set if the scheduler can freely flush this
133   ;; instruction if it thinks it is not needed. Examples are NOP and
134   ;; instructions that have no side effect not described by the
135   ;; writes.
136   flushable
137   ;; This attribute is set when an instruction can cause a control
138   ;; transfer. For test instructions, the delay is used to determine
139   ;; how many instructions follow the branch.
140   branch
141   ;; This attribute indicates that this ``instruction'' can be
142   ;; variable length, and therefore better never be used in a branch
143   ;; delay slot.
144   variable-length)
145
146 (defstruct (instruction
147             (:include sset-element)
148             (:conc-name inst-)
149             (:constructor make-instruction (number emitter attributes delay))
150             (:copier nil))
151   ;; The function to envoke to actually emit this instruction. Gets called
152   ;; with the segment as its one argument.
153   (emitter (required-argument) :type (or null function))
154   ;; The attributes of this instruction.
155   (attributes (instruction-attributes) :type sb!c:attributes)
156   ;; Number of instructions or cycles of delay before additional
157   ;; instructions can read our writes.
158   (delay 0 :type (and fixnum unsigned-byte))
159   ;; the maximum number of instructions in the longest dependency
160   ;; chain from this instruction to one of the independent
161   ;; instructions. This is used as a heuristic at to which
162   ;; instructions should be scheduled first.
163   (depth nil :type (or null (and fixnum unsigned-byte)))
164   ;; Note: When trying remember which of the next four is which, note
165   ;; that the ``read'' or ``write'' always refers to the dependent
166   ;; (second) instruction.
167   ;;
168   ;; instructions whose writes this instruction tries to read
169   (read-dependencies (make-sset) :type sset)
170   ;; instructions whose writes or reads are overwritten by this instruction
171   (write-dependencies (make-sset) :type sset)
172   ;; instructions which write what we read or write
173   (write-dependents (make-sset) :type sset)
174   ;; instructions which read what we write
175   (read-dependents (make-sset) :type sset))
176 #!+sb-show-assem (defvar *inst-ids* (make-hash-table :test 'eq))
177 #!+sb-show-assem (defvar *next-inst-id* 0)
178 (sb!int:def!method print-object ((inst instruction) stream)
179   (print-unreadable-object (inst stream :type t :identity t)
180     #!+sb-show-assem
181     (princ (or (gethash inst *inst-ids*)
182                (setf (gethash inst *inst-ids*)
183                      (incf *next-inst-id*)))
184            stream)
185     (format stream
186             #!+sb-show-assem " emitter=~S" #!-sb-show-assem "emitter=~S"
187             (let ((emitter (inst-emitter inst)))
188               (if emitter
189                   (multiple-value-bind (lambda lexenv-p name)
190                       (function-lambda-expression emitter)
191                     (declare (ignore lambda lexenv-p))
192                     name)
193                   '<flushed>)))
194     (when (inst-depth inst)
195       (format stream ", depth=~D" (inst-depth inst)))))
196
197 #!+sb-show-assem
198 (defun reset-inst-ids ()
199   (clrhash *inst-ids*)
200   (setf *next-inst-id* 0))
201 \f
202 ;;;; the scheduler itself
203
204 (defmacro without-scheduling ((&optional (segment '**current-segment**))
205                               &body body)
206   #!+sb-doc
207   "Execute BODY (as a PROGN) without scheduling any of the instructions
208    generated inside it. This is not protected by UNWIND-PROTECT, so
209    DO NOT use THROW or RETURN-FROM to escape from it."
210   ;; FIXME: Why not just use UNWIND-PROTECT? Or is there some other
211   ;; reason why we shouldn't use THROW or RETURN-FROM?
212   (let ((var (gensym))
213         (seg (gensym)))
214     `(let* ((,seg ,segment)
215             (,var (segment-run-scheduler ,seg)))
216        (when ,var
217          (schedule-pending-instructions ,seg)
218          (setf (segment-run-scheduler ,seg) nil))
219        ,@body
220        (setf (segment-run-scheduler ,seg) ,var))))
221
222 (defmacro note-dependencies ((segment inst) &body body)
223   (sb!int:once-only ((segment segment) (inst inst))
224     `(macrolet ((reads (loc) `(note-read-dependency ,',segment ,',inst ,loc))
225                 (writes (loc &rest keys)
226                   `(note-write-dependency ,',segment ,',inst ,loc ,@keys)))
227        ,@body)))
228
229 (defun note-read-dependency (segment inst read)
230   (multiple-value-bind (loc-num size)
231       (sb!c:location-number read)
232     #!+sb-show-assem (format *trace-output*
233                              "~&~S reads ~S[~D for ~D]~%"
234                              inst read loc-num size)
235     (when loc-num
236       ;; Iterate over all the locations for this TN.
237       (do ((index loc-num (1+ index))
238            (end-loc (+ loc-num (or size 1))))
239           ((>= index end-loc))
240         (declare (type (mod 2048) index end-loc))
241         (let ((writers (svref (segment-writers segment) index)))
242           (when writers
243             ;; The inst that wrote the value we want to read must have
244             ;; completed.
245             (let ((writer (car writers)))
246               (sset-adjoin writer (inst-read-dependencies inst))
247               (sset-adjoin inst (inst-read-dependents writer))
248               (sset-delete writer (segment-emittable-insts-sset segment))
249               ;; And it must have been completed *after* all other
250               ;; writes to that location. Actually, that isn't quite
251               ;; true. Each of the earlier writes could be done
252               ;; either before this last write, or after the read, but
253               ;; we have no way of representing that.
254               (dolist (other-writer (cdr writers))
255                 (sset-adjoin other-writer (inst-write-dependencies writer))
256                 (sset-adjoin writer (inst-write-dependents other-writer))
257                 (sset-delete other-writer
258                              (segment-emittable-insts-sset segment))))
259             ;; And we don't need to remember about earlier writes any
260             ;; more. Shortening the writers list means that we won't
261             ;; bother generating as many explicit arcs in the graph.
262             (setf (cdr writers) nil)))
263         (push inst (svref (segment-readers segment) index)))))
264   (values))
265
266 (defun note-write-dependency (segment inst write &key partially)
267   (multiple-value-bind (loc-num size)
268       (sb!c:location-number write)
269     #!+sb-show-assem (format *trace-output*
270                              "~&~S writes ~S[~D for ~D]~%"
271                              inst write loc-num size)
272     (when loc-num
273       ;; Iterate over all the locations for this TN.
274       (do ((index loc-num (1+ index))
275            (end-loc (+ loc-num (or size 1))))
276           ((>= index end-loc))
277         (declare (type (mod 2048) index end-loc))
278         ;; All previous reads of this location must have completed.
279         (dolist (prev-inst (svref (segment-readers segment) index))
280           (unless (eq prev-inst inst)
281             (sset-adjoin prev-inst (inst-write-dependencies inst))
282             (sset-adjoin inst (inst-write-dependents prev-inst))
283             (sset-delete prev-inst (segment-emittable-insts-sset segment))))
284         (when partially
285           ;; All previous writes to the location must have completed.
286           (dolist (prev-inst (svref (segment-writers segment) index))
287             (sset-adjoin prev-inst (inst-write-dependencies inst))
288             (sset-adjoin inst (inst-write-dependents prev-inst))
289             (sset-delete prev-inst (segment-emittable-insts-sset segment)))
290           ;; And we can forget about remembering them, because
291           ;; depending on us is as good as depending on them.
292           (setf (svref (segment-writers segment) index) nil))
293         (push inst (svref (segment-writers segment) index)))))
294   (values))
295
296 ;;; This routine is called by due to uses of the INST macro when the
297 ;;; scheduler is turned on. The change to the dependency graph has
298 ;;; already been computed, so we just have to check to see whether the
299 ;;; basic block is terminated.
300 (defun queue-inst (segment inst)
301   #!+sb-show-assem (format *trace-output* "~&queuing ~S~%" inst)
302   #!+sb-show-assem (format *trace-output*
303                            "  reads ~S~%  writes ~S~%"
304                            (sb!int:collect ((reads))
305                              (do-sset-elements (read
306                                                 (inst-read-dependencies inst))
307                                 (reads read))
308                              (reads))
309                            (sb!int:collect ((writes))
310                              (do-sset-elements (write
311                                                 (inst-write-dependencies inst))
312                                 (writes write))
313                              (writes)))
314   (assert (segment-run-scheduler segment))
315   (let ((countdown (segment-branch-countdown segment)))
316     (when countdown
317       (decf countdown)
318       (assert (not (instruction-attributep (inst-attributes inst)
319                                            variable-length))))
320     (cond ((instruction-attributep (inst-attributes inst) branch)
321            (unless countdown
322              (setf countdown (inst-delay inst)))
323            (push (cons countdown inst)
324                  (segment-queued-branches segment)))
325           (t
326            (sset-adjoin inst (segment-emittable-insts-sset segment))))
327     (when countdown
328       (setf (segment-branch-countdown segment) countdown)
329       (when (zerop countdown)
330         (schedule-pending-instructions segment))))
331   (values))
332
333 ;;; Emit all the pending instructions, and reset any state. This is
334 ;;; called whenever we hit a label (i.e. an entry point of some kind)
335 ;;; and when the user turns the scheduler off (otherwise, the queued
336 ;;; instructions would sit there until the scheduler was turned back
337 ;;; on, and emitted in the wrong place).
338 (defun schedule-pending-instructions (segment)
339   (assert (segment-run-scheduler segment))
340
341   ;; Quick blow-out if nothing to do.
342   (when (and (sset-empty (segment-emittable-insts-sset segment))
343              (null (segment-queued-branches segment)))
344     (return-from schedule-pending-instructions
345                  (values)))
346
347   #!+sb-show-assem (format *trace-output*
348                            "~&scheduling pending instructions..~%")
349
350   ;; Note that any values live at the end of the block have to be
351   ;; computed last.
352   (let ((emittable-insts (segment-emittable-insts-sset segment))
353         (writers (segment-writers segment)))
354     (dotimes (index (length writers))
355       (let* ((writer (svref writers index))
356              (inst (car writer))
357              (overwritten (cdr writer)))
358         (when writer
359           (when overwritten
360             (let ((write-dependencies (inst-write-dependencies inst)))
361               (dolist (other-inst overwritten)
362                 (sset-adjoin inst (inst-write-dependents other-inst))
363                 (sset-adjoin other-inst write-dependencies)
364                 (sset-delete other-inst emittable-insts))))
365           ;; If the value is live at the end of the block, we can't flush it.
366           (setf (instruction-attributep (inst-attributes inst) flushable)
367                 nil)))))
368
369   ;; Grovel through the entire graph in the forward direction finding
370   ;; all the leaf instructions.
371   (labels ((grovel-inst (inst)
372              (let ((max 0))
373                (do-sset-elements (dep (inst-write-dependencies inst))
374                  (let ((dep-depth (or (inst-depth dep) (grovel-inst dep))))
375                    (when (> dep-depth max)
376                      (setf max dep-depth))))
377                (do-sset-elements (dep (inst-read-dependencies inst))
378                  (let ((dep-depth
379                         (+ (or (inst-depth dep) (grovel-inst dep))
380                            (inst-delay dep))))
381                    (when (> dep-depth max)
382                      (setf max dep-depth))))
383                (cond ((and (sset-empty (inst-read-dependents inst))
384                            (instruction-attributep (inst-attributes inst)
385                                                    flushable))
386                       #!+sb-show-assem (format *trace-output*
387                                                "flushing ~S~%"
388                                                inst)
389                       (setf (inst-emitter inst) nil)
390                       (setf (inst-depth inst) max))
391                      (t
392                       (setf (inst-depth inst) max))))))
393     (let ((emittable-insts nil)
394           (delayed nil))
395       (do-sset-elements (inst (segment-emittable-insts-sset segment))
396         (grovel-inst inst)
397         (if (zerop (inst-delay inst))
398             (push inst emittable-insts)
399             (setf delayed
400                   (add-to-nth-list delayed inst (1- (inst-delay inst))))))
401       (setf (segment-emittable-insts-queue segment)
402             (sort emittable-insts #'> :key #'inst-depth))
403       (setf (segment-delayed segment) delayed))
404     (dolist (branch (segment-queued-branches segment))
405       (grovel-inst (cdr branch))))
406   #!+sb-show-assem (format *trace-output*
407                            "queued branches: ~S~%"
408                            (segment-queued-branches segment))
409   #!+sb-show-assem (format *trace-output*
410                            "initially emittable: ~S~%"
411                            (segment-emittable-insts-queue segment))
412   #!+sb-show-assem (format *trace-output*
413                            "initially delayed: ~S~%"
414                            (segment-delayed segment))
415
416   ;; Accumulate the results in reverse order. Well, actually, this
417   ;; list will be in forward order, because we are generating the
418   ;; reverse order in reverse.
419   (let ((results nil))
420
421     ;; Schedule all the branches in their exact locations.
422     (let ((insts-from-end (segment-branch-countdown segment)))
423       (dolist (branch (segment-queued-branches segment))
424         (let ((inst (cdr branch)))
425           (dotimes (i (- (car branch) insts-from-end))
426             ;; Each time through this loop we need to emit another
427             ;; instruction. First, we check to see whether there is
428             ;; any instruction that must be emitted before (i.e. must
429             ;; come after) the branch inst. If so, emit it. Otherwise,
430             ;; just pick one of the emittable insts. If there is
431             ;; nothing to do, then emit a nop. ### Note: despite the
432             ;; fact that this is a loop, it really won't work for
433             ;; repetitions other then zero and one. For example, if
434 p           ;; the branch has two dependents and one of them dpends on
435             ;; the other, then the stuff that grabs a dependent could
436             ;; easily grab the wrong one. But I don't feel like fixing
437             ;; this because it doesn't matter for any of the
438             ;; architectures we are using or plan on using.
439             (flet ((maybe-schedule-dependent (dependents)
440                      (do-sset-elements (inst dependents)
441                        ;; If do-sset-elements enters the body, then there is a
442                        ;; dependent. Emit it.
443                        (note-resolved-dependencies segment inst)
444                        ;; Remove it from the emittable insts.
445                        (setf (segment-emittable-insts-queue segment)
446                              (delete inst
447                                      (segment-emittable-insts-queue segment)
448                                      :test #'eq))
449                        ;; And if it was delayed, removed it from the delayed
450                        ;; list. This can happen if there is a load in a
451                        ;; branch delay slot.
452                        (block scan-delayed
453                          (do ((delayed (segment-delayed segment)
454                                        (cdr delayed)))
455                              ((null delayed))
456                            (do ((prev nil cons)
457                                 (cons (car delayed) (cdr cons)))
458                                ((null cons))
459                              (when (eq (car cons) inst)
460                                (if prev
461                                    (setf (cdr prev) (cdr cons))
462                                    (setf (car delayed) (cdr cons)))
463                                (return-from scan-delayed nil)))))
464                        ;; And return it.
465                        (return inst))))
466               (let ((fill (or (maybe-schedule-dependent
467                                (inst-read-dependents inst))
468                               (maybe-schedule-dependent
469                                (inst-write-dependents inst))
470                               (schedule-one-inst segment t)
471                               :nop)))
472                 #!+sb-show-assem (format *trace-output*
473                                          "filling branch delay slot with ~S~%"
474                                          fill)
475                 (push fill results)))
476             (advance-one-inst segment)
477             (incf insts-from-end))
478           (note-resolved-dependencies segment inst)
479           (push inst results)
480           #!+sb-show-assem (format *trace-output* "emitting ~S~%" inst)
481           (advance-one-inst segment))))
482
483     ;; Keep scheduling stuff until we run out.
484     (loop
485       (let ((inst (schedule-one-inst segment nil)))
486         (unless inst
487           (return))
488         (push inst results)
489         (advance-one-inst segment)))
490
491     ;; Now call the emitters, but turn the scheduler off for the duration.
492     (setf (segment-run-scheduler segment) nil)
493     (dolist (inst results)
494       (if (eq inst :nop)
495           (sb!c:emit-nop segment)
496           (funcall (inst-emitter inst) segment)))
497     (setf (segment-run-scheduler segment) t))
498
499   ;; Clear out any residue left over.
500   (setf (segment-inst-number segment) 0)
501   (setf (segment-queued-branches segment) nil)
502   (setf (segment-branch-countdown segment) nil)
503   (setf (segment-emittable-insts-sset segment) (make-sset))
504   (fill (segment-readers segment) nil)
505   (fill (segment-writers segment) nil)
506
507   ;; That's all, folks.
508   (values))
509
510 ;;; a utility for maintaining the segment-delayed list. We cdr down
511 ;;; list n times (extending it if necessary) and then push thing on
512 ;;; into the car of that cons cell.
513 (defun add-to-nth-list (list thing n)
514   (do ((cell (or list (setf list (list nil)))
515              (or (cdr cell) (setf (cdr cell) (list nil))))
516        (i n (1- i)))
517       ((zerop i)
518        (push thing (car cell))
519        list)))
520
521 ;;; Find the next instruction to schedule and return it after updating
522 ;;; any dependency information. If we can't do anything useful right
523 ;;; now, but there is more work to be done, return :NOP to indicate
524 ;;; that a nop must be emitted. If we are all done, return NIL.
525 (defun schedule-one-inst (segment delay-slot-p)
526   (do ((prev nil remaining)
527        (remaining (segment-emittable-insts-queue segment) (cdr remaining)))
528       ((null remaining))
529     (let ((inst (car remaining)))
530       (unless (and delay-slot-p
531                    (instruction-attributep (inst-attributes inst)
532                                            variable-length))
533         ;; We've got us a live one here. Go for it.
534         #!+sb-show-assem (format *trace-output* "emitting ~S~%" inst)
535         ;; Delete it from the list of insts.
536         (if prev
537             (setf (cdr prev) (cdr remaining))
538             (setf (segment-emittable-insts-queue segment)
539                   (cdr remaining)))
540         ;; Note that this inst has been emitted.
541         (note-resolved-dependencies segment inst)
542         ;; And return.
543         (return-from schedule-one-inst
544                      ;; Are we wanting to flush this instruction?
545                      (if (inst-emitter inst)
546                          ;; Nope, it's still a go. So return it.
547                          inst
548                          ;; Yes, so pick a new one. We have to start
549                          ;; over, because note-resolved-dependencies
550                          ;; might have changed the emittable-insts-queue.
551                          (schedule-one-inst segment delay-slot-p))))))
552   ;; Nothing to do, so make something up.
553   (cond ((segment-delayed segment)
554          ;; No emittable instructions, but we have more work to do. Emit
555          ;; a NOP to fill in a delay slot.
556          #!+sb-show-assem (format *trace-output* "emitting a NOP~%")
557          :nop)
558         (t
559          ;; All done.
560          nil)))
561
562 ;;; This function is called whenever an instruction has been
563 ;;; scheduled, and we want to know what possibilities that opens up.
564 ;;; So look at all the instructions that this one depends on, and
565 ;;; remove this instruction from their dependents list. If we were the
566 ;;; last dependent, then that dependency can be emitted now.
567 (defun note-resolved-dependencies (segment inst)
568   (assert (sset-empty (inst-read-dependents inst)))
569   (assert (sset-empty (inst-write-dependents inst)))
570   (do-sset-elements (dep (inst-write-dependencies inst))
571     ;; These are the instructions who have to be completed before our
572     ;; write fires. Doesn't matter how far before, just before.
573     (let ((dependents (inst-write-dependents dep)))
574       (sset-delete inst dependents)
575       (when (and (sset-empty dependents)
576                  (sset-empty (inst-read-dependents dep)))
577         (insert-emittable-inst segment dep))))
578   (do-sset-elements (dep (inst-read-dependencies inst))
579     ;; These are the instructions who write values we read. If there
580     ;; is no delay, then just remove us from the dependent list.
581     ;; Otherwise, record the fact that in n cycles, we should be
582     ;; removed.
583     (if (zerop (inst-delay dep))
584         (let ((dependents (inst-read-dependents dep)))
585           (sset-delete inst dependents)
586           (when (and (sset-empty dependents)
587                      (sset-empty (inst-write-dependents dep)))
588             (insert-emittable-inst segment dep)))
589         (setf (segment-delayed segment)
590               (add-to-nth-list (segment-delayed segment)
591                                (cons dep inst)
592                                (inst-delay dep)))))
593   (values))
594
595 ;;; Process the next entry in segment-delayed. This is called whenever
596 ;;; anyone emits an instruction.
597 (defun advance-one-inst (segment)
598   (let ((delayed-stuff (pop (segment-delayed segment))))
599     (dolist (stuff delayed-stuff)
600       (if (consp stuff)
601           (let* ((dependency (car stuff))
602                  (dependent (cdr stuff))
603                  (dependents (inst-read-dependents dependency)))
604             (sset-delete dependent dependents)
605             (when (and (sset-empty dependents)
606                        (sset-empty (inst-write-dependents dependency)))
607               (insert-emittable-inst segment dependency)))
608           (insert-emittable-inst segment stuff)))))
609
610 ;;; Note that inst is emittable by sticking it in the
611 ;;; SEGMENT-EMITTABLE-INSTS-QUEUE list. We keep the emittable-insts
612 ;;; sorted with the largest ``depths'' first. Except that if INST is a
613 ;;; branch, don't bother. It will be handled correctly by the branch
614 ;;; emitting code in SCHEDULE-PENDING-INSTRUCTIONS.
615 (defun insert-emittable-inst (segment inst)
616   (unless (instruction-attributep (inst-attributes inst) branch)
617     #!+sb-show-assem (format *trace-output* "now emittable: ~S~%" inst)
618     (do ((my-depth (inst-depth inst))
619          (remaining (segment-emittable-insts-queue segment) (cdr remaining))
620          (prev nil remaining))
621         ((or (null remaining) (> my-depth (inst-depth (car remaining))))
622          (if prev
623              (setf (cdr prev) (cons inst remaining))
624              (setf (segment-emittable-insts-queue segment)
625                    (cons inst remaining))))))
626   (values))
627 \f
628 ;;;; structure used during output emission
629
630 ;;; common supertype for all the different kinds of annotations
631 (defstruct (annotation (:constructor nil)
632                        (:copier nil))
633   ;; Where in the raw output stream was this annotation emitted.
634   (index 0 :type index)
635   ;; What position does that correspond to.
636   (posn nil :type (or index null)))
637
638 (defstruct (label (:include annotation)
639                   (:constructor gen-label ())
640                   (:copier nil))
641   ;; (doesn't need any additional information beyond what is in the
642   ;; annotation structure)
643   )
644 (sb!int:def!method print-object ((label label) stream)
645   (if (or *print-escape* *print-readably*)
646       (print-unreadable-object (label stream :type t)
647         (prin1 (sb!c:label-id label) stream))
648       (format stream "L~D" (sb!c:label-id label))))
649
650 ;;; a constraint on how the output stream must be aligned
651 (defstruct (alignment-note
652             (:include annotation)
653             (:conc-name alignment-)
654             (:predicate alignment-p)
655             (:constructor make-alignment (bits size fill-byte))
656             (:copier nil))
657   ;; The minimum number of low-order bits that must be zero.
658   (bits 0 :type alignment)
659   ;; The amount of filler we are assuming this alignment op will take.
660   (size 0 :type (integer 0 #.(1- (ash 1 max-alignment))))
661   ;; The byte used as filling.
662   (fill-byte 0 :type (or assembly-unit (signed-byte #.assembly-unit-bits))))
663
664 ;;; a reference to someplace that needs to be back-patched when
665 ;;; we actually know what label positions, etc. are
666 (defstruct (back-patch
667             (:include annotation)
668             (:constructor make-back-patch (size function))
669             (:copier nil))
670   ;; The area effected by this back-patch.
671   (size 0 :type index)
672   ;; The function to use to generate the real data
673   (function nil :type function))
674
675 ;;; This is similar to a BACK-PATCH, but also an indication that the
676 ;;; amount of stuff output depends on label-positions, etc.
677 ;;; Back-patches can't change their mind about how much stuff to emit,
678 ;;; but choosers can.
679 (defstruct (chooser
680             (:include annotation)
681             (:constructor make-chooser
682                           (size alignment maybe-shrink worst-case-fun))
683             (:copier nil))
684   ;; the worst case size for this chooser. There is this much space
685   ;; allocated in the output buffer.
686   (size 0 :type index)
687   ;; the worst case alignment this chooser is guaranteed to preserve
688   (alignment 0 :type alignment)
689   ;; the function to call to determine of we can use a shorter
690   ;; sequence. It returns NIL if nothing shorter can be used, or emits
691   ;; that sequence and returns T.
692   (maybe-shrink nil :type function)
693   ;; the function to call to generate the worst case sequence. This is
694   ;; used when nothing else can be condensed.
695   (worst-case-fun nil :type function))
696
697 ;;; This is used internally when we figure out a chooser or alignment
698 ;;; doesn't really need as much space as we initially gave it.
699 (defstruct (filler
700             (:include annotation)
701             (:constructor make-filler (bytes))
702             (:copier nil))
703   ;; the number of bytes of filler here
704   (bytes 0 :type index))
705 \f
706 ;;;; output functions
707
708 ;;; interface: Emit the supplied BYTE to SEGMENT, growing SEGMENT if
709 ;;; necessary.
710 (defun emit-byte (segment byte)
711   (declare (type segment segment))
712   ;; We could use DECLARE instead of CHECK-TYPE here, but (1) CMU CL's
713   ;; inspired decision to treat DECLARE as ASSERT by default has not
714   ;; been copied by other compilers, and this code runs in the
715   ;; cross-compilation host Common Lisp, not just CMU CL, and (2)
716   ;; classic CMU CL allowed more things here than this, and I haven't
717   ;; tried to proof-read all the calls to EMIT-BYTE to ensure that
718   ;; they're passing appropriate. -- WHN 19990323
719   (check-type byte possibly-signed-assembly-unit)
720   (vector-push-extend (logand byte assembly-unit-mask)
721                       (segment-buffer segment))
722   (incf (segment-current-posn segment))
723   (values))
724
725 ;;; interface: Output AMOUNT copies of FILL-BYTE to SEGMENT.
726 (defun emit-skip (segment amount &optional (fill-byte 0))
727   (declare (type segment segment)
728            (type index amount))
729   (dotimes (i amount)
730     (emit-byte segment fill-byte))
731   (values))
732
733 ;;; Used to handle the common parts of annotation emision. We just
734 ;;; assign the posn and index of the note and tack it on to the end of
735 ;;; the segment's annotations list.
736 (defun emit-annotation (segment note)
737   (declare (type segment segment)
738            (type annotation note))
739   (when (annotation-posn note)
740     (error "attempt to emit ~S a second time"))
741   (setf (annotation-posn note) (segment-current-posn segment))
742   (setf (annotation-index note) (segment-current-index segment))
743   (let ((last (segment-last-annotation segment))
744         (new (list note)))
745     (setf (segment-last-annotation segment)
746           (if last
747               (setf (cdr last) new)
748               (setf (segment-annotations segment) new))))
749   (values))
750
751 (defun emit-back-patch (segment size function)
752   #!+sb-doc
753   "Note that the instruction stream has to be back-patched when label positions
754    are finally known. SIZE bytes are reserved in SEGMENT, and function will
755    be called with two arguments: the segment and the position. The function
756    should look at the position and the position of any labels it wants to
757    and emit the correct sequence. (And it better be the same size as SIZE).
758    SIZE can be zero, which is useful if you just want to find out where things
759    ended up."
760   (emit-annotation segment (make-back-patch size function))
761   (emit-skip segment size))
762
763 (defun emit-chooser (segment size alignment maybe-shrink worst-case-fun)
764   #!+sb-doc
765   "Note that the instruction stream here depends on the actual positions of
766    various labels, so can't be output until label positions are known. Space
767    is made in SEGMENT for at least SIZE bytes. When all output has been
768    generated, the MAYBE-SHRINK functions for all choosers are called with
769    three arguments: the segment, the position, and a magic value. The MAYBE-
770    SHRINK decides if it can use a shorter sequence, and if so, emits that
771    sequence to the segment and returns T. If it can't do better than the
772    worst case, it should return NIL (without emitting anything). When calling
773    LABEL-POSITION, it should pass it the position and the magic-value it was
774    passed so that LABEL-POSITION can return the correct result. If the chooser
775    never decides to use a shorter sequence, the WORST-CASE-FUN will be called,
776    just like a BACK-PATCH. (See EMIT-BACK-PATCH.)"
777   (declare (type segment segment) (type index size) (type alignment alignment)
778            (type function maybe-shrink worst-case-fun))
779   (let ((chooser (make-chooser size alignment maybe-shrink worst-case-fun)))
780     (emit-annotation segment chooser)
781     (emit-skip segment size)
782     (adjust-alignment-after-chooser segment chooser)))
783
784 ;;; Called in EMIT-CHOOSER and COMPRESS-SEGMENT in order to recompute
785 ;;; the current alignment information in light of this chooser. If the
786 ;;; alignment guaranteed byte the chooser is less then the segments
787 ;;; current alignment, we have to adjust the segments notion of the
788 ;;; current alignment.
789 ;;;
790 ;;; The hard part is recomputing the sync posn, because it's not just
791 ;;; the choosers posn. Consider a chooser that emits either one or
792 ;;; three words. It preserves 8-byte (3 bit) alignments, because the
793 ;;; difference between the two choices is 8 bytes.
794 (defun adjust-alignment-after-chooser (segment chooser)
795   (declare (type segment segment) (type chooser chooser))
796   (let ((alignment (chooser-alignment chooser))
797         (seg-alignment (segment-alignment segment)))
798     (when (< alignment seg-alignment)
799       ;; The chooser might change the alignment of the output. So we
800       ;; have to figure out what the worst case alignment could be.
801       (setf (segment-alignment segment) alignment)
802       (let* ((posn (chooser-posn chooser))
803              (sync-posn (segment-sync-posn segment))
804              (offset (- posn sync-posn))
805              (delta (logand offset (1- (ash 1 alignment)))))
806         (setf (segment-sync-posn segment) (- posn delta)))))
807   (values))
808
809 ;;; Used internally whenever a chooser or alignment decides it doesn't
810 ;;; need as much space as it originally thought.
811 (defun emit-filler (segment bytes)
812   (let ((last (segment-last-annotation segment)))
813     (cond ((and last (filler-p (car last)))
814            (incf (filler-bytes (car last)) bytes))
815           (t
816            (emit-annotation segment (make-filler bytes)))))
817   (incf (segment-current-index segment) bytes)
818   (values))
819
820 ;;; EMIT-LABEL (the interface) basically just expands into this,
821 ;;; supplying the segment and vop.
822 (defun %emit-label (segment vop label)
823   (when (segment-run-scheduler segment)
824     (schedule-pending-instructions segment))
825   (let ((postits (segment-postits segment)))
826     (setf (segment-postits segment) nil)
827     (dolist (postit postits)
828       (emit-back-patch segment 0 postit)))
829   (let ((hook (segment-inst-hook segment)))
830     (when hook
831       (funcall hook segment vop :label label)))
832   (emit-annotation segment label))
833
834 ;;; Called by the ALIGN macro to emit an alignment note. We check to
835 ;;; see if we can guarantee the alignment restriction by just
836 ;;; outputting a fixed number of bytes. If so, we do so. Otherwise, we
837 ;;; create and emit an alignment note.
838 (defun emit-alignment (segment vop bits &optional (fill-byte 0))
839   (when (segment-run-scheduler segment)
840     (schedule-pending-instructions segment))
841   (let ((hook (segment-inst-hook segment)))
842     (when hook
843       (funcall hook segment vop :align bits)))
844   (let ((alignment (segment-alignment segment))
845         (offset (- (segment-current-posn segment)
846                    (segment-sync-posn segment))))
847     (cond ((> bits alignment)
848            ;; We need more bits of alignment. First emit enough noise
849            ;; to get back in sync with alignment, and then emit an
850            ;; alignment note to cover the rest.
851            (let ((slop (logand offset (1- (ash 1 alignment)))))
852              (unless (zerop slop)
853                (emit-skip segment (- (ash 1 alignment) slop) fill-byte)))
854            (let ((size (logand (1- (ash 1 bits))
855                                (lognot (1- (ash 1 alignment))))))
856              (assert (> size 0))
857              (emit-annotation segment (make-alignment bits size fill-byte))
858              (emit-skip segment size fill-byte))
859            (setf (segment-alignment segment) bits)
860            (setf (segment-sync-posn segment) (segment-current-posn segment)))
861           (t
862            ;; The last alignment was more restrictive then this one.
863            ;; So we can just figure out how much noise to emit
864            ;; assuming the last alignment was met.
865            (let* ((mask (1- (ash 1 bits)))
866                   (new-offset (logand (+ offset mask) (lognot mask))))
867              (emit-skip segment (- new-offset offset) fill-byte))
868            ;; But we emit an alignment with size=0 so we can verify
869            ;; that everything works.
870            (emit-annotation segment (make-alignment bits 0 fill-byte)))))
871   (values))
872
873 ;;; Used to find how ``aligned'' different offsets are. Returns the
874 ;;; number of low-order 0 bits, up to MAX-ALIGNMENT.
875 (defun find-alignment (offset)
876   (dotimes (i max-alignment max-alignment)
877     (when (logbitp i offset)
878       (return i))))
879
880 ;;; Emit a postit. The function will be called as a back-patch with
881 ;;; the position the following instruction is finally emitted. Postits
882 ;;; do not interfere at all with scheduling.
883 (defun %emit-postit (segment function)
884   (push function (segment-postits segment))
885   (values))
886 \f
887 ;;;; output compression/position assignment stuff
888
889 ;;; Grovel though all the annotations looking for choosers. When we
890 ;;; find a chooser, invoke the maybe-shrink function. If it returns T,
891 ;;; it output some other byte sequence.
892 (defun compress-output (segment)
893   (dotimes (i 5) ; it better not take more than one or two passes.
894     (let ((delta 0))
895       (setf (segment-alignment segment) max-alignment)
896       (setf (segment-sync-posn segment) 0)
897       (do* ((prev nil)
898             (remaining (segment-annotations segment) next)
899             (next (cdr remaining) (cdr remaining)))
900            ((null remaining))
901         (let* ((note (car remaining))
902                (posn (annotation-posn note)))
903           (unless (zerop delta)
904             (decf posn delta)
905             (setf (annotation-posn note) posn))
906           (cond
907            ((chooser-p note)
908             (setf (segment-current-index segment) (chooser-index note))
909             (setf (segment-current-posn segment) posn)
910             (setf (segment-last-annotation segment) prev)
911             (cond
912              ((funcall (chooser-maybe-shrink note) segment posn delta)
913               ;; It emitted some replacement.
914               (let ((new-size (- (segment-current-index segment)
915                                  (chooser-index note)))
916                     (old-size (chooser-size note)))
917                 (when (> new-size old-size)
918                   (error "~S emitted ~D bytes, but claimed its max was ~D."
919                          note new-size old-size))
920                 (let ((additional-delta (- old-size new-size)))
921                   (when (< (find-alignment additional-delta)
922                            (chooser-alignment note))
923                     (error "~S shrunk by ~D bytes, but claimed that it ~
924                             preserve ~D bits of alignment."
925                            note additional-delta (chooser-alignment note)))
926                   (incf delta additional-delta)
927                   (emit-filler segment additional-delta))
928                 (setf prev (segment-last-annotation segment))
929                 (if prev
930                     (setf (cdr prev) (cdr remaining))
931                     (setf (segment-annotations segment)
932                           (cdr remaining)))))
933              (t
934               ;; The chooser passed on shrinking. Make sure it didn't emit
935               ;; anything.
936               (unless (= (segment-current-index segment) (chooser-index note))
937                 (error "Chooser ~S passed, but not before emitting ~D bytes."
938                        note
939                        (- (segment-current-index segment)
940                           (chooser-index note))))
941               ;; Act like we just emitted this chooser.
942               (let ((size (chooser-size note)))
943                 (incf (segment-current-index segment) size)
944                 (incf (segment-current-posn segment) size))
945               ;; Adjust the alignment accordingly.
946               (adjust-alignment-after-chooser segment note)
947               ;; And keep this chooser for next time around.
948               (setf prev remaining))))
949            ((alignment-p note)
950             (unless (zerop (alignment-size note))
951               ;; Re-emit the alignment, letting it collapse if we know
952               ;; anything more about the alignment guarantees of the
953               ;; segment.
954               (let ((index (alignment-index note)))
955                 (setf (segment-current-index segment) index)
956                 (setf (segment-current-posn segment) posn)
957                 (setf (segment-last-annotation segment) prev)
958                 (emit-alignment segment nil (alignment-bits note)
959                                 (alignment-fill-byte note))
960                 (let* ((new-index (segment-current-index segment))
961                        (size (- new-index index))
962                        (old-size (alignment-size note))
963                        (additional-delta (- old-size size)))
964                   (when (minusp additional-delta)
965                     (error "Alignment ~S needs more space now?  It was ~D, ~
966                             and is ~D now."
967                            note old-size size))
968                   (when (plusp additional-delta)
969                     (emit-filler segment additional-delta)
970                     (incf delta additional-delta)))
971                 (setf prev (segment-last-annotation segment))
972                 (if prev
973                     (setf (cdr prev) (cdr remaining))
974                     (setf (segment-annotations segment)
975                           (cdr remaining))))))
976            (t
977             (setf prev remaining)))))
978       (when (zerop delta)
979         (return))
980       (decf (segment-final-posn segment) delta)))
981   (values))
982
983 ;;; We have run all the choosers we can, so now we have to figure out exactly
984 ;;; how much space each alignment note needs.
985 (defun finalize-positions (segment)
986   (let ((delta 0))
987     (do* ((prev nil)
988           (remaining (segment-annotations segment) next)
989           (next (cdr remaining) (cdr remaining)))
990          ((null remaining))
991       (let* ((note (car remaining))
992              (posn (- (annotation-posn note) delta)))
993         (cond
994          ((alignment-p note)
995           (let* ((bits (alignment-bits note))
996                  (mask (1- (ash 1 bits)))
997                  (new-posn (logand (+ posn mask) (lognot mask)))
998                  (size (- new-posn posn))
999                  (old-size (alignment-size note))
1000                  (additional-delta (- old-size size)))
1001             (assert (<= 0 size old-size))
1002             (unless (zerop additional-delta)
1003               (setf (segment-last-annotation segment) prev)
1004               (incf delta additional-delta)
1005               (setf (segment-current-index segment) (alignment-index note))
1006               (setf (segment-current-posn segment) posn)
1007               (emit-filler segment additional-delta)
1008               (setf prev (segment-last-annotation segment)))
1009             (if prev
1010                 (setf (cdr prev) next)
1011                 (setf (segment-annotations segment) next))))
1012          (t
1013           (setf (annotation-posn note) posn)
1014           (setf prev remaining)
1015           (setf next (cdr remaining))))))
1016     (unless (zerop delta)
1017       (decf (segment-final-posn segment) delta)))
1018   (values))
1019
1020 ;;; Grovel over segment, filling in any backpatches. If any choosers
1021 ;;; are left over, we need to emit their worst case varient.
1022 (defun process-back-patches (segment)
1023   (do* ((prev nil)
1024         (remaining (segment-annotations segment) next)
1025         (next (cdr remaining) (cdr remaining)))
1026       ((null remaining))
1027     (let ((note (car remaining)))
1028       (flet ((fill-in (function old-size)
1029                (let ((index (annotation-index note))
1030                      (posn (annotation-posn note)))
1031                  (setf (segment-current-index segment) index)
1032                  (setf (segment-current-posn segment) posn)
1033                  (setf (segment-last-annotation segment) prev)
1034                  (funcall function segment posn)
1035                  (let ((new-size (- (segment-current-index segment) index)))
1036                    (unless (= new-size old-size)
1037                      (error "~S emitted ~D bytes, but claimed it was ~D."
1038                             note new-size old-size)))
1039                  (let ((tail (segment-last-annotation segment)))
1040                    (if tail
1041                        (setf (cdr tail) next)
1042                        (setf (segment-annotations segment) next)))
1043                  (setf next (cdr prev)))))
1044         (cond ((back-patch-p note)
1045                (fill-in (back-patch-function note)
1046                         (back-patch-size note)))
1047               ((chooser-p note)
1048                (fill-in (chooser-worst-case-fun note)
1049                         (chooser-size note)))
1050               (t
1051                (setf prev remaining)))))))
1052 \f
1053 ;;;; interface to the rest of the compiler
1054
1055 ;;; This holds the current segment while assembling. Use ASSEMBLE to
1056 ;;; change it.
1057 ;;;
1058 ;;; The double asterisks in the name are intended to suggest that this
1059 ;;; isn't just any old special variable, it's an extra-special
1060 ;;; variable, because sometimes MACROLET is used to bind it. So be
1061 ;;; careful out there..
1062 (defvar **current-segment**)
1063
1064 ;;; Just like **CURRENT-SEGMENT**, except this holds the current vop.
1065 ;;; Used only to keep track of which vops emit which insts.
1066 ;;;
1067 ;;; The double asterisks in the name are intended to suggest that this
1068 ;;; isn't just any old special variable, it's an extra-special
1069 ;;; variable, because sometimes MACROLET is used to bind it. So be
1070 ;;; careful out there..
1071 (defvar **current-vop** nil)
1072
1073 ;;; We also SYMBOL-MACROLET **CURRENT-SEGMENT** to a local holding the
1074 ;;; segment so uses of **CURRENT-SEGMENT** inside the body don't have
1075 ;;; to keep dereferencing the symbol. Given that ASSEMBLE is the only
1076 ;;; interface to **CURRENT-SEGMENT**, we don't have to worry about the
1077 ;;; special value becomming out of sync with the lexical value. Unless
1078 ;;; some bozo closes over it, but nobody does anything like that...
1079 ;;;
1080 ;;; FIXME: The way this macro uses MACROEXPAND internally breaks my
1081 ;;; old assumptions about macros which are needed both in the host and
1082 ;;; the target. (This is more or less the same way that PUSH-IN,
1083 ;;; DELETEF-IN, and DEF-BOOLEAN-ATTRIBUTE break my old assumptions,
1084 ;;; except that they used GET-SETF-EXPANSION instead of MACROEXPAND to
1085 ;;; do the dirty deed.) The quick and dirty "solution" here is the
1086 ;;; same as there: use cut and paste to duplicate the defmacro in a
1087 ;;; (SB!INT:DEF!MACRO FOO (..) .. CL:MACROEXPAND ..) #+SB-XC-HOST
1088 ;;; (DEFMACRO FOO (..) .. SB!XC:MACROEXPAND ..) idiom. This is
1089 ;;; disgusting and unmaintainable, and there are obviously better
1090 ;;; solutions and maybe even good solutions, but I'm disinclined to
1091 ;;; hunt for good solutions until the system works and I can test them
1092 ;;; in isolation.
1093 (sb!int:def!macro assemble ((&optional segment vop &key labels) &body body
1094                             &environment env)
1095   #!+sb-doc
1096   "Execute BODY (as a progn) with SEGMENT as the current segment."
1097   (flet ((label-name-p (thing)
1098            (and thing (symbolp thing))))
1099     (let* ((seg-var (gensym "SEGMENT-"))
1100            (vop-var (gensym "VOP-"))
1101            (visible-labels (remove-if-not #'label-name-p body))
1102            (inherited-labels
1103             (multiple-value-bind (expansion expanded)
1104                 (macroexpand '..inherited-labels.. env)
1105               (if expanded expansion nil)))
1106            (new-labels (append labels
1107                                (set-difference visible-labels
1108                                                inherited-labels)))
1109            (nested-labels (set-difference (append inherited-labels new-labels)
1110                                           visible-labels)))
1111       (when (intersection labels inherited-labels)
1112         (error "duplicate nested labels: ~S"
1113                (intersection labels inherited-labels)))
1114       `(let* ((,seg-var ,(or segment '**current-segment**))
1115               (,vop-var ,(or vop '**current-vop**))
1116               ,@(when segment
1117                   `((**current-segment** ,seg-var)))
1118               ,@(when vop
1119                   `((**current-vop** ,vop-var)))
1120               ,@(mapcar #'(lambda (name)
1121                             `(,name (gen-label)))
1122                         new-labels))
1123          (symbol-macrolet ((**current-segment** ,seg-var)
1124                            (**current-vop** ,vop-var)
1125                            ,@(when (or inherited-labels nested-labels)
1126                                `((..inherited-labels.. ,nested-labels))))
1127            ,@(mapcar #'(lambda (form)
1128                          (if (label-name-p form)
1129                              `(emit-label ,form)
1130                              form))
1131                      body))))))
1132 #+sb-xc-host
1133 (sb!xc:defmacro assemble ((&optional segment vop &key labels)
1134                           &body body
1135                           &environment env)
1136   #!+sb-doc
1137   "Execute BODY (as a progn) with SEGMENT as the current segment."
1138   (flet ((label-name-p (thing)
1139            (and thing (symbolp thing))))
1140     (let* ((seg-var (gensym "SEGMENT-"))
1141            (vop-var (gensym "VOP-"))
1142            (visible-labels (remove-if-not #'label-name-p body))
1143            (inherited-labels
1144             (multiple-value-bind
1145                 (expansion expanded)
1146                 (sb!xc:macroexpand '..inherited-labels.. env)
1147               (if expanded expansion nil)))
1148            (new-labels (append labels
1149                                (set-difference visible-labels
1150                                                inherited-labels)))
1151            (nested-labels (set-difference (append inherited-labels new-labels)
1152                                           visible-labels)))
1153       (when (intersection labels inherited-labels)
1154         (error "duplicate nested labels: ~S"
1155                (intersection labels inherited-labels)))
1156       `(let* ((,seg-var ,(or segment '**current-segment**))
1157               (,vop-var ,(or vop '**current-vop**))
1158               ,@(when segment
1159                   `((**current-segment** ,seg-var)))
1160               ,@(when vop
1161                   `((**current-vop** ,vop-var)))
1162               ,@(mapcar #'(lambda (name)
1163                             `(,name (gen-label)))
1164                         new-labels))
1165          (symbol-macrolet ((**current-segment** ,seg-var)
1166                            (**current-vop** ,vop-var)
1167                            ,@(when (or inherited-labels nested-labels)
1168                                `((..inherited-labels.. ,nested-labels))))
1169            ,@(mapcar #'(lambda (form)
1170                          (if (label-name-p form)
1171                              `(emit-label ,form)
1172                              form))
1173                      body))))))
1174
1175 (defmacro inst (&whole whole instruction &rest args &environment env)
1176   #!+sb-doc
1177   "Emit the specified instruction to the current segment."
1178   (let ((inst (gethash (symbol-name instruction) *assem-instructions*)))
1179     (cond ((null inst)
1180            (error "unknown instruction: ~S" instruction))
1181           ((functionp inst)
1182            (funcall inst (cdr whole) env))
1183           (t
1184            `(,inst **current-segment** **current-vop** ,@args)))))
1185
1186 ;;; Note: The need to capture SYMBOL-MACROLET bindings of
1187 ;;; **CURRENT-SEGMENT* and **CURRENT-VOP** prevents this from being an
1188 ;;; ordinary function.
1189 (defmacro emit-label (label)
1190   #!+sb-doc
1191   "Emit LABEL at this location in the current segment."
1192   `(%emit-label **current-segment** **current-vop** ,label))
1193
1194 ;;; Note: The need to capture SYMBOL-MACROLET bindings of
1195 ;;; **CURRENT-SEGMENT* prevents this from being an ordinary function.
1196 (defmacro emit-postit (function)
1197   `(%emit-postit **current-segment** ,function))
1198
1199 ;;; Note: The need to capture SYMBOL-MACROLET bindings of
1200 ;;; **CURRENT-SEGMENT* and **CURRENT-VOP** prevents this from being an
1201 ;;; ordinary function.
1202 (defmacro align (bits &optional (fill-byte 0))
1203   #!+sb-doc
1204   "Emit an alignment restriction to the current segment."
1205   `(emit-alignment **current-segment** **current-vop** ,bits ,fill-byte))
1206 ;;; FIXME: By analogy with EMIT-LABEL and EMIT-POSTIT, this should be
1207 ;;; called EMIT-ALIGNMENT, and the function that it calls should be
1208 ;;; called %EMIT-ALIGNMENT.
1209
1210 (defun label-position (label &optional if-after delta)
1211   #!+sb-doc
1212   "Return the current position for LABEL. Chooser maybe-shrink functions
1213    should supply IF-AFTER and DELTA in order to ensure correct results."
1214   (let ((posn (label-posn label)))
1215     (if (and if-after (> posn if-after))
1216         (- posn delta)
1217         posn)))
1218
1219 (defun append-segment (segment other-segment)
1220   #!+sb-doc
1221   "Append OTHER-SEGMENT to the end of SEGMENT. Don't use OTHER-SEGMENT
1222    for anything after this."
1223   (when (segment-run-scheduler segment)
1224     (schedule-pending-instructions segment))
1225   (let ((postits (segment-postits segment)))
1226     (setf (segment-postits segment) (segment-postits other-segment))
1227     (dolist (postit postits)
1228       (emit-back-patch segment 0 postit)))
1229   #!-x86 (emit-alignment segment nil max-alignment)
1230   #!+x86 (emit-alignment segment nil max-alignment #x90)
1231   (let ((segment-current-index-0 (segment-current-index segment))
1232         (segment-current-posn-0  (segment-current-posn  segment)))
1233     (incf (segment-current-index segment)
1234           (segment-current-index other-segment))
1235     (replace (segment-buffer segment)
1236              (segment-buffer other-segment)
1237              :start1 segment-current-index-0)
1238     (setf (segment-buffer other-segment) nil) ; to prevent accidental reuse
1239     (incf (segment-current-posn segment)
1240           (segment-current-posn other-segment))
1241     (let ((other-annotations (segment-annotations other-segment)))
1242       (when other-annotations
1243         (dolist (note other-annotations)
1244           (incf (annotation-index note) segment-current-index-0)
1245           (incf (annotation-posn note) segment-current-posn-0))
1246         ;; This SEGMENT-LAST-ANNOTATION code is confusing. Is it really
1247         ;; worth enough in efficiency to justify it? -- WHN 19990322
1248         (let ((last (segment-last-annotation segment)))
1249           (if last
1250             (setf (cdr last) other-annotations)
1251             (setf (segment-annotations segment) other-annotations)))
1252         (setf (segment-last-annotation segment)
1253               (segment-last-annotation other-segment)))))
1254   (values))
1255
1256 (defun finalize-segment (segment)
1257   #!+sb-doc
1258   "Do any final processing of SEGMENT and return the total number of bytes
1259    covered by this segment."
1260   (when (segment-run-scheduler segment)
1261     (schedule-pending-instructions segment))
1262   (setf (segment-run-scheduler segment) nil)
1263   (let ((postits (segment-postits segment)))
1264     (setf (segment-postits segment) nil)
1265     (dolist (postit postits)
1266       (emit-back-patch segment 0 postit)))
1267   (setf (segment-final-index segment) (segment-current-index segment))
1268   (setf (segment-final-posn segment) (segment-current-posn segment))
1269   (setf (segment-inst-hook segment) nil)
1270   (compress-output segment)
1271   (finalize-positions segment)
1272   (process-back-patches segment)
1273   (segment-final-posn segment))
1274
1275 ;;; Call FUNCTION on all the stuff accumulated in SEGMENT. FUNCTION
1276 ;;; should accept a single vector argument. It will be called zero or
1277 ;;; more times on vectors of the appropriate byte type. The
1278 ;;; concatenation of the vector arguments from all the calls is the
1279 ;;; contents of SEGMENT.
1280 ;;;
1281 ;;; KLUDGE: This implementation is sort of slow and gross, calling
1282 ;;; FUNCTION repeatedly and consing a fresh vector for its argument
1283 ;;; each time. It might be possible to make a more efficient version
1284 ;;; by making FINALIZE-SEGMENT do all the compacting currently done by
1285 ;;; this function: then this function could become trivial and fast,
1286 ;;; calling FUNCTION once on the entire compacted segment buffer. --
1287 ;;; WHN 19990322
1288 (defun on-segment-contents-vectorly (segment function)
1289   (let ((buffer (segment-buffer segment))
1290         (i0 0))
1291     (flet ((frob (i0 i1)
1292              (when (< i0 i1)
1293                (funcall function (subseq buffer i0 i1)))))
1294       (dolist (note (segment-annotations segment))
1295         (when (filler-p note)
1296           (let ((i1 (filler-index note)))
1297             (frob i0 i1)
1298             (setf i0 (+ i1 (filler-bytes note))))))
1299       (frob i0 (segment-final-index segment))))
1300   (values))
1301
1302 ;;; Write the code accumulated in SEGMENT to STREAM, and return the
1303 ;;; number of bytes written.
1304 (defun write-segment-contents (segment stream)
1305   (let ((result 0))
1306     (declare (type index result))
1307     (on-segment-contents-vectorly segment
1308                                   (lambda (v)
1309                                     (declare (type (vector assembly-unit) v))
1310                                     (incf result (length v))
1311                                     (write-sequence v stream)))
1312     result))
1313 \f
1314 ;;;; interface to the instruction set definition
1315
1316 ;;; Define a function named NAME that merges its arguments into a
1317 ;;; single integer and then emits the bytes of that integer in the
1318 ;;; correct order based on the endianness of the target-backend.
1319 (defmacro define-bitfield-emitter (name total-bits &rest byte-specs)
1320   (sb!int:collect ((arg-names) (arg-types))
1321     (let* ((total-bits (eval total-bits))
1322            (overall-mask (ash -1 total-bits))
1323            (num-bytes (multiple-value-bind (quo rem)
1324                           (truncate total-bits assembly-unit-bits)
1325                         (unless (zerop rem)
1326                           (error "~D isn't an even multiple of ~D."
1327                                  total-bits assembly-unit-bits))
1328                         quo))
1329            (bytes (make-array num-bytes :initial-element nil))
1330            (segment-arg (gensym "SEGMENT-")))
1331       (dolist (byte-spec-expr byte-specs)
1332         (let* ((byte-spec (eval byte-spec-expr))
1333                (byte-size (byte-size byte-spec))
1334                (byte-posn (byte-position byte-spec))
1335                (arg (gensym (format nil "~:@(ARG-FOR-~S-~)" byte-spec-expr))))
1336           (when (ldb-test (byte byte-size byte-posn) overall-mask)
1337             (error "The byte spec ~S either overlaps another byte spec, or ~
1338                     extends past the end."
1339                    byte-spec-expr))
1340           (setf (ldb byte-spec overall-mask) -1)
1341           (arg-names arg)
1342           (arg-types `(type (integer ,(ash -1 (1- byte-size))
1343                                      ,(1- (ash 1 byte-size)))
1344                             ,arg))
1345           (multiple-value-bind (start-byte offset)
1346               (floor byte-posn assembly-unit-bits)
1347             (let ((end-byte (floor (1- (+ byte-posn byte-size))
1348                                    assembly-unit-bits)))
1349               (flet ((maybe-ash (expr offset)
1350                        (if (zerop offset)
1351                            expr
1352                            `(ash ,expr ,offset))))
1353                 (declare (inline maybe-ash))
1354                 (cond ((zerop byte-size))
1355                       ((= start-byte end-byte)
1356                        (push (maybe-ash `(ldb (byte ,byte-size 0) ,arg)
1357                                         offset)
1358                              (svref bytes start-byte)))
1359                       (t
1360                        (push (maybe-ash
1361                               `(ldb (byte ,(- assembly-unit-bits offset) 0)
1362                                     ,arg)
1363                               offset)
1364                              (svref bytes start-byte))
1365                        (do ((index (1+ start-byte) (1+ index)))
1366                            ((>= index end-byte))
1367                          (push
1368                           `(ldb (byte ,assembly-unit-bits
1369                                       ,(- (* assembly-unit-bits
1370                                              (- index start-byte))
1371                                           offset))
1372                                 ,arg)
1373                           (svref bytes index)))
1374                        (let ((len (rem (+ byte-size offset)
1375                                        assembly-unit-bits)))
1376                          (push
1377                           `(ldb (byte ,(if (zerop len)
1378                                            assembly-unit-bits
1379                                            len)
1380                                       ,(- (* assembly-unit-bits
1381                                              (- end-byte start-byte))
1382                                           offset))
1383                                 ,arg)
1384                           (svref bytes end-byte))))))))))
1385       (unless (= overall-mask -1)
1386         (error "There are holes."))
1387       (let ((forms nil))
1388         (dotimes (i num-bytes)
1389           (let ((pieces (svref bytes i)))
1390             (assert pieces)
1391             (push `(emit-byte ,segment-arg
1392                               ,(if (cdr pieces)
1393                                    `(logior ,@pieces)
1394                                    (car pieces)))
1395                   forms)))
1396         `(defun ,name (,segment-arg ,@(arg-names))
1397            (declare (type segment ,segment-arg) ,@(arg-types))
1398            ,@(ecase sb!c:*backend-byte-order*
1399                (:little-endian (nreverse forms))
1400                (:big-endian forms))
1401            ',name)))))
1402
1403 (defun grovel-lambda-list (lambda-list vop-var)
1404   (let ((segment-name (car lambda-list))
1405         (vop-var (or vop-var (gensym "VOP-"))))
1406     (sb!int:collect ((new-lambda-list))
1407       (new-lambda-list segment-name)
1408       (new-lambda-list vop-var)
1409       (labels
1410           ((grovel (state lambda-list)
1411              (when lambda-list
1412                (let ((param (car lambda-list)))
1413                  (cond
1414                   ((member param lambda-list-keywords)
1415                    (new-lambda-list param)
1416                    (grovel param (cdr lambda-list)))
1417                   (t
1418                    (ecase state
1419                      ((nil)
1420                       (new-lambda-list param)
1421                       `(cons ,param ,(grovel state (cdr lambda-list))))
1422                      (&optional
1423                       (multiple-value-bind (name default supplied-p)
1424                           (if (consp param)
1425                               (values (first param)
1426                                       (second param)
1427                                       (or (third param)
1428                                           (gensym "SUPPLIED-P-")))
1429                               (values param nil (gensym "SUPPLIED-P-")))
1430                         (new-lambda-list (list name default supplied-p))
1431                         `(and ,supplied-p
1432                               (cons ,(if (consp name)
1433                                          (second name)
1434                                          name)
1435                                     ,(grovel state (cdr lambda-list))))))
1436                      (&key
1437                       (multiple-value-bind (name default supplied-p)
1438                           (if (consp param)
1439                               (values (first param)
1440                                       (second param)
1441                                       (or (third param)
1442                                           (gensym "SUPPLIED-P-")))
1443                               (values param nil (gensym "SUPPLIED-P-")))
1444                         (new-lambda-list (list name default supplied-p))
1445                         (multiple-value-bind (key var)
1446                             (if (consp name)
1447                                 (values (first name) (second name))
1448                                 (values (intern (symbol-name name) :keyword)
1449                                         name))
1450                           `(append (and ,supplied-p (list ',key ,var))
1451                                    ,(grovel state (cdr lambda-list))))))
1452                      (&rest
1453                       (new-lambda-list param)
1454                       (grovel state (cdr lambda-list))
1455                       param))))))))
1456         (let ((reconstructor (grovel nil (cdr lambda-list))))
1457           (values (new-lambda-list)
1458                   segment-name
1459                   vop-var
1460                   reconstructor))))))
1461
1462 (defun extract-nths (index glue list-of-lists-of-lists)
1463   (mapcar #'(lambda (list-of-lists)
1464               (cons glue
1465                     (mapcar #'(lambda (list)
1466                                 (nth index list))
1467                             list-of-lists)))
1468           list-of-lists-of-lists))
1469
1470 (defmacro define-instruction (name lambda-list &rest options)
1471   (let* ((sym-name (symbol-name name))
1472          (defun-name (sb!int:symbolicate sym-name "-INST-EMITTER"))
1473          (vop-var nil)
1474          (postits (gensym "POSTITS-"))
1475          (emitter nil)
1476          (decls nil)
1477          (attributes nil)
1478          (cost nil)
1479          (dependencies nil)
1480          (delay nil)
1481          (pinned nil)
1482          (pdefs nil))
1483     (sb!int:/noshow "entering DEFINE-INSTRUCTION" name lambda-list options)
1484     (dolist (option-spec options)
1485       (sb!int:/noshow option-spec)
1486       (multiple-value-bind (option args)
1487           (if (consp option-spec)
1488               (values (car option-spec) (cdr option-spec))
1489               (values option-spec nil))
1490         (sb!int:/noshow option args)
1491         (case option
1492           (:emitter
1493            (when emitter
1494              (error "You can only specify :EMITTER once per instruction."))
1495            (setf emitter args))
1496           (:declare
1497            (setf decls (append decls args)))
1498           (:attributes
1499            (setf attributes (append attributes args)))
1500           (:cost
1501            (setf cost (first args)))
1502           (:dependencies
1503            (setf dependencies (append dependencies args)))
1504           (:delay
1505            (when delay
1506              (error "You can only specify :DELAY once per instruction."))
1507            (setf delay args))
1508           (:pinned
1509            (setf pinned t))
1510           (:vop-var
1511            (if vop-var
1512                (error "You can only specify :VOP-VAR once per instruction.")
1513                (setf vop-var (car args))))
1514           (:printer
1515            (push (eval `(list (multiple-value-list
1516                                ,(sb!disassem:gen-printer-def-forms-def-form
1517                                  name
1518                                  (cdr option-spec)))))
1519                  pdefs))
1520           (:printer-list
1521            ;; same as :PRINTER, but is EVALed first, and is a list of
1522            ;; printers
1523            (push
1524             (eval
1525              `(eval
1526                `(list ,@(mapcar #'(lambda (printer)
1527                                     `(multiple-value-list
1528                                       ,(sb!disassem:gen-printer-def-forms-def-form
1529                                         ',name printer nil)))
1530                                 ,(cadr option-spec)))))
1531             pdefs))
1532           (t
1533            (error "unknown option: ~S" option)))))
1534     (sb!int:/noshow "done processing options")
1535     (setf pdefs (nreverse pdefs))
1536     (multiple-value-bind
1537         (new-lambda-list segment-name vop-name arg-reconstructor)
1538         (grovel-lambda-list lambda-list vop-var)
1539       (sb!int:/noshow new-lambda-list segment-name vop-name arg-reconstructor)
1540       (push `(let ((hook (segment-inst-hook ,segment-name)))
1541                (when hook
1542                  (funcall hook ,segment-name ,vop-name ,sym-name
1543                           ,arg-reconstructor)))
1544             emitter)
1545       (push `(dolist (postit ,postits)
1546                (emit-back-patch ,segment-name 0 postit))
1547             emitter)
1548       (unless cost (setf cost 1))
1549       #!+sb-dyncount
1550       (push `(when (segment-collect-dynamic-statistics ,segment-name)
1551                (let* ((info (sb!c:ir2-component-dyncount-info
1552                              (sb!c:component-info
1553                               sb!c:*component-being-compiled*)))
1554                       (costs (sb!c:dyncount-info-costs info))
1555                       (block-number (sb!c:block-number
1556                                      (sb!c:ir2-block-block
1557                                       (sb!c:vop-block ,vop-name)))))
1558                  (incf (aref costs block-number) ,cost)))
1559             emitter)
1560       (when *assem-scheduler-p*
1561         (if pinned
1562             (setf emitter
1563                   `((when (segment-run-scheduler ,segment-name)
1564                       (schedule-pending-instructions ,segment-name))
1565                     ,@emitter))
1566             (let ((flet-name
1567                    (gensym (concatenate 'string "EMIT-" sym-name "-INST-")))
1568                   (inst-name (gensym "INST-")))
1569               (setf emitter `((flet ((,flet-name (,segment-name)
1570                                        ,@emitter))
1571                                 (if (segment-run-scheduler ,segment-name)
1572                                     (let ((,inst-name
1573                                            (make-instruction
1574                                             (incf (segment-inst-number
1575                                                    ,segment-name))
1576                                             #',flet-name
1577                                             (instruction-attributes
1578                                              ,@attributes)
1579                                             (progn ,@delay))))
1580                                       ,@(when dependencies
1581                                           `((note-dependencies
1582                                                 (,segment-name ,inst-name)
1583                                               ,@dependencies)))
1584                                       (queue-inst ,segment-name ,inst-name))
1585                                     (,flet-name ,segment-name))))))))
1586       `(progn
1587          (defun ,defun-name ,new-lambda-list
1588            ,@(when decls
1589                `((declare ,@decls)))
1590            (let ((,postits (segment-postits ,segment-name)))
1591              (setf (segment-postits ,segment-name) nil)
1592              (symbol-macrolet
1593                  (;; Apparently this binding is intended to keep
1594                   ;; anyone from accidentally using
1595                   ;; **CURRENT-SEGMENT** within the body of the
1596                   ;; emitter. The error message sorta suggests that
1597                   ;; this can happen accidentally by including one
1598                   ;; emitter inside another. But I dunno.. -- WHN
1599                   ;; 19990323
1600                   (**current-segment**
1601                    ;; FIXME: I can't see why we have to use
1602                    ;;   (MACROLET ((LOSE () (ERROR ..))) (LOSE))
1603                    ;; instead of just (ERROR "..") here.
1604                    (macrolet ((lose ()
1605                                 (error "You can't use INST without an ~
1606                                         ASSEMBLE inside emitters.")))
1607                      (lose))))
1608                ,@emitter))
1609            (values))
1610          (eval-when (:compile-toplevel :load-toplevel :execute)
1611            (%define-instruction ,sym-name ',defun-name))
1612          ,@(extract-nths 1 'progn pdefs)
1613          ,@(when pdefs
1614              `((sb!disassem:install-inst-flavors
1615                 ',name
1616                 (append ,@(extract-nths 0 'list pdefs)))))))))
1617
1618 (defmacro define-instruction-macro (name lambda-list &body body)
1619   (let ((whole (gensym "WHOLE-"))
1620         (env (gensym "ENV-")))
1621     (multiple-value-bind (body local-defs)
1622         (sb!kernel:parse-defmacro lambda-list
1623                                   whole
1624                                   body
1625                                   name
1626                                   'instruction-macro
1627                                   :environment env)
1628       `(eval-when (:compile-toplevel :load-toplevel :execute)
1629          (%define-instruction ,(symbol-name name)
1630                               #'(lambda (,whole ,env)
1631                                   ,@local-defs
1632                                   (block ,name
1633                                     ,body)))))))
1634
1635 (defun %define-instruction (name defun)
1636   (setf (gethash name *assem-instructions*) defun)
1637   name)