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