0.6.7.22: removed CVS dollar-Header-dollar tags from sources
[sbcl.git] / src / compiler / disassem.lisp
1 ;;;; machine-independent disassembler
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!DISASSEM")
13 \f
14 ;;; types and defaults
15
16 (defconstant label-column-width 7)
17
18 (deftype text-width () '(integer 0 1000))
19 (deftype alignment () '(integer 0 64))
20 (deftype offset () '(signed-byte 24))
21 (deftype address () '(unsigned-byte 32))
22 (deftype length () '(unsigned-byte 24))
23 (deftype column () '(integer 0 1000))
24
25 (defconstant max-filtered-value-index 32)
26 (deftype filtered-value-index ()
27   `(integer 0 ,max-filtered-value-index))
28 (deftype filtered-value-vector ()
29   `(simple-array t (,max-filtered-value-index)))
30 \f
31 ;;;; disassembly parameters
32
33 ;;; instructions
34 (defvar *disassem-insts* (make-hash-table :test 'eq))
35 (declaim (type hash-table *disassem-insts*))
36
37 (defvar *disassem-inst-space* nil)
38 (declaim (type (or null inst-space) *disassem-inst-space*))
39
40 ;;; minimum alignment of instructions, in bytes
41 (defvar *disassem-inst-alignment-bytes* sb!vm:word-bytes)
42 (declaim (type alignment *disassem-inst-alignment-bytes*))
43
44 (defvar *disassem-location-column-width* 8)
45 (declaim (type text-width *disassem-location-column-width*))
46
47 ;;; the width of the column in which instruction-names are printed. A
48 ;;; value of zero gives the effect of not aligning the arguments at
49 ;;; all.
50 (defvar *disassem-opcode-column-width* 6)
51 (declaim (type text-width *disassem-opcode-column-width*))
52
53 (defvar *disassem-note-column* 45
54   #!+sb-doc
55   "The column in which end-of-line comments for notes are started.")
56
57 ;;; the old CMU CL code to set the CMU CL disassembly parameters
58 #|
59 (defmacro set-disassem-params (&rest args)
60   #!+sb-doc
61   "Specify global disassembler params. Keyword arguments include:
62
63   :INSTRUCTION-ALIGNMENT number
64       Minimum alignment of instructions, in bits.
65
66   :ADDRESS-SIZE number
67       Size of a machine address, in bits.
68
69   :OPCODE-COLUMN-WIDTH
70       Width of the column used for printing the opcode portion of the
71       instruction, or NIL to use the default."
72   (gen-preamble-form args))
73
74 (defun gen-preamble-form (args)
75   #!+sb-doc
76   "Generate a form to specify global disassembler params. See the
77   documentation for SET-DISASSEM-PARAMS for more info."
78   (destructuring-bind
79       (&key instruction-alignment
80             address-size
81             (opcode-column-width nil opcode-column-width-p))
82       args
83     `(progn
84        (eval-when (:compile-toplevel :execute)
85          ;; these are not in the params because they only exist at compile time
86          (defparameter ,(format-table-name) (make-hash-table))
87          (defparameter ,(arg-type-table-name) nil)
88          (defparameter ,(function-cache-name) (make-function-cache)))
89        (let ((params
90               (or sb!c:*backend-disassem-params*
91                   (setf sb!c:*backend-disassem-params* (make-params)))))
92          (declare (ignorable params))
93          ,(when instruction-alignment
94             `(setf (params-instruction-alignment params)
95                    (bits-to-bytes ,instruction-alignment)))
96          ,(when address-size
97             `(setf (params-location-column-width params)
98                    (* 2 ,address-size)))
99          ,(when opcode-column-width-p
100             `(setf (params-opcode-column-width params) ,opcode-column-width))
101          'disassem-params))))
102 |#
103 \f
104 ;;;; cached functions
105
106 (defstruct function-cache
107   (printers nil :type list)
108   (labellers nil :type list)
109   (prefilters nil :type list))
110
111 (defvar *disassem-function-cache* (make-function-cache))
112 (declaim (type function-cache *disassem-function-cache*))
113 \f
114 ;;;; A DCHUNK contains the bits we look at to decode an
115 ;;;; instruction.
116 ;;;; I tried to keep this abstract so that if using integers > the machine
117 ;;;; word size conses too much, it can be changed to use bit-vectors or
118 ;;;; something.
119 ;;;;
120 ;;;; KLUDGE: It's not clear that using bit-vectors would be any more efficient.
121 ;;;; Perhaps the abstraction could go away. -- WHN 19991124
122
123 #!-sb-fluid
124 (declaim (inline dchunk-or dchunk-and dchunk-clear dchunk-not
125                  dchunk-make-mask dchunk-make-field
126                  sap-ref-dchunk
127                  dchunk-extract
128                  dchunk=
129                  dchunk-count-bits))
130
131 (defconstant dchunk-bits 32)
132
133 (deftype dchunk ()
134   `(unsigned-byte ,dchunk-bits))
135 (deftype dchunk-index ()
136   `(integer 0 ,dchunk-bits))
137
138 (defconstant dchunk-zero 0)
139 (defconstant dchunk-one #xFFFFFFFF)
140
141 (defun dchunk-extract (from pos)
142   (declare (type dchunk from))
143   (the dchunk (ldb pos (the dchunk from))))
144
145 (defmacro dchunk-copy (x)
146   `(the dchunk ,x))
147
148 (defun dchunk-or (to from)
149   (declare (type dchunk to from))
150   (the dchunk (logior to from)))
151 (defun dchunk-and (to from)
152   (declare (type dchunk to from))
153   (the dchunk (logand to from)))
154 (defun dchunk-clear (to from)
155   (declare (type dchunk to from))
156   (the dchunk (logandc2 to from)))
157 (defun dchunk-not (from)
158   (declare (type dchunk from))
159   (the dchunk (logand dchunk-one (lognot from))))
160
161 (defmacro dchunk-andf (to from)
162   `(setf ,to (dchunk-and ,to ,from)))
163 (defmacro dchunk-orf (to from)
164   `(setf ,to (dchunk-or ,to ,from)))
165 (defmacro dchunk-clearf (to from)
166   `(setf ,to (dchunk-clear ,to ,from)))
167
168 (defun dchunk-make-mask (pos)
169   (the dchunk (mask-field pos -1)))
170 (defun dchunk-make-field (pos value)
171   (the dchunk (dpb value pos 0)))
172
173 (defmacro make-dchunk (value)
174   `(the dchunk ,value))
175
176 (defun sap-ref-dchunk (sap byte-offset byte-order)
177   (declare (type sb!sys:system-area-pointer sap)
178            (type offset byte-offset)
179            (optimize (speed 3) (safety 0)))
180   (the dchunk
181        (if (eq byte-order :big-endian)
182            (+ (ash (sb!sys:sap-ref-8 sap byte-offset) 24)
183               (ash (sb!sys:sap-ref-8 sap (+ 1 byte-offset)) 16)
184               (ash (sb!sys:sap-ref-8 sap (+ 2 byte-offset)) 8)
185               (sb!sys:sap-ref-8 sap (+ 3 byte-offset)))
186            (+ (sb!sys:sap-ref-8 sap byte-offset)
187               (ash (sb!sys:sap-ref-8 sap (+ 1 byte-offset)) 8)
188               (ash (sb!sys:sap-ref-8 sap (+ 2 byte-offset)) 16)
189               (ash (sb!sys:sap-ref-8 sap (+ 3 byte-offset)) 24)))))
190
191 (defun dchunk-corrected-extract (from pos unit-bits byte-order)
192   (declare (type dchunk from))
193   (if (eq byte-order :big-endian)
194       (ldb (byte (byte-size pos)
195                  (+ (byte-position pos) (- dchunk-bits unit-bits)))
196            (the dchunk from))
197       (ldb pos (the dchunk from))))
198
199 (defmacro dchunk-insertf (place pos value)
200   `(setf ,place (the dchunk (dpb ,value ,pos (the dchunk,place)))))
201
202 (defun dchunk= (x y)
203   (declare (type dchunk x y))
204   (= x y))
205 (defmacro dchunk-zerop (x)
206   `(dchunk= ,x dchunk-zero))
207
208 (defun dchunk-strict-superset-p (sup sub)
209   (and (zerop (logandc2 sub sup))
210        (not (zerop (logandc2 sup sub)))))
211
212 (defun dchunk-count-bits (x)
213   (declare (type dchunk x))
214   (logcount x))
215 \f
216 (defstruct (instruction (:conc-name inst-)
217                         (:constructor
218                          make-instruction (name
219                                            format-name
220                                            print-name
221                                            length
222                                            mask id
223                                            printer
224                                            labeller prefilter control)))
225   (name nil :type (or symbol string))
226   (format-name nil :type (or symbol string))
227
228   (mask dchunk-zero :type dchunk)       ; bits in the inst that are constant
229   (id dchunk-zero :type dchunk)         ; value of those constant bits
230
231   (length 0 :type length)               ; in bytes
232
233   (print-name nil :type symbol)
234
235   ;; disassembly functions
236   (prefilter nil :type (or null function))
237   (labeller nil :type (or null function))
238   (printer (required-argument) :type (or null function))
239   (control nil :type (or null function))
240
241   ;; instructions that are the same as this instruction but with more
242   ;; constraints
243   (specializers nil :type list))
244 (def!method print-object ((inst instruction) stream)
245   (print-unreadable-object (inst stream :type t :identity t)
246     (format stream "~A(~A)" (inst-name inst) (inst-format-name inst))))
247 \f
248 ;;;; an instruction space holds all known machine instructions in a form that
249 ;;;; can be easily searched
250
251 (defstruct (inst-space (:conc-name ispace-))
252   (valid-mask dchunk-zero :type dchunk) ; applies to *children*
253   (choices nil :type list))
254 (def!method print-object ((ispace inst-space) stream)
255   (print-unreadable-object (ispace stream :type t :identity t)))
256
257 (defstruct (inst-space-choice (:conc-name ischoice-))
258   (common-id dchunk-zero :type dchunk)  ; applies to *parent's* mask
259   (subspace (required-argument) :type (or inst-space instruction)))
260 \f
261 ;;;; These are the kind of values we can compute for an argument, and
262 ;;;; how to compute them. The :checker functions make sure that a given
263 ;;;; argument is compatible with another argument for a given use.
264
265 (defvar *arg-form-kinds* nil)
266
267 (defstruct arg-form-kind
268   (names nil :type list)
269   (producer (required-argument) :type function)
270   (checker (required-argument) :type function))
271
272 (defun arg-form-kind-or-lose (kind)
273   (or (getf *arg-form-kinds* kind)
274       (pd-error "unknown arg-form kind ~S" kind)))
275
276 (defun find-arg-form-producer (kind)
277   (arg-form-kind-producer (arg-form-kind-or-lose kind)))
278 (defun find-arg-form-checker (kind)
279   (arg-form-kind-checker (arg-form-kind-or-lose kind)))
280
281 (defun canonicalize-arg-form-kind (kind)
282   (car (arg-form-kind-names (arg-form-kind-or-lose kind))))
283 \f
284 ;;;; only used during compilation of the instructions for a backend
285 ;;;;
286 ;;;; FIXME: If only used then, isn't there some way we could do
287 ;;;; EVAL-WHEN tricks to keep this stuff from appearing in the target
288 ;;;; system?
289
290 (defvar *disassem-inst-formats* (make-hash-table))
291 (defvar *disassem-arg-types* nil)
292 (defvar *disassem-function-cache* (make-function-cache))
293
294 (defstruct (argument (:conc-name arg-))
295   (name nil :type symbol)
296   (fields nil :type list)
297
298   (value nil :type (or list integer))
299   (sign-extend-p nil :type (member t nil))
300
301   ;; position in a vector of prefiltered values
302   (position 0 :type fixnum)
303
304   ;; functions to use
305   (printer nil)
306   (prefilter nil)
307   (use-label nil))
308
309 (defstruct (instruction-format (:conc-name format-))
310   (name nil)
311   (args nil :type list)
312
313   (length 0 :type length)               ; in bytes
314
315   (default-printer nil :type list))
316 \f
317 ;;; A FUNSTATE holds the state of any arguments used in a disassembly
318 ;;; function.
319 (defstruct (funstate (:conc-name funstate-) (:constructor %make-funstate))
320   (args nil :type list)
321   (arg-temps nil :type list))           ; See below.
322
323 (defun make-funstate (args)
324   ;; give the args a position
325   (let ((i 0))
326     (dolist (arg args)
327       (setf (arg-position arg) i)
328       (incf i)))
329   (%make-funstate :args args))
330
331 (defun funstate-compatible-p (funstate args)
332   (every #'(lambda (this-arg-temps)
333              (let* ((old-arg (car this-arg-temps))
334                     (new-arg (find (arg-name old-arg) args :key #'arg-name)))
335                (and new-arg
336                     (every #'(lambda (this-kind-temps)
337                                (funcall (find-arg-form-checker
338                                          (car this-kind-temps))
339                                         new-arg
340                                         old-arg))
341                            (cdr this-arg-temps)))))
342          (funstate-arg-temps funstate)))
343
344 (defun arg-or-lose (name funstate)
345   (let ((arg (find name (funstate-args funstate) :key #'arg-name)))
346     (when (null arg)
347       (pd-error "unknown argument ~S" name))
348     arg))
349 \f
350 ;;;; Since we can't include some values in compiled output as they are
351 ;;;; (notably functions), we sometimes use a VALSRC structure to keep track of
352 ;;;; the source from which they were derived.
353
354 (defstruct (valsrc (:constructor %make-valsrc))
355   (value nil)
356   (source nil))
357
358 (defun make-valsrc (value source)
359   (cond ((equal value source)
360          source)
361         ((and (listp value) (eq (car value) 'function))
362          value)
363         (t
364          (%make-valsrc :value value :source source))))
365
366 ;;; machinery to provide more meaningful error messages during compilation
367 (defvar *current-instruction-flavor* nil)
368 (defun pd-error (fmt &rest args)
369   (if *current-instruction-flavor*
370       (error "~@<in printer-definition for ~S(~S): ~3I~:_~?~:>"
371              (car *current-instruction-flavor*)
372              (cdr *current-instruction-flavor*)
373              fmt args)
374       (apply #'error fmt args)))
375
376 ;;; FIXME:
377 ;;;  1. This should become a utility in SB!IMPL.
378 ;;;  2. Arrays are self-evaluating too.
379 (defun self-evaluating-p (x)
380   (typecase x
381     (null t)
382     (keyword t)
383     (symbol (eq x t))
384     (cons nil)
385     (t t)))
386
387 (defun maybe-quote (evalp form)
388   (if (or evalp (self-evaluating-p form)) form `',form))
389
390 ;;; detect things that obviously don't need wrapping, like variable-refs and
391 ;;; #'function
392 (defun doesnt-need-wrapping-p (form)
393   (or (symbolp form)
394       (and (listp form)
395            (eq (car form) 'function)
396            (symbolp (cadr form)))))
397
398 (defun make-wrapper (form arg-name funargs prefix)
399   (if (and (listp form)
400            (eq (car form) 'function))
401       ;; a function def
402       (let ((wrapper-name (symbolicate prefix "-" arg-name "-WRAPPER"))
403             (wrapper-args (make-gensym-list (length funargs))))
404         (values `#',wrapper-name
405                 `(defun ,wrapper-name ,wrapper-args
406                    (funcall ,form ,@wrapper-args))))
407       ;; something else
408       (let ((wrapper-name (symbolicate "*" prefix "-" arg-name "-WRAPPER*")))
409         (values wrapper-name `(defparameter ,wrapper-name ,form)))))
410
411 (defun filter-overrides (overrides evalp)
412   (mapcar #'(lambda (override)
413               (list* (car override) (cadr override)
414                      (munge-fun-refs (cddr override) evalp)))
415           overrides))
416
417 (defparameter *arg-function-params*
418   '((:printer . (value stream dstate))
419     (:use-label . (value dstate))
420     (:prefilter . (value dstate))))
421
422 (defun munge-fun-refs (params evalp &optional wrap-defs-p (prefix ""))
423   (let ((params (copy-list params)))
424     (do ((tail params (cdr tail))
425          (wrapper-defs nil))
426         ((null tail)
427          (values params (nreverse wrapper-defs)))
428       (let ((fun-arg (assoc (car tail) *arg-function-params*)))
429         (when fun-arg
430           (let* ((fun-form (cadr tail))
431                  (quoted-fun-form `',fun-form))
432             (when (and wrap-defs-p (not (doesnt-need-wrapping-p fun-form)))
433               (multiple-value-bind (access-form wrapper-def-form)
434                   (make-wrapper fun-form (car fun-arg) (cdr fun-arg) prefix)
435                 (setf quoted-fun-form `',access-form)
436                 (push wrapper-def-form wrapper-defs)))
437             (if evalp
438                 (setf (cadr tail)
439                       `(make-valsrc ,fun-form ,quoted-fun-form))
440                 (setf (cadr tail)
441                       fun-form))))))))
442
443 (defun gen-args-def-form (overrides format-form &optional (evalp t))
444   (let ((args-var (gensym)))
445     `(let ((,args-var (copy-list (format-args ,format-form))))
446        ,@(mapcar #'(lambda (override)
447                      (update-args-form args-var
448                                        `',(car override)
449                                        (and (cdr override)
450                                             (cons :value (cdr override)))
451                                        evalp))
452                  overrides)
453        ,args-var)))
454
455 (defun gen-printer-def-forms-def-form (name def &optional (evalp t))
456   (destructuring-bind
457       (format-name
458        (&rest field-defs)
459        &optional (printer-form :default)
460        &key ((:print-name print-name-form) `',name) control)
461       def
462     (let ((format-var (gensym))
463           (field-defs (filter-overrides field-defs evalp)))
464       `(let* ((*current-instruction-flavor* ',(cons name format-name))
465               (,format-var (format-or-lose ',format-name))
466               (args ,(gen-args-def-form field-defs format-var evalp))
467               (funcache *disassem-function-cache*))
468          ;; FIXME: This should be SPEED 0 but can't be until we support
469          ;; byte compilation of components of the SBCL system.
470          ;;(declare (optimize (speed 0) (safety 0) (debug 0)))
471          (multiple-value-bind (printer-fun printer-defun)
472              (find-printer-fun ,(if (eq printer-form :default)
473                                      `(format-default-printer ,format-var)
474                                      (maybe-quote evalp printer-form))
475                                args funcache)
476            (multiple-value-bind (labeller-fun labeller-defun)
477                (find-labeller-fun args funcache)
478              (multiple-value-bind (prefilter-fun prefilter-defun)
479                  (find-prefilter-fun args funcache)
480                (multiple-value-bind (mask id)
481                    (compute-mask-id args)
482                  (values
483                   `(make-instruction ',',name
484                                      ',',format-name
485                                      ,',print-name-form
486                                      ,(format-length ,format-var)
487                                      ,mask
488                                      ,id
489                                      ,(and printer-fun `#',printer-fun)
490                                      ,(and labeller-fun `#',labeller-fun)
491                                      ,(and prefilter-fun `#',prefilter-fun)
492                                      ,',control)
493                   `(progn
494                      ,@(and printer-defun (list printer-defun))
495                      ,@(and labeller-defun (list labeller-defun))
496                      ,@(and prefilter-defun (list prefilter-defun))))
497                  ))))))))
498
499 (defun update-args-form (var name-form descrip-forms evalp
500                              &optional format-length-form)
501   `(setf ,var
502          ,(if evalp
503               `(modify-or-add-arg ,name-form
504                                   ,var
505                                   *disassem-arg-types*
506                                   ,@(and format-length-form
507                                          `(:format-length
508                                             ,format-length-form))
509                                   ,@descrip-forms)
510               `(apply #'modify-or-add-arg
511                       ,name-form
512                       ,var
513                       *disassem-arg-types*
514                       ,@(and format-length-form
515                              `(:format-length ,format-length-form))
516                       ',descrip-forms))))
517
518 (defun format-or-lose (name)
519   (or (gethash name *disassem-inst-formats*)
520       (pd-error "unknown instruction format ~S" name)))
521
522 ;;; FIXME: needed only at build-the-system time, not in running system
523 (defmacro define-instruction-format (header &rest fields)
524   #!+sb-doc
525   "DEFINE-INSTRUCTION-FORMAT (Name Length {Format-Key Value}*) Arg-Def*
526   Define an instruction format NAME for the disassembler's use. LENGTH is
527   the length of the format in bits.
528   Possible FORMAT-KEYs:
529
530   :INCLUDE other-format-name
531       Inherit all arguments and properties of the given format. Any
532       arguments defined in the current format definition will either modify
533       the copy of an existing argument (keeping in the same order with
534       respect to when pre-filter's are called), if it has the same name as
535       one, or be added to the end.
536   :DEFAULT-PRINTER printer-list
537       Use the given PRINTER-LIST as a format to print any instructions of
538       this format when they don't specify something else.
539
540   Each ARG-DEF defines one argument in the format, and is of the form
541     (Arg-Name {Arg-Key Value}*)
542
543   Possible ARG-KEYs (the values are evaluated unless otherwise specified):
544
545   :FIELDS byte-spec-list
546       The argument takes values from these fields in the instruction. If
547       the list is of length one, then the corresponding value is supplied by
548       itself; otherwise it is a list of the values. The list may be NIL.
549   :FIELD byte-spec
550       The same as :FIELDS (list byte-spec).
551
552   :VALUE value
553       If the argument only has one field, this is the value it should have,
554       otherwise it's a list of the values of the individual fields. This can
555       be overridden in an instruction-definition or a format definition
556       including this one by specifying another, or NIL to indicate that it's
557       variable.
558
559   :SIGN-EXTEND boolean
560       If non-NIL, the raw value of this argument is sign-extended,
561       immediately after being extracted from the instruction (before any
562       prefilters are run, for instance). If the argument has multiple
563       fields, they are all sign-extended.
564
565   :TYPE arg-type-name
566       Inherit any properties of the given argument-type.
567
568   :PREFILTER function
569       A function which is called (along with all other prefilters, in the
570       order that their arguments appear in the instruction-format) before
571       any printing is done, to filter the raw value. Any uses of READ-SUFFIX
572       must be done inside a prefilter.
573
574   :PRINTER function-string-or-vector
575       A function, string, or vector which is used to print this argument.
576
577   :USE-LABEL
578       If non-NIL, the value of this argument is used as an address, and if
579       that address occurs inside the disassembled code, it is replaced by a
580       label. If this is a function, it is called to filter the value."
581   (gen-format-def-form header fields))
582
583 ;;; FIXME: needed only at build-the-system time, not in running system
584 (defun gen-format-def-form (header descrips &optional (evalp t))
585   #!+sb-doc
586   "Generate a form to define an instruction format. See
587   DEFINE-INSTRUCTION-FORMAT for more info."
588   (when (atom header)
589     (setf header (list header)))
590   (destructuring-bind (name length &key default-printer include) header
591     (let ((args-var (gensym))
592           (length-var (gensym))
593           (all-wrapper-defs nil)
594           (arg-count 0))
595       (collect ((arg-def-forms))
596         (dolist (descrip descrips)
597           (let ((name (pop descrip)))
598             (multiple-value-bind (descrip wrapper-defs)
599                 (munge-fun-refs
600                  descrip evalp t (format nil "~:@(~A~)-~D" name arg-count))
601               (arg-def-forms
602                (update-args-form args-var `',name descrip evalp length-var))
603               (setf all-wrapper-defs
604                     (nconc wrapper-defs all-wrapper-defs)))
605             (incf arg-count)))
606         `(progn
607            ,@all-wrapper-defs
608            (eval-when (:compile-toplevel :execute)
609              (let ((,length-var ,length)
610                    (,args-var
611                     ,(and include
612                           `(copy-list
613                             (format-args
614                              (format-or-lose ,include))))))
615                ,@(arg-def-forms)
616                (setf (gethash ',name *disassem-inst-formats*)
617                      (make-instruction-format
618                       :name ',name
619                       :length (bits-to-bytes ,length-var)
620                       :default-printer ,(maybe-quote evalp default-printer)
621                       :args ,args-var))
622                (eval
623                 `(progn
624                    ,@(mapcar #'(lambda (arg)
625                                  (when (arg-fields arg)
626                                    (gen-arg-access-macro-def-form
627                                     arg ,args-var ',name)))
628                              ,args-var))))))))))
629
630 ;;; FIXME: probably needed only at build-the-system time, not in
631 ;;; final target system
632 (defun modify-or-add-arg (arg-name
633                           args
634                           type-table
635                           &key
636                           (value nil value-p)
637                           (type nil type-p)
638                           (prefilter nil prefilter-p)
639                           (printer nil printer-p)
640                           (sign-extend nil sign-extend-p)
641                           (use-label nil use-label-p)
642                           (field nil field-p)
643                           (fields nil fields-p)
644                           format-length)
645   (let* ((arg-pos (position arg-name args :key #'arg-name))
646          (arg
647           (if (null arg-pos)
648               (let ((arg (make-argument :name arg-name)))
649                 (if (null args)
650                     (setf args (list arg))
651                     (push arg (cdr (last args))))
652                 arg)
653               (setf (nth arg-pos args) (copy-argument (nth arg-pos args))))))
654     (when (and field-p (not fields-p))
655       (setf fields (list field))
656       (setf fields-p t))
657     (when type-p
658       (set-arg-from-type arg type type-table))
659     (when value-p
660       (setf (arg-value arg) value))
661     (when prefilter-p
662       (setf (arg-prefilter arg) prefilter))
663     (when sign-extend-p
664       (setf (arg-sign-extend-p arg) sign-extend))
665     (when printer-p
666       (setf (arg-printer arg) printer))
667     (when use-label-p
668       (setf (arg-use-label arg) use-label))
669     (when fields-p
670       (when (null format-length)
671         (error
672          "~@<in arg ~S: ~3I~:_~
673           can't specify fields except using DEFINE-INSTRUCTION-FORMAT~:>"
674          arg-name))
675       (setf (arg-fields arg)
676             (mapcar #'(lambda (bytespec)
677                         (when (> (+ (byte-position bytespec)
678                                     (byte-size bytespec))
679                                  format-length)
680                           (error "~@<in arg ~S: ~3I~:_~
681                                      The field ~S doesn't fit in an ~
682                                      instruction-format ~D bits wide.~:>"
683                                  arg-name
684                                  bytespec
685                                  format-length))
686                         (correct-dchunk-bytespec-for-endianness
687                          bytespec
688                          format-length
689                          sb!c:*backend-byte-order*))
690                     fields)))
691     args))
692
693 (defun gen-arg-access-macro-def-form (arg args format-name)
694   (let* ((funstate (make-funstate args))
695          (arg-val-form (arg-value-form arg funstate :adjusted))
696          (bindings (make-arg-temp-bindings funstate)))
697     `(sb!xc:defmacro ,(symbolicate format-name "-" (arg-name arg))
698          (chunk dstate)
699        `(let ((chunk ,chunk) (dstate ,dstate))
700           (declare (ignorable chunk dstate))
701           (flet ((local-filtered-value (offset)
702                    (declare (type filtered-value-index offset))
703                    (aref (dstate-filtered-values dstate) offset))
704                  (local-extract (bytespec)
705                    (dchunk-extract chunk bytespec)))
706             (declare (ignorable #'local-filtered-value #'local-extract)
707                      (inline local-filtered-value local-extract))
708             (let* ,',bindings
709               ,',arg-val-form))))))
710
711 (defun arg-value-form (arg funstate
712                        &optional
713                        (kind :final)
714                        (allow-multiple-p (not (eq kind :numeric))))
715   (let ((forms (gen-arg-forms arg kind funstate)))
716     (when (and (not allow-multiple-p)
717                (listp forms)
718                (/= (length forms) 1))
719       (pd-error "~S must not have multiple values." arg))
720     (maybe-listify forms)))
721
722 (defun correct-dchunk-bytespec-for-endianness (bs unit-bits byte-order)
723   (if (eq byte-order :big-endian)
724       (byte (byte-size bs) (+ (byte-position bs) (- dchunk-bits unit-bits)))
725       bs))
726
727 (defun make-arg-temp-bindings (funstate)
728   ;; (Everything is in reverse order, so we just use PUSH, which
729   ;; results in everything being in the right order at the end.)
730   (let ((bindings nil))
731     (dolist (ats (funstate-arg-temps funstate))
732       (dolist (atk (cdr ats))
733         (cond ((null (cadr atk)))
734               ((atom (cadr atk))
735                (push `(,(cadr atk) ,(cddr atk)) bindings))
736               (t
737                (mapc #'(lambda (var form)
738                          (push `(,var ,form) bindings))
739                      (cadr atk)
740                      (cddr atk))))))
741     bindings))
742
743 (defun gen-arg-forms (arg kind funstate)
744   (multiple-value-bind (vars forms)
745       (get-arg-temp arg kind funstate)
746     (when (null forms)
747       (multiple-value-bind (new-forms single-value-p)
748           (funcall (find-arg-form-producer kind) arg funstate)
749         (setq forms new-forms)
750         (cond ((or single-value-p (atom forms))
751                (unless (symbolp forms)
752                  (setq vars (gensym))))
753               ((every #'symbolp forms)
754                ;; just use the same as the forms
755                (setq vars nil))
756               (t
757                (setq vars (make-gensym-list (length forms)))))
758         (set-arg-temps vars forms arg kind funstate)))
759     (or vars forms)))
760
761 (defun maybe-listify (forms)
762   (cond ((atom forms)
763          forms)
764         ((/= (length forms) 1)
765          `(list ,@forms))
766         (t
767          (car forms))))
768 \f
769 (defun set-arg-from-type (arg type-name table)
770   (let ((type-arg (find type-name table :key #'arg-name)))
771     (when (null type-arg)
772       (pd-error "unknown argument type: ~S" type-name))
773     (setf (arg-printer arg) (arg-printer type-arg))
774     (setf (arg-prefilter arg) (arg-prefilter type-arg))
775     (setf (arg-sign-extend-p arg) (arg-sign-extend-p type-arg))
776     (setf (arg-use-label arg) (arg-use-label type-arg))))
777
778 (defun get-arg-temp (arg kind funstate)
779   (let ((this-arg-temps (assoc arg (funstate-arg-temps funstate))))
780     (if this-arg-temps
781         (let ((this-kind-temps
782                (assoc (canonicalize-arg-form-kind kind)
783                       (cdr this-arg-temps))))
784           (values (cadr this-kind-temps) (cddr this-kind-temps)))
785         (values nil nil))))
786
787 (defun set-arg-temps (vars forms arg kind funstate)
788   (let ((this-arg-temps
789          (or (assoc arg (funstate-arg-temps funstate))
790              (car (push (cons arg nil) (funstate-arg-temps funstate)))))
791         (kind (canonicalize-arg-form-kind kind)))
792     (let ((this-kind-temps
793            (or (assoc kind (cdr this-arg-temps))
794                (car (push (cons kind nil) (cdr this-arg-temps))))))
795       (setf (cdr this-kind-temps) (cons vars forms)))))
796 \f
797 (defmacro define-argument-type (name &rest args)
798   #!+sb-doc
799   "DEFINE-ARGUMENT-TYPE Name {Key Value}*
800   Define a disassembler argument type NAME (which can then be referenced in
801   another argument definition using the :TYPE keyword argument). Keyword
802   arguments are:
803
804   :SIGN-EXTEND boolean
805       If non-NIL, the raw value of this argument is sign-extended.
806
807   :TYPE arg-type-name
808       Inherit any properties of given argument-type.
809
810   :PREFILTER function
811       A function which is called (along with all other prefilters, in the
812       order that their arguments appear in the instruction- format) before
813       any printing is done, to filter the raw value. Any uses of READ-SUFFIX
814       must be done inside a prefilter.
815
816   :PRINTER function-string-or-vector
817       A function, string, or vector which is used to print an argument of
818       this type.
819
820   :USE-LABEL
821       If non-NIL, the value of an argument of this type is used as an
822       address, and if that address occurs inside the disassembled code, it is
823       replaced by a label. If this is a function, it is called to filter the
824       value."
825   (gen-arg-type-def-form name args))
826
827 (defun gen-arg-type-def-form (name args &optional (evalp t))
828   #!+sb-doc
829   "Generate a form to define a disassembler argument type. See
830   DEFINE-ARGUMENT-TYPE for more info."
831   (multiple-value-bind (args wrapper-defs)
832       (munge-fun-refs args evalp t name)
833     `(progn
834        ,@wrapper-defs
835        (eval-when (:compile-toplevel :execute)
836          ,(update-args-form '*disassem-arg-types* `',name args evalp))
837        ',name)))
838 \f
839 (defmacro def-arg-form-kind ((&rest names) &rest inits)
840   `(let ((kind (make-arg-form-kind :names ',names ,@inits)))
841      ,@(mapcar #'(lambda (name)
842                    `(setf (getf *arg-form-kinds* ',name) kind))
843                names)))
844
845 (def-arg-form-kind (:raw)
846   :producer #'(lambda (arg funstate)
847                 (declare (ignore funstate))
848                 (mapcar #'(lambda (bytespec)
849                             `(the (unsigned-byte ,(byte-size bytespec))
850                                   (local-extract ',bytespec)))
851                         (arg-fields arg)))
852   :checker #'(lambda (new-arg old-arg)
853                (equal (arg-fields new-arg)
854                       (arg-fields old-arg))))
855
856 (def-arg-form-kind (:sign-extended :unfiltered)
857   :producer #'(lambda (arg funstate)
858                 (let ((raw-forms (gen-arg-forms arg :raw funstate)))
859                   (if (and (arg-sign-extend-p arg) (listp raw-forms))
860                       (mapcar #'(lambda (form field)
861                                   `(the (signed-byte ,(byte-size field))
862                                         (sign-extend ,form
863                                                      ,(byte-size field))))
864                               raw-forms
865                               (arg-fields arg))
866                       raw-forms)))
867   :checker #'(lambda (new-arg old-arg)
868                (equal (arg-sign-extend-p new-arg)
869                       (arg-sign-extend-p old-arg))))
870
871 (defun valsrc-equal (f1 f2)
872   (if (null f1)
873       (null f2)
874       (equal (value-or-source f1)
875              (value-or-source f2))))
876
877 (def-arg-form-kind (:filtering)
878   :producer #'(lambda (arg funstate)
879                 (let ((sign-extended-forms
880                        (gen-arg-forms arg :sign-extended funstate))
881                       (pf (arg-prefilter arg)))
882                   (if pf
883                       (values
884                        `(local-filter ,(maybe-listify sign-extended-forms)
885                                       ,(source-form pf))
886                        t)
887                       (values sign-extended-forms nil))))
888   :checker #'(lambda (new-arg old-arg)
889                (valsrc-equal (arg-prefilter new-arg) (arg-prefilter old-arg))))
890
891 (def-arg-form-kind (:filtered :unadjusted)
892   :producer #'(lambda (arg funstate)
893                 (let ((pf (arg-prefilter arg)))
894                   (if pf
895                       (values `(local-filtered-value ,(arg-position arg)) t)
896                       (gen-arg-forms arg :sign-extended funstate))))
897   :checker #'(lambda (new-arg old-arg)
898                (let ((pf1 (arg-prefilter new-arg))
899                      (pf2 (arg-prefilter old-arg)))
900                  (if (null pf1)
901                      (null pf2)
902                      (= (arg-position new-arg)
903                         (arg-position old-arg))))))
904
905 (def-arg-form-kind (:adjusted :numeric :unlabelled)
906   :producer #'(lambda (arg funstate)
907                 (let ((filtered-forms (gen-arg-forms arg :filtered funstate))
908                       (use-label (arg-use-label arg)))
909                   (if (and use-label (not (eq use-label t)))
910                       (list
911                        `(adjust-label ,(maybe-listify filtered-forms)
912                                       ,(source-form use-label)))
913                       filtered-forms)))
914   :checker #'(lambda (new-arg old-arg)
915                (valsrc-equal (arg-use-label new-arg) (arg-use-label old-arg))))
916
917 (def-arg-form-kind (:labelled :final)
918   :producer #'(lambda (arg funstate)
919                 (let ((adjusted-forms
920                        (gen-arg-forms arg :adjusted funstate))
921                       (use-label (arg-use-label arg)))
922                   (if use-label
923                       (let ((form (maybe-listify adjusted-forms)))
924                         (if (and (not (eq use-label t))
925                                  (not (atom adjusted-forms))
926                                  (/= (Length adjusted-forms) 1))
927                             (pd-error
928                              "cannot label a multiple-field argument ~
929                               unless using a function: ~S" arg)
930                             `((lookup-label ,form))))
931                       adjusted-forms)))
932   :checker #'(lambda (new-arg old-arg)
933                (let ((lf1 (arg-use-label new-arg))
934                      (lf2 (arg-use-label old-arg)))
935                  (if (null lf1) (null lf2) t))))
936
937 ;;; This is a bogus kind that's just used to ensure that printers are
938 ;;; compatible...
939 (def-arg-form-kind (:printed)
940   :producer #'(lambda (&rest noise)
941                 (declare (ignore noise))
942                 (pd-error "bogus! can't use the :printed value of an arg!"))
943   :checker #'(lambda (new-arg old-arg)
944                (valsrc-equal (arg-printer new-arg) (arg-printer old-arg))))
945
946 (defun remember-printer-use (arg funstate)
947   (set-arg-temps nil nil arg :printed funstate))
948 \f
949 ;;; Returns a version of THING suitable for including in an evaluable
950 ;;; position in some form.
951 (defun source-form (thing)
952   (cond ((valsrc-p thing)
953          (valsrc-source thing))
954         ((functionp thing)
955          (pd-error
956           "can't dump functions, so function ref form must be quoted: ~S"
957           thing))
958         ((self-evaluating-p thing)
959          thing)
960         ((eq (car thing) 'function)
961          thing)
962         (t
963          `',thing)))
964
965 ;;; Returns anything but a VALSRC structure.
966 (defun value-or-source (thing)
967   (if (valsrc-p thing)
968       (valsrc-value thing)
969       thing))
970 \f
971 (defstruct (cached-function (:conc-name cached-fun-))
972   (funstate nil :type (or null funstate))
973   (constraint nil :type list)
974   (name nil :type (or null symbol)))
975
976 (defun find-cached-function (cached-funs args constraint)
977   (dolist (cached-fun cached-funs nil)
978     (let ((funstate (cached-fun-funstate cached-fun)))
979       (when (and (equal constraint (cached-fun-constraint cached-fun))
980                  (or (null funstate)
981                      (funstate-compatible-p funstate args)))
982         (return cached-fun)))))
983
984 (defmacro with-cached-function ((name-var funstate-var cache cache-slot
985                                           args &key constraint prefix)
986                                 &body defun-maker-forms)
987   (let ((cache-var (gensym))
988         (constraint-var (gensym)))
989     `(let* ((,constraint-var ,constraint)
990             (,cache-var (find-cached-function (,cache-slot ,cache)
991                                               ,args ,constraint-var)))
992        (cond (,cache-var
993               #+nil
994               (Format t "~&; Using cached function ~S~%"
995                       (cached-fun-name ,cache-var))
996               (values (cached-fun-name ,cache-var) nil))
997              (t
998               (let* ((,name-var (gensym ,prefix))
999                      (,funstate-var (make-funstate ,args))
1000                      (,cache-var
1001                       (make-cached-function :name ,name-var
1002                                             :funstate ,funstate-var
1003                                             :constraint ,constraint-var)))
1004                 #+nil
1005                 (format t "~&; Making new function ~S~%"
1006                         (cached-fun-name ,cache-var))
1007                 (values ,name-var
1008                         `(progn
1009                            ,(progn ,@defun-maker-forms)
1010                            (eval-when (:compile-toplevel :execute)
1011                              (push ,,cache-var
1012                                    (,',cache-slot ',,cache)))))))))))
1013 \f
1014 (defun find-printer-fun (printer-source args cache)
1015   (if (null printer-source)
1016       (values nil nil)
1017       (let ((printer-source (preprocess-printer printer-source args)))
1018         (with-cached-function
1019             (name funstate cache function-cache-printers args
1020                   :constraint printer-source
1021                   :prefix "PRINTER")
1022           (make-printer-defun printer-source funstate name)))))
1023 \f
1024 ;;;; Note that these things are compiled byte compiled to save space.
1025
1026 (defun make-printer-defun (source funstate function-name)
1027   (let ((printer-form (compile-printer-list source funstate))
1028         (bindings (make-arg-temp-bindings funstate)))
1029     `(defun ,function-name (chunk inst stream dstate)
1030        (declare (type dchunk chunk)
1031                 (type instruction inst)
1032                 (type stream stream)
1033                 (type disassem-state dstate)
1034                 ;; FIXME: This should be SPEED 0 but can't be until we support
1035                 ;; byte compilation of components of the SBCL system.
1036                 #+nil (optimize (speed 0) (safety 0) (debug 0)))
1037        (macrolet ((local-format-arg (arg fmt)
1038                     `(funcall (formatter ,fmt) stream ,arg)))
1039          (flet ((local-tab-to-arg-column ()
1040                   (tab (dstate-argument-column dstate) stream))
1041                 (local-print-name ()
1042                   (princ (inst-print-name inst) stream))
1043                 (local-write-char (ch)
1044                   (write-char ch stream))
1045                 (local-princ (thing)
1046                   (princ thing stream))
1047                 (local-princ16 (thing)
1048                   (princ16 thing stream))
1049                 (local-call-arg-printer (arg printer)
1050                   (funcall printer arg stream dstate))
1051                 (local-call-global-printer (fun)
1052                   (funcall fun chunk inst stream dstate))
1053                 (local-filtered-value (offset)
1054                   (declare (type filtered-value-index offset))
1055                   (aref (dstate-filtered-values dstate) offset))
1056                 (local-extract (bytespec)
1057                   (dchunk-extract chunk bytespec))
1058                 (lookup-label (lab)
1059                   (or (gethash lab (dstate-label-hash dstate))
1060                       lab))
1061                 (adjust-label (val adjust-fun)
1062                   (funcall adjust-fun val dstate)))
1063            (declare (ignorable #'local-tab-to-arg-column
1064                                #'local-print-name
1065                                #'local-princ #'local-princ16
1066                                #'local-write-char
1067                                #'local-call-arg-printer
1068                                #'local-call-global-printer
1069                                #'local-extract
1070                                #'local-filtered-value
1071                                #'lookup-label #'adjust-label)
1072                     (inline local-tab-to-arg-column
1073                             local-princ local-princ16
1074                             local-call-arg-printer local-call-global-printer
1075                             local-filtered-value local-extract
1076                             lookup-label adjust-label))
1077            (let* ,bindings
1078              ,@printer-form))))))
1079 \f
1080 (defun preprocess-test (subj form args)
1081   (multiple-value-bind (subj test)
1082       (if (and (consp form) (symbolp (car form)) (not (keywordp (car form))))
1083           (values (car form) (cdr form))
1084           (values subj form))
1085     (let ((key (if (consp test) (car test) test))
1086           (body (if (consp test) (cdr test) nil)))
1087       (case key
1088         (:constant
1089          (if (null body)
1090              ;; If no supplied constant values, just any constant is ok, just
1091              ;; see whether there's some constant value in the arg.
1092              (not
1093               (null
1094                (arg-value
1095                 (or (find subj args :key #'arg-name)
1096                     (pd-error "unknown argument ~S" subj)))))
1097              ;; Otherwise, defer to run-time.
1098              form))
1099         ((:or :and :not)
1100          (sharing-cons
1101           form
1102           subj
1103           (sharing-cons
1104            test
1105            key
1106            (sharing-mapcar
1107             #'(lambda (sub-test)
1108                 (preprocess-test subj sub-test args))
1109             body))))
1110         (t form)))))
1111
1112 (defun preprocess-conditionals (printer args)
1113   (if (atom printer)
1114       printer
1115       (case (car printer)
1116         (:unless
1117          (preprocess-conditionals
1118           `(:cond ((:not ,(nth 1 printer)) ,@(nthcdr 2 printer)))
1119           args))
1120         (:when
1121          (preprocess-conditionals `(:cond (,(cdr printer))) args))
1122         (:if
1123          (preprocess-conditionals
1124           `(:cond (,(nth 1 printer) ,(nth 2 printer))
1125                   (t ,(nth 3 printer)))
1126           args))
1127         (:cond
1128          (sharing-cons
1129           printer
1130           :cond
1131           (sharing-mapcar
1132            #'(lambda (clause)
1133                (let ((filtered-body
1134                       (sharing-mapcar
1135                        #'(lambda (sub-printer)
1136                            (preprocess-conditionals sub-printer args))
1137                        (cdr clause))))
1138                  (sharing-cons
1139                   clause
1140                   (preprocess-test (find-first-field-name filtered-body)
1141                                    (car clause)
1142                                    args)
1143                   filtered-body)))
1144            (cdr printer))))
1145         (quote printer)
1146         (t
1147          (sharing-mapcar
1148           #'(lambda (sub-printer)
1149               (preprocess-conditionals sub-printer args))
1150           printer)))))
1151
1152 (defun preprocess-printer (printer args)
1153   #!+sb-doc
1154   "Returns a version of the disassembly-template PRINTER with compile-time
1155   tests (e.g. :constant without a value), and any :CHOOSE operators resolved
1156   properly for the args ARGS. (:CHOOSE Sub*) simply returns the first Sub in
1157   which every field reference refers to a valid arg."
1158   (preprocess-conditionals (preprocess-chooses printer args) args))
1159 \f
1160 (defun find-first-field-name (tree)
1161   #!+sb-doc
1162   "Returns the first non-keyword symbol in a depth-first search of TREE."
1163   (cond ((null tree)
1164          nil)
1165         ((and (symbolp tree) (not (keywordp tree)))
1166          tree)
1167         ((atom tree)
1168          nil)
1169         ((eq (car tree) 'quote)
1170          nil)
1171         (t
1172          (or (find-first-field-name (car tree))
1173              (find-first-field-name (cdr tree))))))
1174
1175 (defun preprocess-chooses (printer args)
1176   (cond ((atom printer)
1177          printer)
1178         ((eq (car printer) :choose)
1179          (pick-printer-choice (cdr printer) args))
1180         (t
1181          (sharing-mapcar #'(lambda (sub) (preprocess-chooses sub args))
1182                          printer))))
1183 \f
1184 ;;;; some simple functions that help avoid consing when we're just
1185 ;;;; recursively filtering things that usually don't change
1186
1187 (defun sharing-cons (old-cons car cdr)
1188   #!+sb-doc
1189   "If CAR is eq to the car of OLD-CONS and CDR is eq to the CDR, return
1190   OLD-CONS, otherwise return (cons CAR CDR)."
1191   (if (and (eq car (car old-cons)) (eq cdr (cdr old-cons)))
1192       old-cons
1193       (cons car cdr)))
1194
1195 (defun sharing-mapcar (fun list)
1196   #!+sb-doc
1197   "A simple (one list arg) mapcar that avoids consing up a new list
1198   as long as the results of calling FUN on the elements of LIST are
1199   eq to the original."
1200   (and list
1201        (sharing-cons list
1202                      (funcall fun (car list))
1203                      (sharing-mapcar fun (cdr list)))))
1204 \f
1205 (defun all-arg-refs-relevant-p (printer args)
1206   (cond ((or (null printer) (keywordp printer) (eq printer t))
1207          t)
1208         ((symbolp printer)
1209          (find printer args :key #'arg-name))
1210         ((listp printer)
1211          (every #'(lambda (x) (all-arg-refs-relevant-p x args))
1212                 printer))
1213         (t t)))
1214
1215 (defun pick-printer-choice (choices args)
1216   (dolist (choice choices
1217            (pd-error "no suitable choice found in ~S" choices))
1218     (when (all-arg-refs-relevant-p choice args)
1219       (return choice))))
1220
1221 (defun compile-printer-list (sources funstate)
1222   (unless (null sources)
1223     ;; Coalesce adjacent symbols/strings, and convert to strings if possible,
1224     ;; since they require less consing to write.
1225     (do ((el (car sources) (car sources))
1226          (names nil (cons (strip-quote el) names)))
1227         ((not (string-or-qsym-p el))
1228          (when names
1229            ;; concatenate adjacent strings and symbols
1230            (let ((string
1231                   (apply #'concatenate
1232                          'string
1233                          (mapcar #'string (nreverse names)))))
1234              (push (if (some #'alpha-char-p string)
1235                        `',(make-symbol string) ; Preserve casifying output.
1236                        string)
1237                    sources))))
1238       (pop sources))
1239     (cons (compile-printer-body (car sources) funstate)
1240           (compile-printer-list (cdr sources) funstate))))
1241
1242 (defun compile-printer-body (source funstate)
1243   (cond ((null source)
1244          nil)
1245         ((eq source :name)
1246          `(local-print-name))
1247         ((eq source :tab)
1248          `(local-tab-to-arg-column))
1249         ((keywordp source)
1250          (pd-error "unknown printer element: ~S" source))
1251         ((symbolp source)
1252          (compile-print source funstate))
1253         ((atom source)
1254          `(local-princ ',source))
1255         ((eq (car source) :using)
1256          (unless (or (stringp (cadr source))
1257                      (and (listp (cadr source))
1258                           (eq (caadr source) 'function)))
1259            (pd-error "The first arg to :USING must be a string or #'function."))
1260          (compile-print (caddr source) funstate
1261                         (cons (eval (cadr source)) (cadr source))))
1262         ((eq (car source) :plus-integer)
1263          ;; prints the given field proceed with a + or a -
1264          (let ((form
1265                 (arg-value-form (arg-or-lose (cadr source) funstate)
1266                                 funstate
1267                                 :numeric)))
1268            `(progn
1269               (when (>= ,form 0)
1270                 (local-write-char #\+))
1271               (local-princ ,form))))
1272         ((eq (car source) 'quote)
1273          `(local-princ ,source))
1274         ((eq (car source) 'function)
1275          `(local-call-global-printer ,source))
1276         ((eq (car source) :cond)
1277          `(cond ,@(mapcar #'(lambda (clause)
1278                               `(,(compile-test (find-first-field-name
1279                                                 (cdr clause))
1280                                                (car clause)
1281                                                funstate)
1282                                 ,@(compile-printer-list (cdr clause)
1283                                                         funstate)))
1284                           (cdr source))))
1285         ;; :IF, :UNLESS, and :WHEN are replaced by :COND during preprocessing
1286         (t
1287          `(progn ,@(compile-printer-list source funstate)))))
1288
1289 (defun compile-print (arg-name funstate &optional printer)
1290   (let* ((arg (arg-or-lose arg-name funstate))
1291          (printer (or printer (arg-printer arg)))
1292          (printer-val (value-or-source printer))
1293          (printer-src (source-form printer)))
1294     (remember-printer-use arg funstate)
1295     (cond ((stringp printer-val)
1296            `(local-format-arg ,(arg-value-form arg funstate) ,printer-val))
1297           ((vectorp printer-val)
1298            `(local-princ
1299              (aref ,printer-src
1300                    ,(arg-value-form arg funstate :numeric))))
1301           ((or (functionp printer-val)
1302                (and (consp printer-val) (eq (car printer-val) 'function)))
1303            `(local-call-arg-printer ,(arg-value-form arg funstate)
1304                                     ,printer-src))
1305           ((or (null printer-val) (eq printer-val t))
1306            `(,(if (arg-use-label arg) 'local-princ16 'local-princ)
1307              ,(arg-value-form arg funstate)))
1308           (t
1309            (pd-error "illegal printer: ~S" printer-src)))))
1310
1311 (defun string-or-qsym-p (thing)
1312   (or (stringp thing)
1313       (and (consp thing)
1314            (eq (car thing) 'quote)
1315            (or (stringp (cadr thing))
1316                (symbolp (cadr thing))))))
1317
1318 (defun strip-quote (thing)
1319   (if (and (consp thing) (eq (car thing) 'quote))
1320       (cadr thing)
1321       thing))
1322 \f
1323 (defun compare-fields-form (val-form-1 val-form-2)
1324   (flet ((listify-fields (fields)
1325            (cond ((symbolp fields) fields)
1326                  ((every #'constantp fields) `',fields)
1327                  (t `(list ,@fields)))))
1328     (cond ((or (symbolp val-form-1) (symbolp val-form-2))
1329            `(equal ,(listify-fields val-form-1)
1330                    ,(listify-fields val-form-2)))
1331           (t
1332            `(and ,@(mapcar #'(lambda (v1 v2) `(= ,v1 ,v2))
1333                            val-form-1 val-form-2))))))
1334
1335 (defun compile-test (subj test funstate)
1336   (when (and (consp test) (symbolp (car test)) (not (keywordp (car test))))
1337     (setf subj (car test)
1338           test (cdr test)))
1339   (let ((key (if (consp test) (car test) test))
1340         (body (if (consp test) (cdr test) nil)))
1341     (cond ((null key)
1342            nil)
1343           ((eq key t)
1344            t)
1345           ((eq key :constant)
1346            (let* ((arg (arg-or-lose subj funstate))
1347                   (fields (arg-fields arg))
1348                   (consts body))
1349              (when (not (= (length fields) (length consts)))
1350                (pd-error "The number of constants doesn't match number of ~
1351                           fields in: (~S :constant~{ ~S~})"
1352                          subj body))
1353              (compare-fields-form (gen-arg-forms arg :numeric funstate)
1354                                   consts)))
1355           ((eq key :positive)
1356            `(> ,(arg-value-form (arg-or-lose subj funstate) funstate :numeric)
1357                0))
1358           ((eq key :negative)
1359            `(< ,(arg-value-form (arg-or-lose subj funstate) funstate :numeric)
1360                0))
1361           ((eq key :same-as)
1362            (let ((arg1 (arg-or-lose subj funstate))
1363                  (arg2 (arg-or-lose (car body) funstate)))
1364              (unless (and (= (length (arg-fields arg1))
1365                              (length (arg-fields arg2)))
1366                           (every #'(lambda (bs1 bs2)
1367                                      (= (byte-size bs1) (byte-size bs2)))
1368                                  (arg-fields arg1)
1369                                  (arg-fields arg2)))
1370                (pd-error "can't compare differently sized fields: ~
1371                           (~S :same-as ~S)" subj (car body)))
1372              (compare-fields-form (gen-arg-forms arg1 :numeric funstate)
1373                                   (gen-arg-forms arg2 :numeric funstate))))
1374           ((eq key :or)
1375            `(or ,@(mapcar #'(lambda (sub) (compile-test subj sub funstate))
1376                           body)))
1377           ((eq key :and)
1378            `(and ,@(mapcar #'(lambda (sub) (compile-test subj sub funstate))
1379                            body)))
1380           ((eq key :not)
1381            `(not ,(compile-test subj (car body) funstate)))
1382           ((and (consp key) (null body))
1383            (compile-test subj key funstate))
1384           (t
1385            (pd-error "bogus test-form: ~S" test)))))
1386 \f
1387 (defun find-labeller-fun (args cache)
1388   (let ((labelled-fields
1389          (mapcar #'arg-name (remove-if-not #'arg-use-label args))))
1390     (if (null labelled-fields)
1391         (values nil nil)
1392         (with-cached-function
1393             (name funstate cache function-cache-labellers args
1394              :prefix "LABELLER"
1395              :constraint labelled-fields)
1396           (let ((labels-form 'labels))
1397             (dolist (arg args)
1398               (when (arg-use-label arg)
1399                 (setf labels-form
1400                       `(let ((labels ,labels-form)
1401                              (addr
1402                               ,(arg-value-form arg funstate :adjusted nil)))
1403                          (if (assoc addr labels :test #'eq)
1404                              labels
1405                              (cons (cons addr nil) labels))))))
1406             `(defun ,name (chunk labels dstate)
1407                (declare (type list labels)
1408                         (type dchunk chunk)
1409                         (type disassem-state dstate)
1410                         ;; FIXME: This should be SPEED 0 but can't be
1411                         ;; until we support byte compilation of
1412                         ;; components of the SBCL system.
1413                         #+nil (optimize (speed 0) (safety 0) (debug 0)))
1414                (flet ((local-filtered-value (offset)
1415                         (declare (type filtered-value-index offset))
1416                         (aref (dstate-filtered-values dstate) offset))
1417                       (local-extract (bytespec)
1418                         (dchunk-extract chunk bytespec))
1419                       (adjust-label (val adjust-fun)
1420                         (funcall adjust-fun val dstate)))
1421                  (declare (ignorable #'local-filtered-value #'local-extract
1422                                      #'adjust-label)
1423                           (inline local-filtered-value local-extract
1424                                   adjust-label))
1425                  (let* ,(make-arg-temp-bindings funstate)
1426                    ,labels-form))))))))
1427
1428 (defun find-prefilter-fun (args cache)
1429   (let ((filtered-args
1430          (mapcar #'arg-name (remove-if-not #'arg-prefilter args))))
1431     (if (null filtered-args)
1432         (values nil nil)
1433         (with-cached-function
1434             (name funstate cache function-cache-prefilters args
1435              :prefix "PREFILTER"
1436              :constraint filtered-args)
1437           (collect ((forms))
1438             (dolist (arg args)
1439               (let ((pf (arg-prefilter arg)))
1440                 (when pf
1441                   (forms
1442                    `(setf (local-filtered-value ,(arg-position arg))
1443                           ,(maybe-listify
1444                             (gen-arg-forms arg :filtering funstate)))))
1445                 ))
1446             `(defun ,name (chunk dstate)
1447                (declare (type dchunk chunk)
1448                         (type disassem-state dstate)
1449                         ;; FIXME: This should be SPEED 0 but can't be
1450                         ;; until we support byte compilation of
1451                         ;; components of the SBCL system.
1452                         #+nil (optimize (speed 0) (safety 0) (debug 0)))
1453                (flet (((setf local-filtered-value) (value offset)
1454                        (declare (type filtered-value-index offset))
1455                        (setf (aref (dstate-filtered-values dstate) offset)
1456                              value))
1457                       (local-filter (value filter)
1458                                     (funcall filter value dstate))
1459                       (local-extract (bytespec)
1460                                      (dchunk-extract chunk bytespec)))
1461                 (declare (ignorable #'local-filter #'local-extract)
1462                          (inline (setf local-filtered-value)
1463                                  local-filter local-extract))
1464                 ;; Use them for side-effects only.
1465                 (let* ,(make-arg-temp-bindings funstate)
1466                   ,@(forms)))))))))
1467 \f
1468 (defun compute-mask-id (args)
1469   (let ((mask dchunk-zero)
1470         (id dchunk-zero))
1471     (dolist (arg args (values mask id))
1472       (let ((av (arg-value arg)))
1473         (when av
1474           (do ((fields (arg-fields arg) (cdr fields))
1475                (values (if (atom av) (list av) av) (cdr values)))
1476               ((null fields))
1477             (let ((field-mask (dchunk-make-mask (car fields))))
1478               (when (/= (dchunk-and mask field-mask) dchunk-zero)
1479                 (pd-error "The field ~S in arg ~S overlaps some other field."
1480                           (car fields)
1481                           (arg-name arg)))
1482               (dchunk-insertf id (car fields) (car values))
1483               (dchunk-orf mask field-mask))))))))
1484
1485 (defun install-inst-flavors (name flavors)
1486   (setf (gethash name *disassem-insts*)
1487         flavors))
1488 \f
1489 #!-sb-fluid (declaim (inline bytes-to-bits))
1490 (declaim (maybe-inline sign-extend aligned-p align tab tab0))
1491
1492 (defun bytes-to-bits (bytes)
1493   (declare (type length bytes))
1494   (* bytes sb!vm:byte-bits))
1495
1496 (defun bits-to-bytes (bits)
1497   (declare (type length bits))
1498   (multiple-value-bind (bytes rbits)
1499       (truncate bits sb!vm:byte-bits)
1500     (when (not (zerop rbits))
1501       (error "~D bits is not a byte-multiple." bits))
1502     bytes))
1503
1504 (defun sign-extend (int size)
1505   (declare (type integer int)
1506            (type (integer 0 128) size))
1507   (if (logbitp (1- size) int)
1508       (dpb int (byte size 0) -1)
1509       int))
1510
1511 (defun aligned-p (address size)
1512   #!+sb-doc
1513   "Returns non-NIL if ADDRESS is aligned on a SIZE byte boundary."
1514   (declare (type address address)
1515            (type alignment size))
1516   (zerop (logand (1- size) address)))
1517
1518 (defun align (address size)
1519   #!+sb-doc
1520   "Return ADDRESS aligned *upward* to a SIZE byte boundary."
1521   (declare (type address address)
1522            (type alignment size))
1523   (logandc1 (1- size) (+ (1- size) address)))
1524
1525 (defun tab (column stream)
1526   (funcall (formatter "~V,1t") stream column)
1527   nil)
1528 (defun tab0 (column stream)
1529   (funcall (formatter "~V,0t") stream column)
1530   nil)
1531
1532 (defun princ16 (value stream)
1533   (write value :stream stream :radix t :base 16 :escape nil))
1534 \f
1535 (defun read-signed-suffix (length dstate)
1536   (declare (type (member 8 16 32) length)
1537            (type disassem-state dstate)
1538            (optimize (speed 3) (safety 0)))
1539   (sign-extend (read-suffix length dstate) length))
1540
1541 ;;; KLUDGE: The associated run-time machinery for this is in
1542 ;;; target-disassem.lisp (much later). This is here just to make sure
1543 ;;; it's defined before it's used. -- WHN ca. 19990701
1544 (defmacro dstate-get-prop (dstate name)
1545   #!+sb-doc
1546   "Get the value of the property called NAME in DSTATE. Also setf'able."
1547   `(getf (dstate-properties ,dstate) ,name))