0.pre7.88:
[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 had better never be used in a
143   ;; branch delay slot.
144   var-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 (missing-arg) :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=~W" (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[~W for ~W]~%"
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[~W for ~W]~%"
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   (aver (segment-run-scheduler segment))
315   (let ((countdown (segment-branch-countdown segment)))
316     (when countdown
317       (decf countdown)
318       (aver (not (instruction-attributep (inst-attributes inst)
319                                          var-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   (aver (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                                            var-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   (aver (sset-empty (inst-read-dependents inst)))
569   (aver (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   (declare (type possibly-signed-assembly-unit byte))
713   (vector-push-extend (logand byte assembly-unit-mask)
714                       (segment-buffer segment))
715   (incf (segment-current-posn segment))
716   (values))
717
718 ;;; interface: Output AMOUNT copies of FILL-BYTE to SEGMENT.
719 (defun emit-skip (segment amount &optional (fill-byte 0))
720   (declare (type segment segment)
721            (type index amount))
722   (dotimes (i amount)
723     (emit-byte segment fill-byte))
724   (values))
725
726 ;;; Used to handle the common parts of annotation emision. We just
727 ;;; assign the posn and index of the note and tack it on to the end of
728 ;;; the segment's annotations list.
729 (defun emit-annotation (segment note)
730   (declare (type segment segment)
731            (type annotation note))
732   (when (annotation-posn note)
733     (error "attempt to emit ~S a second time"))
734   (setf (annotation-posn note) (segment-current-posn segment))
735   (setf (annotation-index note) (segment-current-index segment))
736   (let ((last (segment-last-annotation segment))
737         (new (list note)))
738     (setf (segment-last-annotation segment)
739           (if last
740               (setf (cdr last) new)
741               (setf (segment-annotations segment) new))))
742   (values))
743
744 (defun emit-back-patch (segment size function)
745   #!+sb-doc
746   "Note that the instruction stream has to be back-patched when label positions
747    are finally known. SIZE bytes are reserved in SEGMENT, and function will
748    be called with two arguments: the segment and the position. The function
749    should look at the position and the position of any labels it wants to
750    and emit the correct sequence. (And it better be the same size as SIZE).
751    SIZE can be zero, which is useful if you just want to find out where things
752    ended up."
753   (emit-annotation segment (make-back-patch size function))
754   (emit-skip segment size))
755
756 (defun emit-chooser (segment size alignment maybe-shrink worst-case-fun)
757   #!+sb-doc
758   "Note that the instruction stream here depends on the actual positions of
759    various labels, so can't be output until label positions are known. Space
760    is made in SEGMENT for at least SIZE bytes. When all output has been
761    generated, the MAYBE-SHRINK functions for all choosers are called with
762    three arguments: the segment, the position, and a magic value. The MAYBE-
763    SHRINK decides if it can use a shorter sequence, and if so, emits that
764    sequence to the segment and returns T. If it can't do better than the
765    worst case, it should return NIL (without emitting anything). When calling
766    LABEL-POSITION, it should pass it the position and the magic-value it was
767    passed so that LABEL-POSITION can return the correct result. If the chooser
768    never decides to use a shorter sequence, the WORST-CASE-FUN will be called,
769    just like a BACK-PATCH. (See EMIT-BACK-PATCH.)"
770   (declare (type segment segment) (type index size) (type alignment alignment)
771            (type function maybe-shrink worst-case-fun))
772   (let ((chooser (make-chooser size alignment maybe-shrink worst-case-fun)))
773     (emit-annotation segment chooser)
774     (emit-skip segment size)
775     (adjust-alignment-after-chooser segment chooser)))
776
777 ;;; Called in EMIT-CHOOSER and COMPRESS-SEGMENT in order to recompute
778 ;;; the current alignment information in light of this chooser. If the
779 ;;; alignment guaranteed byte the chooser is less then the segments
780 ;;; current alignment, we have to adjust the segments notion of the
781 ;;; current alignment.
782 ;;;
783 ;;; The hard part is recomputing the sync posn, because it's not just
784 ;;; the choosers posn. Consider a chooser that emits either one or
785 ;;; three words. It preserves 8-byte (3 bit) alignments, because the
786 ;;; difference between the two choices is 8 bytes.
787 (defun adjust-alignment-after-chooser (segment chooser)
788   (declare (type segment segment) (type chooser chooser))
789   (let ((alignment (chooser-alignment chooser))
790         (seg-alignment (segment-alignment segment)))
791     (when (< alignment seg-alignment)
792       ;; The chooser might change the alignment of the output. So we
793       ;; have to figure out what the worst case alignment could be.
794       (setf (segment-alignment segment) alignment)
795       (let* ((posn (chooser-posn chooser))
796              (sync-posn (segment-sync-posn segment))
797              (offset (- posn sync-posn))
798              (delta (logand offset (1- (ash 1 alignment)))))
799         (setf (segment-sync-posn segment) (- posn delta)))))
800   (values))
801
802 ;;; Used internally whenever a chooser or alignment decides it doesn't
803 ;;; need as much space as it originally thought.
804 (defun emit-filler (segment bytes)
805   (let ((last (segment-last-annotation segment)))
806     (cond ((and last (filler-p (car last)))
807            (incf (filler-bytes (car last)) bytes))
808           (t
809            (emit-annotation segment (make-filler bytes)))))
810   (incf (segment-current-index segment) bytes)
811   (values))
812
813 ;;; EMIT-LABEL (the interface) basically just expands into this,
814 ;;; supplying the segment and vop.
815 (defun %emit-label (segment vop label)
816   (when (segment-run-scheduler segment)
817     (schedule-pending-instructions segment))
818   (let ((postits (segment-postits segment)))
819     (setf (segment-postits segment) nil)
820     (dolist (postit postits)
821       (emit-back-patch segment 0 postit)))
822   (let ((hook (segment-inst-hook segment)))
823     (when hook
824       (funcall hook segment vop :label label)))
825   (emit-annotation segment label))
826
827 ;;; Called by the ALIGN macro to emit an alignment note. We check to
828 ;;; see if we can guarantee the alignment restriction by just
829 ;;; outputting a fixed number of bytes. If so, we do so. Otherwise, we
830 ;;; create and emit an alignment note.
831 (defun emit-alignment (segment vop bits &optional (fill-byte 0))
832   (when (segment-run-scheduler segment)
833     (schedule-pending-instructions segment))
834   (let ((hook (segment-inst-hook segment)))
835     (when hook
836       (funcall hook segment vop :align bits)))
837   (let ((alignment (segment-alignment segment))
838         (offset (- (segment-current-posn segment)
839                    (segment-sync-posn segment))))
840     (cond ((> bits alignment)
841            ;; We need more bits of alignment. First emit enough noise
842            ;; to get back in sync with alignment, and then emit an
843            ;; alignment note to cover the rest.
844            (let ((slop (logand offset (1- (ash 1 alignment)))))
845              (unless (zerop slop)
846                (emit-skip segment (- (ash 1 alignment) slop) fill-byte)))
847            (let ((size (logand (1- (ash 1 bits))
848                                (lognot (1- (ash 1 alignment))))))
849              (aver (> size 0))
850              (emit-annotation segment (make-alignment bits size fill-byte))
851              (emit-skip segment size fill-byte))
852            (setf (segment-alignment segment) bits)
853            (setf (segment-sync-posn segment) (segment-current-posn segment)))
854           (t
855            ;; The last alignment was more restrictive then this one.
856            ;; So we can just figure out how much noise to emit
857            ;; assuming the last alignment was met.
858            (let* ((mask (1- (ash 1 bits)))
859                   (new-offset (logand (+ offset mask) (lognot mask))))
860              (emit-skip segment (- new-offset offset) fill-byte))
861            ;; But we emit an alignment with size=0 so we can verify
862            ;; that everything works.
863            (emit-annotation segment (make-alignment bits 0 fill-byte)))))
864   (values))
865
866 ;;; Used to find how ``aligned'' different offsets are. Returns the
867 ;;; number of low-order 0 bits, up to MAX-ALIGNMENT.
868 (defun find-alignment (offset)
869   (dotimes (i max-alignment max-alignment)
870     (when (logbitp i offset)
871       (return i))))
872
873 ;;; Emit a postit. The function will be called as a back-patch with
874 ;;; the position the following instruction is finally emitted. Postits
875 ;;; do not interfere at all with scheduling.
876 (defun %emit-postit (segment function)
877   (push function (segment-postits segment))
878   (values))
879 \f
880 ;;;; output compression/position assignment stuff
881
882 ;;; Grovel though all the annotations looking for choosers. When we
883 ;;; find a chooser, invoke the maybe-shrink function. If it returns T,
884 ;;; it output some other byte sequence.
885 (defun compress-output (segment)
886   (dotimes (i 5) ; it better not take more than one or two passes.
887     (let ((delta 0))
888       (setf (segment-alignment segment) max-alignment)
889       (setf (segment-sync-posn segment) 0)
890       (do* ((prev nil)
891             (remaining (segment-annotations segment) next)
892             (next (cdr remaining) (cdr remaining)))
893            ((null remaining))
894         (let* ((note (car remaining))
895                (posn (annotation-posn note)))
896           (unless (zerop delta)
897             (decf posn delta)
898             (setf (annotation-posn note) posn))
899           (cond
900            ((chooser-p note)
901             (setf (segment-current-index segment) (chooser-index note))
902             (setf (segment-current-posn segment) posn)
903             (setf (segment-last-annotation segment) prev)
904             (cond
905              ((funcall (chooser-maybe-shrink note) segment posn delta)
906               ;; It emitted some replacement.
907               (let ((new-size (- (segment-current-index segment)
908                                  (chooser-index note)))
909                     (old-size (chooser-size note)))
910                 (when (> new-size old-size)
911                   (error "~S emitted ~W bytes, but claimed its max was ~W."
912                          note new-size old-size))
913                 (let ((additional-delta (- old-size new-size)))
914                   (when (< (find-alignment additional-delta)
915                            (chooser-alignment note))
916                     (error "~S shrunk by ~W bytes, but claimed that it ~
917                             preserves ~W bits of alignment."
918                            note additional-delta (chooser-alignment note)))
919                   (incf delta additional-delta)
920                   (emit-filler segment additional-delta))
921                 (setf prev (segment-last-annotation segment))
922                 (if prev
923                     (setf (cdr prev) (cdr remaining))
924                     (setf (segment-annotations segment)
925                           (cdr remaining)))))
926              (t
927               ;; The chooser passed on shrinking. Make sure it didn't emit
928               ;; anything.
929               (unless (= (segment-current-index segment) (chooser-index note))
930                 (error "Chooser ~S passed, but not before emitting ~W bytes."
931                        note
932                        (- (segment-current-index segment)
933                           (chooser-index note))))
934               ;; Act like we just emitted this chooser.
935               (let ((size (chooser-size note)))
936                 (incf (segment-current-index segment) size)
937                 (incf (segment-current-posn segment) size))
938               ;; Adjust the alignment accordingly.
939               (adjust-alignment-after-chooser segment note)
940               ;; And keep this chooser for next time around.
941               (setf prev remaining))))
942            ((alignment-p note)
943             (unless (zerop (alignment-size note))
944               ;; Re-emit the alignment, letting it collapse if we know
945               ;; anything more about the alignment guarantees of the
946               ;; segment.
947               (let ((index (alignment-index note)))
948                 (setf (segment-current-index segment) index)
949                 (setf (segment-current-posn segment) posn)
950                 (setf (segment-last-annotation segment) prev)
951                 (emit-alignment segment nil (alignment-bits note)
952                                 (alignment-fill-byte note))
953                 (let* ((new-index (segment-current-index segment))
954                        (size (- new-index index))
955                        (old-size (alignment-size note))
956                        (additional-delta (- old-size size)))
957                   (when (minusp additional-delta)
958                     (error "Alignment ~S needs more space now?  It was ~W, ~
959                             and is ~W now."
960                            note old-size size))
961                   (when (plusp additional-delta)
962                     (emit-filler segment additional-delta)
963                     (incf delta additional-delta)))
964                 (setf prev (segment-last-annotation segment))
965                 (if prev
966                     (setf (cdr prev) (cdr remaining))
967                     (setf (segment-annotations segment)
968                           (cdr remaining))))))
969            (t
970             (setf prev remaining)))))
971       (when (zerop delta)
972         (return))
973       (decf (segment-final-posn segment) delta)))
974   (values))
975
976 ;;; We have run all the choosers we can, so now we have to figure out exactly
977 ;;; how much space each alignment note needs.
978 (defun finalize-positions (segment)
979   (let ((delta 0))
980     (do* ((prev nil)
981           (remaining (segment-annotations segment) next)
982           (next (cdr remaining) (cdr remaining)))
983          ((null remaining))
984       (let* ((note (car remaining))
985              (posn (- (annotation-posn note) delta)))
986         (cond
987          ((alignment-p note)
988           (let* ((bits (alignment-bits note))
989                  (mask (1- (ash 1 bits)))
990                  (new-posn (logand (+ posn mask) (lognot mask)))
991                  (size (- new-posn posn))
992                  (old-size (alignment-size note))
993                  (additional-delta (- old-size size)))
994             (aver (<= 0 size old-size))
995             (unless (zerop additional-delta)
996               (setf (segment-last-annotation segment) prev)
997               (incf delta additional-delta)
998               (setf (segment-current-index segment) (alignment-index note))
999               (setf (segment-current-posn segment) posn)
1000               (emit-filler segment additional-delta)
1001               (setf prev (segment-last-annotation segment)))
1002             (if prev
1003                 (setf (cdr prev) next)
1004                 (setf (segment-annotations segment) next))))
1005          (t
1006           (setf (annotation-posn note) posn)
1007           (setf prev remaining)
1008           (setf next (cdr remaining))))))
1009     (unless (zerop delta)
1010       (decf (segment-final-posn segment) delta)))
1011   (values))
1012
1013 ;;; Grovel over segment, filling in any backpatches. If any choosers
1014 ;;; are left over, we need to emit their worst case varient.
1015 (defun process-back-patches (segment)
1016   (do* ((prev nil)
1017         (remaining (segment-annotations segment) next)
1018         (next (cdr remaining) (cdr remaining)))
1019       ((null remaining))
1020     (let ((note (car remaining)))
1021       (flet ((fill-in (function old-size)
1022                (let ((index (annotation-index note))
1023                      (posn (annotation-posn note)))
1024                  (setf (segment-current-index segment) index)
1025                  (setf (segment-current-posn segment) posn)
1026                  (setf (segment-last-annotation segment) prev)
1027                  (funcall function segment posn)
1028                  (let ((new-size (- (segment-current-index segment) index)))
1029                    (unless (= new-size old-size)
1030                      (error "~S emitted ~W bytes, but claimed it was ~W."
1031                             note new-size old-size)))
1032                  (let ((tail (segment-last-annotation segment)))
1033                    (if tail
1034                        (setf (cdr tail) next)
1035                        (setf (segment-annotations segment) next)))
1036                  (setf next (cdr prev)))))
1037         (cond ((back-patch-p note)
1038                (fill-in (back-patch-function note)
1039                         (back-patch-size note)))
1040               ((chooser-p note)
1041                (fill-in (chooser-worst-case-fun note)
1042                         (chooser-size note)))
1043               (t
1044                (setf prev remaining)))))))
1045 \f
1046 ;;;; interface to the rest of the compiler
1047
1048 ;;; This holds the current segment while assembling. Use ASSEMBLE to
1049 ;;; change it.
1050 ;;;
1051 ;;; The double asterisks in the name are intended to suggest that this
1052 ;;; isn't just any old special variable, it's an extra-special
1053 ;;; variable, because sometimes MACROLET is used to bind it. So be
1054 ;;; careful out there..
1055 (defvar **current-segment**)
1056
1057 ;;; Just like **CURRENT-SEGMENT**, except this holds the current vop.
1058 ;;; Used only to keep track of which vops emit which insts.
1059 ;;;
1060 ;;; The double asterisks in the name are intended to suggest that this
1061 ;;; isn't just any old special variable, it's an extra-special
1062 ;;; variable, because sometimes MACROLET is used to bind it. So be
1063 ;;; careful out there..
1064 (defvar **current-vop** nil)
1065
1066 ;;; We also SYMBOL-MACROLET **CURRENT-SEGMENT** to a local holding the
1067 ;;; segment so uses of **CURRENT-SEGMENT** inside the body don't have
1068 ;;; to keep dereferencing the symbol. Given that ASSEMBLE is the only
1069 ;;; interface to **CURRENT-SEGMENT**, we don't have to worry about the
1070 ;;; special value becomming out of sync with the lexical value. Unless
1071 ;;; some bozo closes over it, but nobody does anything like that...
1072 ;;;
1073 ;;; FIXME: The way this macro uses MACROEXPAND internally breaks my
1074 ;;; old assumptions about macros which are needed both in the host and
1075 ;;; the target. (This is more or less the same way that PUSH-IN,
1076 ;;; DELETEF-IN, and DEF-BOOLEAN-ATTRIBUTE break my old assumptions,
1077 ;;; except that they used GET-SETF-EXPANSION instead of MACROEXPAND to
1078 ;;; do the dirty deed.) The quick and dirty "solution" here is the
1079 ;;; same as there: use cut and paste to duplicate the defmacro in a
1080 ;;; (SB!INT:DEF!MACRO FOO (..) .. CL:MACROEXPAND ..) #+SB-XC-HOST
1081 ;;; (DEFMACRO FOO (..) .. SB!XC:MACROEXPAND ..) idiom. This is
1082 ;;; disgusting and unmaintainable, and there are obviously better
1083 ;;; solutions and maybe even good solutions, but I'm disinclined to
1084 ;;; hunt for good solutions until the system works and I can test them
1085 ;;; in isolation.
1086 (sb!int:def!macro assemble ((&optional segment vop &key labels) &body body
1087                             &environment env)
1088   #!+sb-doc
1089   "Execute BODY (as a progn) with SEGMENT as the current segment."
1090   (flet ((label-name-p (thing)
1091            (and thing (symbolp thing))))
1092     (let* ((seg-var (gensym "SEGMENT-"))
1093            (vop-var (gensym "VOP-"))
1094            (visible-labels (remove-if-not #'label-name-p body))
1095            (inherited-labels
1096             (multiple-value-bind (expansion expanded)
1097                 (macroexpand '..inherited-labels.. env)
1098               (if expanded expansion nil)))
1099            (new-labels (append labels
1100                                (set-difference visible-labels
1101                                                inherited-labels)))
1102            (nested-labels (set-difference (append inherited-labels new-labels)
1103                                           visible-labels)))
1104       (when (intersection labels inherited-labels)
1105         (error "duplicate nested labels: ~S"
1106                (intersection labels inherited-labels)))
1107       `(let* ((,seg-var ,(or segment '**current-segment**))
1108               (,vop-var ,(or vop '**current-vop**))
1109               ,@(when segment
1110                   `((**current-segment** ,seg-var)))
1111               ,@(when vop
1112                   `((**current-vop** ,vop-var)))
1113               ,@(mapcar #'(lambda (name)
1114                             `(,name (gen-label)))
1115                         new-labels))
1116          (symbol-macrolet ((**current-segment** ,seg-var)
1117                            (**current-vop** ,vop-var)
1118                            ,@(when (or inherited-labels nested-labels)
1119                                `((..inherited-labels.. ,nested-labels))))
1120            ,@(mapcar #'(lambda (form)
1121                          (if (label-name-p form)
1122                              `(emit-label ,form)
1123                              form))
1124                      body))))))
1125 #+sb-xc-host
1126 (sb!xc:defmacro assemble ((&optional segment vop &key labels)
1127                           &body body
1128                           &environment env)
1129   #!+sb-doc
1130   "Execute BODY (as a progn) with SEGMENT as the current segment."
1131   (flet ((label-name-p (thing)
1132            (and thing (symbolp thing))))
1133     (let* ((seg-var (gensym "SEGMENT-"))
1134            (vop-var (gensym "VOP-"))
1135            (visible-labels (remove-if-not #'label-name-p body))
1136            (inherited-labels
1137             (multiple-value-bind
1138                 (expansion expanded)
1139                 (sb!xc:macroexpand '..inherited-labels.. env)
1140               (if expanded expansion nil)))
1141            (new-labels (append labels
1142                                (set-difference visible-labels
1143                                                inherited-labels)))
1144            (nested-labels (set-difference (append inherited-labels new-labels)
1145                                           visible-labels)))
1146       (when (intersection labels inherited-labels)
1147         (error "duplicate nested labels: ~S"
1148                (intersection labels inherited-labels)))
1149       `(let* ((,seg-var ,(or segment '**current-segment**))
1150               (,vop-var ,(or vop '**current-vop**))
1151               ,@(when segment
1152                   `((**current-segment** ,seg-var)))
1153               ,@(when vop
1154                   `((**current-vop** ,vop-var)))
1155               ,@(mapcar #'(lambda (name)
1156                             `(,name (gen-label)))
1157                         new-labels))
1158          (symbol-macrolet ((**current-segment** ,seg-var)
1159                            (**current-vop** ,vop-var)
1160                            ,@(when (or inherited-labels nested-labels)
1161                                `((..inherited-labels.. ,nested-labels))))
1162            ,@(mapcar #'(lambda (form)
1163                          (if (label-name-p form)
1164                              `(emit-label ,form)
1165                              form))
1166                      body))))))
1167
1168 (defmacro inst (&whole whole instruction &rest args &environment env)
1169   #!+sb-doc
1170   "Emit the specified instruction to the current segment."
1171   (let ((inst (gethash (symbol-name instruction) *assem-instructions*)))
1172     (cond ((null inst)
1173            (error "unknown instruction: ~S" instruction))
1174           ((functionp inst)
1175            (funcall inst (cdr whole) env))
1176           (t
1177            `(,inst **current-segment** **current-vop** ,@args)))))
1178
1179 ;;; Note: The need to capture SYMBOL-MACROLET bindings of
1180 ;;; **CURRENT-SEGMENT* and **CURRENT-VOP** prevents this from being an
1181 ;;; ordinary function.
1182 (defmacro emit-label (label)
1183   #!+sb-doc
1184   "Emit LABEL at this location in the current segment."
1185   `(%emit-label **current-segment** **current-vop** ,label))
1186
1187 ;;; Note: The need to capture SYMBOL-MACROLET bindings of
1188 ;;; **CURRENT-SEGMENT* prevents this from being an ordinary function.
1189 (defmacro emit-postit (function)
1190   `(%emit-postit **current-segment** ,function))
1191
1192 ;;; Note: The need to capture SYMBOL-MACROLET bindings of
1193 ;;; **CURRENT-SEGMENT* and **CURRENT-VOP** prevents this from being an
1194 ;;; ordinary function.
1195 (defmacro align (bits &optional (fill-byte 0))
1196   #!+sb-doc
1197   "Emit an alignment restriction to the current segment."
1198   `(emit-alignment **current-segment** **current-vop** ,bits ,fill-byte))
1199 ;;; FIXME: By analogy with EMIT-LABEL and EMIT-POSTIT, this should be
1200 ;;; called EMIT-ALIGNMENT, and the function that it calls should be
1201 ;;; called %EMIT-ALIGNMENT.
1202
1203 (defun label-position (label &optional if-after delta)
1204   #!+sb-doc
1205   "Return the current position for LABEL. Chooser maybe-shrink functions
1206    should supply IF-AFTER and DELTA in order to ensure correct results."
1207   (let ((posn (label-posn label)))
1208     (if (and if-after (> posn if-after))
1209         (- posn delta)
1210         posn)))
1211
1212 (defun append-segment (segment other-segment)
1213   #!+sb-doc
1214   "Append OTHER-SEGMENT to the end of SEGMENT. Don't use OTHER-SEGMENT
1215    for anything after this."
1216   (when (segment-run-scheduler segment)
1217     (schedule-pending-instructions segment))
1218   (let ((postits (segment-postits segment)))
1219     (setf (segment-postits segment) (segment-postits other-segment))
1220     (dolist (postit postits)
1221       (emit-back-patch segment 0 postit)))
1222   #!-x86 (emit-alignment segment nil max-alignment)
1223   #!+x86 (emit-alignment segment nil max-alignment #x90)
1224   (let ((segment-current-index-0 (segment-current-index segment))
1225         (segment-current-posn-0  (segment-current-posn  segment)))
1226     (incf (segment-current-index segment)
1227           (segment-current-index other-segment))
1228     (replace (segment-buffer segment)
1229              (segment-buffer other-segment)
1230              :start1 segment-current-index-0)
1231     (setf (segment-buffer other-segment) nil) ; to prevent accidental reuse
1232     (incf (segment-current-posn segment)
1233           (segment-current-posn other-segment))
1234     (let ((other-annotations (segment-annotations other-segment)))
1235       (when other-annotations
1236         (dolist (note other-annotations)
1237           (incf (annotation-index note) segment-current-index-0)
1238           (incf (annotation-posn note) segment-current-posn-0))
1239         ;; This SEGMENT-LAST-ANNOTATION code is confusing. Is it really
1240         ;; worth enough in efficiency to justify it? -- WHN 19990322
1241         (let ((last (segment-last-annotation segment)))
1242           (if last
1243             (setf (cdr last) other-annotations)
1244             (setf (segment-annotations segment) other-annotations)))
1245         (setf (segment-last-annotation segment)
1246               (segment-last-annotation other-segment)))))
1247   (values))
1248
1249 (defun finalize-segment (segment)
1250   #!+sb-doc
1251   "Do any final processing of SEGMENT and return the total number of bytes
1252    covered by this segment."
1253   (when (segment-run-scheduler segment)
1254     (schedule-pending-instructions segment))
1255   (setf (segment-run-scheduler segment) nil)
1256   (let ((postits (segment-postits segment)))
1257     (setf (segment-postits segment) nil)
1258     (dolist (postit postits)
1259       (emit-back-patch segment 0 postit)))
1260   (setf (segment-final-index segment) (segment-current-index segment))
1261   (setf (segment-final-posn segment) (segment-current-posn segment))
1262   (setf (segment-inst-hook segment) nil)
1263   (compress-output segment)
1264   (finalize-positions segment)
1265   (process-back-patches segment)
1266   (segment-final-posn segment))
1267
1268 ;;; Call FUNCTION on all the stuff accumulated in SEGMENT. FUNCTION
1269 ;;; should accept a single vector argument. It will be called zero or
1270 ;;; more times on vectors of the appropriate byte type. The
1271 ;;; concatenation of the vector arguments from all the calls is the
1272 ;;; contents of SEGMENT.
1273 ;;;
1274 ;;; KLUDGE: This implementation is sort of slow and gross, calling
1275 ;;; FUNCTION repeatedly and consing a fresh vector for its argument
1276 ;;; each time. It might be possible to make a more efficient version
1277 ;;; by making FINALIZE-SEGMENT do all the compacting currently done by
1278 ;;; this function: then this function could become trivial and fast,
1279 ;;; calling FUNCTION once on the entire compacted segment buffer. --
1280 ;;; WHN 19990322
1281 (defun on-segment-contents-vectorly (segment function)
1282   (let ((buffer (segment-buffer segment))
1283         (i0 0))
1284     (flet ((frob (i0 i1)
1285              (when (< i0 i1)
1286                (funcall function (subseq buffer i0 i1)))))
1287       (dolist (note (segment-annotations segment))
1288         (when (filler-p note)
1289           (let ((i1 (filler-index note)))
1290             (frob i0 i1)
1291             (setf i0 (+ i1 (filler-bytes note))))))
1292       (frob i0 (segment-final-index segment))))
1293   (values))
1294
1295 ;;; Write the code accumulated in SEGMENT to STREAM, and return the
1296 ;;; number of bytes written.
1297 (defun write-segment-contents (segment stream)
1298   (let ((result 0))
1299     (declare (type index result))
1300     (on-segment-contents-vectorly segment
1301                                   (lambda (v)
1302                                     (declare (type (vector assembly-unit) v))
1303                                     (incf result (length v))
1304                                     (write-sequence v stream)))
1305     result))
1306 \f
1307 ;;;; interface to the instruction set definition
1308
1309 ;;; Define a function named NAME that merges its arguments into a
1310 ;;; single integer and then emits the bytes of that integer in the
1311 ;;; correct order based on the endianness of the target-backend.
1312 (defmacro define-bitfield-emitter (name total-bits &rest byte-specs)
1313   (sb!int:collect ((arg-names) (arg-types))
1314     (let* ((total-bits (eval total-bits))
1315            (overall-mask (ash -1 total-bits))
1316            (num-bytes (multiple-value-bind (quo rem)
1317                           (truncate total-bits assembly-unit-bits)
1318                         (unless (zerop rem)
1319                           (error "~W isn't an even multiple of ~W."
1320                                  total-bits assembly-unit-bits))
1321                         quo))
1322            (bytes (make-array num-bytes :initial-element nil))
1323            (segment-arg (gensym "SEGMENT-")))
1324       (dolist (byte-spec-expr byte-specs)
1325         (let* ((byte-spec (eval byte-spec-expr))
1326                (byte-size (byte-size byte-spec))
1327                (byte-posn (byte-position byte-spec))
1328                (arg (gensym (format nil "~:@(ARG-FOR-~S-~)" byte-spec-expr))))
1329           (when (ldb-test (byte byte-size byte-posn) overall-mask)
1330             (error "The byte spec ~S either overlaps another byte spec, or ~
1331                     extends past the end."
1332                    byte-spec-expr))
1333           (setf (ldb byte-spec overall-mask) -1)
1334           (arg-names arg)
1335           (arg-types `(type (integer ,(ash -1 (1- byte-size))
1336                                      ,(1- (ash 1 byte-size)))
1337                             ,arg))
1338           (multiple-value-bind (start-byte offset)
1339               (floor byte-posn assembly-unit-bits)
1340             (let ((end-byte (floor (1- (+ byte-posn byte-size))
1341                                    assembly-unit-bits)))
1342               (flet ((maybe-ash (expr offset)
1343                        (if (zerop offset)
1344                            expr
1345                            `(ash ,expr ,offset))))
1346                 (declare (inline maybe-ash))
1347                 (cond ((zerop byte-size))
1348                       ((= start-byte end-byte)
1349                        (push (maybe-ash `(ldb (byte ,byte-size 0) ,arg)
1350                                         offset)
1351                              (svref bytes start-byte)))
1352                       (t
1353                        (push (maybe-ash
1354                               `(ldb (byte ,(- assembly-unit-bits offset) 0)
1355                                     ,arg)
1356                               offset)
1357                              (svref bytes start-byte))
1358                        (do ((index (1+ start-byte) (1+ index)))
1359                            ((>= index end-byte))
1360                          (push
1361                           `(ldb (byte ,assembly-unit-bits
1362                                       ,(- (* assembly-unit-bits
1363                                              (- index start-byte))
1364                                           offset))
1365                                 ,arg)
1366                           (svref bytes index)))
1367                        (let ((len (rem (+ byte-size offset)
1368                                        assembly-unit-bits)))
1369                          (push
1370                           `(ldb (byte ,(if (zerop len)
1371                                            assembly-unit-bits
1372                                            len)
1373                                       ,(- (* assembly-unit-bits
1374                                              (- end-byte start-byte))
1375                                           offset))
1376                                 ,arg)
1377                           (svref bytes end-byte))))))))))
1378       (unless (= overall-mask -1)
1379         (error "There are holes."))
1380       (let ((forms nil))
1381         (dotimes (i num-bytes)
1382           (let ((pieces (svref bytes i)))
1383             (aver pieces)
1384             (push `(emit-byte ,segment-arg
1385                               ,(if (cdr pieces)
1386                                    `(logior ,@pieces)
1387                                    (car pieces)))
1388                   forms)))
1389         `(defun ,name (,segment-arg ,@(arg-names))
1390            (declare (type segment ,segment-arg) ,@(arg-types))
1391            ,@(ecase sb!c:*backend-byte-order*
1392                (:little-endian (nreverse forms))
1393                (:big-endian forms))
1394            ',name)))))
1395
1396 (defun grovel-lambda-list (lambda-list vop-var)
1397   (let ((segment-name (car lambda-list))
1398         (vop-var (or vop-var (gensym "VOP-"))))
1399     (sb!int:collect ((new-lambda-list))
1400       (new-lambda-list segment-name)
1401       (new-lambda-list vop-var)
1402       (labels
1403           ((grovel (state lambda-list)
1404              (when lambda-list
1405                (let ((param (car lambda-list)))
1406                  (cond
1407                   ((member param sb!xc:lambda-list-keywords)
1408                    (new-lambda-list param)
1409                    (grovel param (cdr lambda-list)))
1410                   (t
1411                    (ecase state
1412                      ((nil)
1413                       (new-lambda-list param)
1414                       `(cons ,param ,(grovel state (cdr lambda-list))))
1415                      (&optional
1416                       (multiple-value-bind (name default supplied-p)
1417                           (if (consp param)
1418                               (values (first param)
1419                                       (second param)
1420                                       (or (third param)
1421                                           (gensym "SUPPLIED-P-")))
1422                               (values param nil (gensym "SUPPLIED-P-")))
1423                         (new-lambda-list (list name default supplied-p))
1424                         `(and ,supplied-p
1425                               (cons ,(if (consp name)
1426                                          (second name)
1427                                          name)
1428                                     ,(grovel state (cdr lambda-list))))))
1429                      (&key
1430                       (multiple-value-bind (name default supplied-p)
1431                           (if (consp param)
1432                               (values (first param)
1433                                       (second param)
1434                                       (or (third param)
1435                                           (gensym "SUPPLIED-P-")))
1436                               (values param nil (gensym "SUPPLIED-P-")))
1437                         (new-lambda-list (list name default supplied-p))
1438                         (multiple-value-bind (key var)
1439                             (if (consp name)
1440                                 (values (first name) (second name))
1441                                 (values (keywordicate name) name))
1442                           `(append (and ,supplied-p (list ',key ,var))
1443                                    ,(grovel state (cdr lambda-list))))))
1444                      (&rest
1445                       (new-lambda-list param)
1446                       (grovel state (cdr lambda-list))
1447                       param))))))))
1448         (let ((reconstructor (grovel nil (cdr lambda-list))))
1449           (values (new-lambda-list)
1450                   segment-name
1451                   vop-var
1452                   reconstructor))))))
1453
1454 (defun extract-nths (index glue list-of-lists-of-lists)
1455   (mapcar #'(lambda (list-of-lists)
1456               (cons glue
1457                     (mapcar #'(lambda (list)
1458                                 (nth index list))
1459                             list-of-lists)))
1460           list-of-lists-of-lists))
1461
1462 (defmacro define-instruction (name lambda-list &rest options)
1463   (let* ((sym-name (symbol-name name))
1464          (defun-name (sb!int:symbolicate sym-name "-INST-EMITTER"))
1465          (vop-var nil)
1466          (postits (gensym "POSTITS-"))
1467          (emitter nil)
1468          (decls nil)
1469          (attributes nil)
1470          (cost nil)
1471          (dependencies nil)
1472          (delay nil)
1473          (pinned nil)
1474          (pdefs nil))
1475     (sb!int:/noshow "entering DEFINE-INSTRUCTION" name lambda-list options)
1476     (dolist (option-spec options)
1477       (sb!int:/noshow option-spec)
1478       (multiple-value-bind (option args)
1479           (if (consp option-spec)
1480               (values (car option-spec) (cdr option-spec))
1481               (values option-spec nil))
1482         (sb!int:/noshow option args)
1483         (case option
1484           (:emitter
1485            (when emitter
1486              (error "You can only specify :EMITTER once per instruction."))
1487            (setf emitter args))
1488           (:declare
1489            (setf decls (append decls args)))
1490           (:attributes
1491            (setf attributes (append attributes args)))
1492           (:cost
1493            (setf cost (first args)))
1494           (:dependencies
1495            (setf dependencies (append dependencies args)))
1496           (:delay
1497            (when delay
1498              (error "You can only specify :DELAY once per instruction."))
1499            (setf delay args))
1500           (:pinned
1501            (setf pinned t))
1502           (:vop-var
1503            (if vop-var
1504                (error "You can only specify :VOP-VAR once per instruction.")
1505                (setf vop-var (car args))))
1506           (:printer
1507            (sb!int:/noshow "uniquifying :PRINTER with" args)
1508            (push (eval `(list (multiple-value-list
1509                                ,(sb!disassem:gen-printer-def-forms-def-form
1510                                  name
1511                                  (format nil "~A[~A]" name args)
1512                                  (cdr option-spec)))))
1513                  pdefs))
1514           (:printer-list
1515            ;; same as :PRINTER, but is EVALed first, and is a list of
1516            ;; printers
1517            (push
1518             (eval
1519              `(eval
1520                `(list ,@(mapcar (lambda (printer)
1521                                   `(multiple-value-list
1522                                     ,(sb!disassem:gen-printer-def-forms-def-form
1523                                       ',name
1524                                       (format nil "~A[~A]" ',name printer)
1525                                       printer
1526                                       nil)))
1527                                 ,(cadr option-spec)))))
1528             pdefs))
1529           (t
1530            (error "unknown option: ~S" option)))))
1531     (sb!int:/noshow "done processing options")
1532     (setf pdefs (nreverse pdefs))
1533     (multiple-value-bind
1534         (new-lambda-list segment-name vop-name arg-reconstructor)
1535         (grovel-lambda-list lambda-list vop-var)
1536       (sb!int:/noshow new-lambda-list segment-name vop-name arg-reconstructor)
1537       (push `(let ((hook (segment-inst-hook ,segment-name)))
1538                (when hook
1539                  (funcall hook ,segment-name ,vop-name ,sym-name
1540                           ,arg-reconstructor)))
1541             emitter)
1542       (push `(dolist (postit ,postits)
1543                (emit-back-patch ,segment-name 0 postit))
1544             emitter)
1545       (unless cost (setf cost 1))
1546       #!+sb-dyncount
1547       (push `(when (segment-collect-dynamic-statistics ,segment-name)
1548                (let* ((info (sb!c:ir2-component-dyncount-info
1549                              (sb!c:component-info
1550                               sb!c:*component-being-compiled*)))
1551                       (costs (sb!c:dyncount-info-costs info))
1552                       (block-number (sb!c:block-number
1553                                      (sb!c:ir2-block-block
1554                                       (sb!c:vop-block ,vop-name)))))
1555                  (incf (aref costs block-number) ,cost)))
1556             emitter)
1557       (when *assem-scheduler-p*
1558         (if pinned
1559             (setf emitter
1560                   `((when (segment-run-scheduler ,segment-name)
1561                       (schedule-pending-instructions ,segment-name))
1562                     ,@emitter))
1563             (let ((flet-name
1564                    (gensym (concatenate 'string "EMIT-" sym-name "-INST-")))
1565                   (inst-name (gensym "INST-")))
1566               (setf emitter `((flet ((,flet-name (,segment-name)
1567                                        ,@emitter))
1568                                 (if (segment-run-scheduler ,segment-name)
1569                                     (let ((,inst-name
1570                                            (make-instruction
1571                                             (incf (segment-inst-number
1572                                                    ,segment-name))
1573                                             #',flet-name
1574                                             (instruction-attributes
1575                                              ,@attributes)
1576                                             (progn ,@delay))))
1577                                       ,@(when dependencies
1578                                           `((note-dependencies
1579                                                 (,segment-name ,inst-name)
1580                                               ,@dependencies)))
1581                                       (queue-inst ,segment-name ,inst-name))
1582                                     (,flet-name ,segment-name))))))))
1583       `(progn
1584          (defun ,defun-name ,new-lambda-list
1585            ,@(when decls
1586                `((declare ,@decls)))
1587            (let ((,postits (segment-postits ,segment-name)))
1588              (setf (segment-postits ,segment-name) nil)
1589              (symbol-macrolet
1590                  (;; Apparently this binding is intended to keep
1591                   ;; anyone from accidentally using
1592                   ;; **CURRENT-SEGMENT** within the body of the
1593                   ;; emitter. The error message sorta suggests that
1594                   ;; this can happen accidentally by including one
1595                   ;; emitter inside another. But I dunno.. -- WHN
1596                   ;; 19990323
1597                   (**current-segment**
1598                    ;; FIXME: I can't see why we have to use
1599                    ;;   (MACROLET ((LOSE () (ERROR ..))) (LOSE))
1600                    ;; instead of just (ERROR "..") here.
1601                    (macrolet ((lose ()
1602                                 (error "You can't use INST without an ~
1603                                         ASSEMBLE inside emitters.")))
1604                      (lose))))
1605                ,@emitter))
1606            (values))
1607          (eval-when (:compile-toplevel :load-toplevel :execute)
1608            (%define-instruction ,sym-name ',defun-name))
1609          ,@(extract-nths 1 'progn pdefs)
1610          ,@(when pdefs
1611              `((sb!disassem:install-inst-flavors
1612                 ',name
1613                 (append ,@(extract-nths 0 'list pdefs)))))))))
1614
1615 (defmacro define-instruction-macro (name lambda-list &body body)
1616   (let ((whole (gensym "WHOLE-"))
1617         (env (gensym "ENV-")))
1618     (multiple-value-bind (body local-defs)
1619         (sb!kernel:parse-defmacro lambda-list
1620                                   whole
1621                                   body
1622                                   name
1623                                   'instruction-macro
1624                                   :environment env)
1625       `(eval-when (:compile-toplevel :load-toplevel :execute)
1626          (%define-instruction ,(symbol-name name)
1627                               #'(lambda (,whole ,env)
1628                                   ,@local-defs
1629                                   (block ,name
1630                                     ,body)))))))
1631
1632 (defun %define-instruction (name defun)
1633   (setf (gethash name *assem-instructions*) defun)
1634   name)