805761f5cd5825581ed5385d23c51754f6dc5d63
[sbcl.git] / src / compiler / meta-vmdef.lisp
1 ;;;; This file contains the implementation-independent facilities used
2 ;;;; for defining the compiler's interface to the VM in a given
3 ;;;; implementation that are needed at meta-compile time. They are
4 ;;;; separated out from vmdef.lisp so that they can be compiled and
5 ;;;; loaded without trashing the running compiler.
6 ;;;;
7 ;;;; FIXME: The "trashing the running [CMU CL] compiler" motivation no
8 ;;;; longer makes sense in SBCL, since we can cross-compile cleanly.
9
10 ;;;; This software is part of the SBCL system. See the README file for
11 ;;;; more information.
12 ;;;;
13 ;;;; This software is derived from the CMU CL system, which was
14 ;;;; written at Carnegie Mellon University and released into the
15 ;;;; public domain. The software is in the public domain and is
16 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
17 ;;;; files for more information.
18
19 (in-package "SB!C")
20 \f
21 ;;;; storage class and storage base definition
22
23 ;;; Define a storage base having the specified NAME. KIND may be :FINITE,
24 ;;; :UNBOUNDED or :NON-PACKED. The following keywords are legal:
25 ;;;    :SIZE specifies the number of locations in a :FINITE SB or
26 ;;;          the initial size of an :UNBOUNDED SB.
27 ;;;
28 ;;; We enter the basic structure at meta-compile time, and then fill
29 ;;; in the missing slots at load time.
30 (defmacro define-storage-base (name kind &key size)
31
32   (declare (type symbol name))
33   (declare (type (member :finite :unbounded :non-packed) kind))
34
35   ;; SIZE is either mandatory or forbidden.
36   (ecase kind
37     (:non-packed
38      (when size
39        (error "A size specification is meaningless in a ~S SB." kind)))
40     ((:finite :unbounded)
41      (unless size (error "Size is not specified in a ~S SB." kind))
42      (aver (typep size 'unsigned-byte))))
43
44   (let ((res (if (eq kind :non-packed)
45                  (make-sb :name name :kind kind)
46                  (make-finite-sb :name name :kind kind :size size))))
47     `(progn
48        (eval-when (:compile-toplevel :load-toplevel :execute)
49          (/show0 "about to SETF GETHASH META-SB-NAMES in DEFINE-STORAGE-BASE")
50          (setf (gethash ',name *backend-meta-sb-names*)
51                ',res))
52        (/show0 "about to SETF GETHASH SB-NAMES in DEFINE-STORAGE-BASE")
53        ,(if (eq kind :non-packed)
54             `(setf (gethash ',name *backend-sb-names*)
55                    (copy-sb ',res))
56             `(let ((res (copy-finite-sb ',res)))
57                (/show0 "not :NON-PACKED, i.e. hairy case")
58                (setf (finite-sb-always-live res)
59                      (make-array ',size
60                                  :initial-element
61                                  #-(or sb-xc sb-xc-host) #*
62                                  ;; The cross-compiler isn't very good
63                                  ;; at dumping specialized arrays; we
64                                  ;; work around that by postponing
65                                  ;; generation of the specialized
66                                  ;; array 'til runtime.
67                                  #+(or sb-xc sb-xc-host)
68                                  (make-array 0 :element-type 'bit)))
69                (/show0 "doing second SETF")
70                (setf (finite-sb-conflicts res)
71                      (make-array ',size :initial-element '#()))
72                (/show0 "doing third SETF")
73                (setf (finite-sb-live-tns res)
74                      (make-array ',size :initial-element nil))
75                (/show0 "doing fourth and final SETF")
76                (setf (gethash ',name *backend-sb-names*)
77                      res)))
78
79        (/show0 "about to put SB onto/into SB-LIST")
80        (setf *backend-sb-list*
81              (cons (sb-or-lose ',name)
82                    (remove ',name *backend-sb-list* :key #'sb-name)))
83        (/show0 "finished with DEFINE-STORAGE-BASE expansion")
84        ',name)))
85
86 ;;; Define a storage class NAME that uses the named Storage-Base.
87 ;;; NUMBER is a small, non-negative integer that is used as an alias.
88 ;;; The following keywords are defined:
89 ;;;
90 ;;; :ELEMENT-SIZE Size
91 ;;;   The size of objects in this SC in whatever units the SB uses.
92 ;;;   This defaults to 1.
93 ;;;
94 ;;; :ALIGNMENT Size
95 ;;;   The alignment restrictions for this SC. TNs will only be
96 ;;;   allocated at offsets that are an even multiple of this number.
97 ;;;   This defaults to 1.
98 ;;;
99 ;;; :LOCATIONS (Location*)
100 ;;;   If the SB is :FINITE, then this is a list of the offsets within
101 ;;;   the SB that are in this SC.
102 ;;;
103 ;;; :RESERVE-LOCATIONS (Location*)
104 ;;;   A subset of the Locations that the register allocator should try to
105 ;;;   reserve for operand loading (instead of to hold variable values.)
106 ;;;
107 ;;; :SAVE-P {T | NIL}
108 ;;;   If T, then values stored in this SC must be saved in one of the
109 ;;;   non-save-p :ALTERNATE-SCs across calls.
110 ;;;
111 ;;; :ALTERNATE-SCS (SC*)
112 ;;;   Indicates other SCs that can be used to hold values from this SC across
113 ;;;   calls or when storage in this SC is exhausted. The SCs should be
114 ;;;   specified in order of decreasing \"goodness\". There must be at least
115 ;;;   one SC in an unbounded SB, unless this SC is only used for restricted or
116 ;;;   wired TNs.
117 ;;;
118 ;;; :CONSTANT-SCS (SC*)
119 ;;;   A list of the names of all the constant SCs that can be loaded into this
120 ;;;   SC by a move function.
121 (defmacro define-storage-class (name number sb-name &key (element-size '1)
122                                      (alignment '1) locations reserve-locations
123                                      save-p alternate-scs constant-scs)
124   (declare (type symbol name))
125   (declare (type sc-number number))
126   (declare (type symbol sb-name))
127   (declare (type list locations reserve-locations alternate-scs constant-scs))
128   (declare (type boolean save-p))
129   (unless (= (logcount alignment) 1)
130     (error "alignment not a power of two: ~W" alignment))
131
132   (let ((sb (meta-sb-or-lose sb-name)))
133     (if (eq (sb-kind sb) :finite)
134         (let ((size (sb-size sb))
135               (element-size (eval element-size)))
136           (declare (type unsigned-byte element-size))
137           (dolist (el locations)
138             (declare (type unsigned-byte el))
139             (unless (<= 1 (+ el element-size) size)
140               (error "SC element ~W out of bounds for ~S" el sb))))
141         (when locations
142           (error ":LOCATIONS is meaningless in a ~S SB." (sb-kind sb))))
143
144     (unless (subsetp reserve-locations locations)
145       (error "RESERVE-LOCATIONS not a subset of LOCATIONS."))
146
147     (when (and (or alternate-scs constant-scs)
148                (eq (sb-kind sb) :non-packed))
149       (error
150        "It's meaningless to specify alternate or constant SCs in a ~S SB."
151        (sb-kind sb))))
152
153   (let ((nstack-p
154          (if (or (eq sb-name 'non-descriptor-stack)
155                  (find 'non-descriptor-stack
156                        (mapcar #'meta-sc-or-lose alternate-scs)
157                        :key (lambda (x)
158                               (sb-name (sc-sb x)))))
159              t nil)))
160     `(progn
161        (eval-when (:compile-toplevel :load-toplevel :execute)
162          (let ((res (make-sc :name ',name :number ',number
163                              :sb (meta-sb-or-lose ',sb-name)
164                              :element-size ,element-size
165                              :alignment ,alignment
166                              :locations ',locations
167                              :reserve-locations ',reserve-locations
168                              :save-p ',save-p
169                              :number-stack-p ,nstack-p
170                              :alternate-scs (mapcar #'meta-sc-or-lose
171                                                     ',alternate-scs)
172                              :constant-scs (mapcar #'meta-sc-or-lose
173                                                    ',constant-scs))))
174            (setf (gethash ',name *backend-meta-sc-names*) res)
175            (setf (svref *backend-meta-sc-numbers* ',number) res)
176            (setf (svref (sc-load-costs res) ',number) 0)))
177
178        (let ((old (svref *backend-sc-numbers* ',number)))
179          (when (and old (not (eq (sc-name old) ',name)))
180            (warn "redefining SC number ~W from ~S to ~S" ',number
181                  (sc-name old) ',name)))
182
183        (setf (svref *backend-sc-numbers* ',number)
184              (meta-sc-or-lose ',name))
185        (setf (gethash ',name *backend-sc-names*)
186              (meta-sc-or-lose ',name))
187        (setf (sc-sb (sc-or-lose ',name)) (sb-or-lose ',sb-name))
188        ',name)))
189 \f
190 ;;;; move/coerce definition
191
192 ;;; Given a list of pairs of lists of SCs (as given to DEFINE-MOVE-VOP,
193 ;;; etc.), bind TO-SC and FROM-SC to all the combinations.
194 (defmacro do-sc-pairs ((from-sc-var to-sc-var scs) &body body)
195   `(do ((froms ,scs (cddr froms))
196         (tos (cdr ,scs) (cddr tos)))
197        ((null froms))
198      (dolist (from (car froms))
199        (let ((,from-sc-var (meta-sc-or-lose from)))
200          (dolist (to (car tos))
201            (let ((,to-sc-var (meta-sc-or-lose to)))
202              ,@body))))))
203
204 ;;; Define the function NAME and note it as the function used for
205 ;;; moving operands from the From-SCs to the To-SCs. Cost is the cost
206 ;;; of this move operation. The function is called with three
207 ;;; arguments: the VOP (for context), and the source and destination
208 ;;; TNs. An ASSEMBLE form is wrapped around the body. All uses of
209 ;;; DEFINE-MOVE-FUN should be compiled before any uses of
210 ;;; DEFINE-VOP.
211 (defmacro define-move-fun ((name cost) lambda-list scs &body body)
212   (declare (type index cost))
213   (when (or (oddp (length scs)) (null scs))
214     (error "malformed SCs spec: ~S" scs))
215   `(progn
216      (eval-when (:compile-toplevel :load-toplevel :execute)
217        (do-sc-pairs (from-sc to-sc ',scs)
218          (unless (eq from-sc to-sc)
219            (let ((num (sc-number from-sc)))
220              (setf (svref (sc-move-funs to-sc) num) ',name)
221              (setf (svref (sc-load-costs to-sc) num) ',cost)))))
222
223      (defun ,name ,lambda-list
224        (sb!assem:assemble (*code-segment* ,(first lambda-list))
225          ,@body))))
226
227 (eval-when (:compile-toplevel :load-toplevel :execute)
228   (defparameter *sc-vop-slots*
229     '((:move . sc-move-vops)
230       (:move-arg . sc-move-arg-vops))))
231
232 ;;; Make NAME be the VOP used to move values in the specified FROM-SCs
233 ;;; to the representation of the TO-SCs of each SC pair in SCS.
234 ;;;
235 ;;; If KIND is :MOVE-ARG, then the VOP takes an extra argument,
236 ;;; which is the frame pointer of the frame to move into.
237 ;;;
238 ;;; We record the VOP and costs for all SCs that we can move between
239 ;;; (including implicit loading).
240 (defmacro define-move-vop (name kind &rest scs)
241   (when (or (oddp (length scs)) (null scs))
242     (error "malformed SCs spec: ~S" scs))
243   (let ((accessor (or (cdr (assoc kind *sc-vop-slots*))
244                       (error "unknown kind ~S" kind))))
245     `(progn
246        ,@(when (eq kind :move)
247            `((eval-when (:compile-toplevel :load-toplevel :execute)
248                (do-sc-pairs (from-sc to-sc ',scs)
249                  (compute-move-costs from-sc to-sc
250                                      ,(vop-parse-cost
251                                        (vop-parse-or-lose name)))))))
252
253        (let ((vop (template-or-lose ',name)))
254          (do-sc-pairs (from-sc to-sc ',scs)
255            (dolist (dest-sc (cons to-sc (sc-alternate-scs to-sc)))
256              (let ((vec (,accessor dest-sc)))
257                (let ((scn (sc-number from-sc)))
258                  (setf (svref vec scn)
259                        (adjoin-template vop (svref vec scn))))
260                (dolist (sc (append (sc-alternate-scs from-sc)
261                                    (sc-constant-scs from-sc)))
262                  (let ((scn (sc-number sc)))
263                    (setf (svref vec scn)
264                          (adjoin-template vop (svref vec scn))))))))))))
265 \f
266 ;;;; primitive type definition
267
268 (defun meta-primitive-type-or-lose (name)
269   (the primitive-type
270        (or (gethash name *backend-meta-primitive-type-names*)
271            (error "~S is not a defined primitive type." name))))
272
273 ;;; Define a primitive type NAME. Each SCS entry specifies a storage
274 ;;; class that values of this type may be allocated in. TYPE is the
275 ;;; type descriptor for the Lisp type that is equivalent to this type.
276 (defmacro !def-primitive-type (name scs &key (type name))
277   (declare (type symbol name) (type list scs))
278   (let ((scns (mapcar #'meta-sc-number-or-lose scs)))
279     `(progn
280        (/show0 "doing !DEF-PRIMITIVE-TYPE, NAME=..")
281        (/primitive-print ,(symbol-name name))
282        (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
283          (setf (gethash ',name *backend-meta-primitive-type-names*)
284                (make-primitive-type :name ',name
285                                     :scs ',scns
286                                     :specifier ',type)))
287        ,(once-only ((n-old `(gethash ',name *backend-primitive-type-names*)))
288           `(progn
289              ;; If the PRIMITIVE-TYPE structure already exists, we
290              ;; destructively modify it so that existing references in
291              ;; templates won't be invalidated. FIXME: This should no
292              ;; longer be an issue in SBCL, since we don't try to do
293              ;; serious surgery on ourselves. Probably this should
294              ;; just become an assertion that N-OLD is NIL, so that we
295              ;; don't have to try to maintain the correctness of the
296              ;; never-ordinarily-used clause.
297              (/show0 "in !DEF-PRIMITIVE-TYPE, about to COND")
298              (cond (,n-old
299                     (/show0 "in ,N-OLD clause of COND")
300                     (setf (primitive-type-scs ,n-old) ',scns)
301                     (setf (primitive-type-specifier ,n-old) ',type))
302                    (t
303                     (/show0 "in T clause of COND")
304                     (setf (gethash ',name *backend-primitive-type-names*)
305                           (make-primitive-type :name ',name
306                                                :scs ',scns
307                                                :specifier ',type))))
308              (/show0 "done with !DEF-PRIMITIVE-TYPE")
309              ',name)))))
310
311 ;;; Define NAME to be an alias for RESULT in VOP operand type restrictions.
312 (defmacro !def-primitive-type-alias (name result)
313   ;; Just record the translation.
314   `(eval-when (:compile-toplevel :load-toplevel :execute)
315      (setf (gethash ',name *backend-primitive-type-aliases*) ',result)
316      ',name))
317
318 (defparameter *primitive-type-slot-alist*
319   '((:check . primitive-type-check)))
320
321 ;;;  Primitive-Type-VOP Vop (Kind*) Type*
322 ;;;
323 ;;; Annotate all the specified primitive Types with the named VOP
324 ;;; under each of the specified kinds:
325 ;;;
326 ;;; :CHECK
327 ;;;    A one-argument one-result VOP that moves the argument to the
328 ;;;    result, checking that the value is of this type in the process.
329 (defmacro primitive-type-vop (vop kinds &rest types)
330   (let ((n-vop (gensym))
331         (n-type (gensym)))
332     `(let ((,n-vop (template-or-lose ',vop)))
333        ,@(mapcar
334           (lambda (type)
335             `(let ((,n-type (primitive-type-or-lose ',type)))
336                ,@(mapcar
337                   (lambda (kind)
338                     (let ((slot (or (cdr (assoc kind
339                                                 *primitive-type-slot-alist*))
340                                     (error "unknown kind: ~S" kind))))
341                       `(setf (,slot ,n-type) ,n-vop)))
342                   kinds)))
343           types)
344        nil)))
345
346 ;;; Return true if SC is either one of PTYPE's SC's, or one of those
347 ;;; SC's alternate or constant SCs.
348 (defun meta-sc-allowed-by-primitive-type (sc ptype)
349   (declare (type sc sc) (type primitive-type ptype))
350   (let ((scn (sc-number sc)))
351     (dolist (allowed (primitive-type-scs ptype) nil)
352       (when (eql allowed scn)
353         (return t))
354       (let ((allowed-sc (svref *backend-meta-sc-numbers* allowed)))
355         (when (or (member sc (sc-alternate-scs allowed-sc))
356                   (member sc (sc-constant-scs allowed-sc)))
357           (return t))))))
358 \f
359 ;;;; VOP definition structures
360 ;;;;
361 ;;;; DEFINE-VOP uses some fairly complex data structures at
362 ;;;; meta-compile time, both to hold the results of parsing the
363 ;;;; elaborate syntax and to retain the information so that it can be
364 ;;;; inherited by other VOPs.
365
366 ;;; A VOP-PARSE object holds everything we need to know about a VOP at
367 ;;; meta-compile time.
368 (def!struct (vop-parse
369              (:make-load-form-fun just-dump-it-normally)
370              #-sb-xc-host (:pure t))
371   ;; the name of this VOP
372   (name nil :type symbol)
373   ;; If true, then the name of the VOP we inherit from.
374   (inherits nil :type (or symbol null))
375   ;; lists of OPERAND-PARSE structures describing the arguments,
376   ;; results and temporaries of the VOP
377   (args nil :type list)
378   (results nil :type list)
379   (temps nil :type list)
380   ;; OPERAND-PARSE structures containing information about more args
381   ;; and results. If null, then there there are no more operands of
382   ;; that kind
383   (more-args nil :type (or operand-parse null))
384   (more-results nil :type (or operand-parse null))
385   ;; a list of all the above together
386   (operands nil :type list)
387   ;; names of variables that should be declared IGNORE
388   (ignores () :type list)
389   ;; true if this is a :CONDITIONAL VOP
390   (conditional-p nil)
391   ;; argument and result primitive types. These are pulled out of the
392   ;; operands, since we often want to change them without respecifying
393   ;; the operands.
394   (arg-types :unspecified :type (or (member :unspecified) list))
395   (result-types :unspecified :type (or (member :unspecified) list))
396   ;; the guard expression specified, or NIL if none
397   (guard nil)
398   ;; the cost of and body code for the generator
399   (cost 0 :type unsigned-byte)
400   (body :unspecified :type (or (member :unspecified) list))
401   ;; info for VOP variants. The list of forms to be evaluated to get
402   ;; the variant args for this VOP, and the list of variables to be
403   ;; bound to the variant args.
404   (variant () :type list)
405   (variant-vars () :type list)
406   ;; variables bound to the VOP and Vop-Node when in the generator body
407   (vop-var '.vop. :type symbol)
408   (node-var nil :type (or symbol null))
409   ;; a list of the names of the codegen-info arguments to this VOP
410   (info-args () :type list)
411   ;; an efficiency note associated with this VOP
412   (note nil :type (or string null))
413   ;; a list of the names of the Effects and Affected attributes for
414   ;; this VOP
415   (effects '(any) :type list)
416   (affected '(any) :type list)
417   ;; a list of the names of functions this VOP is a translation of and
418   ;; the policy that allows this translation to be done. :FAST is a
419   ;; safe default, since it isn't a safe policy.
420   (translate () :type list)
421   (ltn-policy :fast :type ltn-policy)
422   ;; stuff used by life analysis
423   (save-p nil :type (member t nil :compute-only :force-to-stack))
424   ;; info about how to emit MOVE-ARG VOPs for the &MORE operand in
425   ;; call/return VOPs
426   (move-args nil :type (member nil :local-call :full-call :known-return)))
427 (defprinter (vop-parse)
428   name
429   (inherits :test inherits)
430   args
431   results
432   temps
433   (more-args :test more-args)
434   (more-results :test more-results)
435   (conditional-p :test conditional-p)
436   ignores
437   arg-types
438   result-types
439   cost
440   body
441   (variant :test variant)
442   (variant-vars :test variant-vars)
443   (info-args :test info-args)
444   (note :test note)
445   effects
446   affected
447   translate
448   ltn-policy
449   (save-p :test save-p)
450   (move-args :test move-args))
451
452 ;;; An OPERAND-PARSE object contains stuff we need to know about an
453 ;;; operand or temporary at meta-compile time. Besides the obvious
454 ;;; stuff, we also store the names of per-operand temporaries here.
455 (def!struct (operand-parse
456              (:make-load-form-fun just-dump-it-normally)
457              #-sb-xc-host (:pure t))
458   ;; name of the operand (which we bind to the TN)
459   (name nil :type symbol)
460   ;; the way this operand is used:
461   (kind (missing-arg)
462         :type (member :argument :result :temporary
463                       :more-argument :more-result))
464   ;; If true, the name of an operand that this operand is targeted to.
465   ;; This is only meaningful in :ARGUMENT and :TEMPORARY operands.
466   (target nil :type (or symbol null))
467   ;; TEMP is a temporary that holds the TN-REF for this operand.
468   (temp (make-operand-parse-temp) :type symbol)
469   ;; the time that this operand is first live and the time at which it
470   ;; becomes dead again. These are TIME-SPECs, as returned by
471   ;; PARSE-TIME-SPEC.
472   born
473   dies
474   ;; a list of the names of the SCs that this operand is allowed into.
475   ;; If false, there is no restriction.
476   (scs nil :type list)
477   ;; Variable that is bound to the load TN allocated for this operand, or to
478   ;; NIL if no load-TN was allocated.
479   (load-tn (make-operand-parse-load-tn) :type symbol)
480   ;; an expression that tests whether to do automatic operand loading
481   (load t)
482   ;; In a wired or restricted temporary this is the SC the TN is to be
483   ;; packed in. Null otherwise.
484   (sc nil :type (or symbol null))
485   ;; If non-null, we are a temp wired to this offset in SC.
486   (offset nil :type (or unsigned-byte null)))
487 (defprinter (operand-parse)
488   name
489   kind
490   (target :test target)
491   born
492   dies
493   (scs :test scs)
494   (load :test load)
495   (sc :test sc)
496   (offset :test offset))
497 \f
498 ;;;; miscellaneous utilities
499
500 ;;; Find the operand or temporary with the specifed Name in the VOP
501 ;;; Parse. If there is no such operand, signal an error. Also error if
502 ;;; the operand kind isn't one of the specified Kinds. If Error-P is
503 ;;; NIL, just return NIL if there is no such operand.
504 (defun find-operand (name parse &optional
505                           (kinds '(:argument :result :temporary))
506                           (error-p t))
507   (declare (symbol name) (type vop-parse parse) (list kinds))
508   (let ((found (find name (vop-parse-operands parse)
509                      :key #'operand-parse-name)))
510     (if found
511         (unless (member (operand-parse-kind found) kinds)
512           (error "Operand ~S isn't one of these kinds: ~S." name kinds))
513         (when error-p
514           (error "~S is not an operand to ~S." name (vop-parse-name parse))))
515     found))
516
517 ;;; Get the VOP-PARSE structure for NAME or die trying. For all
518 ;;; meta-compile time uses, the VOP-PARSE should be used instead of
519 ;;; the VOP-INFO.
520 (defun vop-parse-or-lose (name)
521   (the vop-parse
522        (or (gethash name *backend-parsed-vops*)
523            (error "~S is not the name of a defined VOP." name))))
524
525 ;;; Return a list of LET-forms to parse a TN-REF list into the temps
526 ;;; specified by the operand-parse structures. MORE-OPERAND is the
527 ;;; OPERAND-PARSE describing any more operand, or NIL if none. REFS is
528 ;;; an expression that evaluates into the first TN-REF.
529 (defun access-operands (operands more-operand refs)
530   (declare (list operands))
531   (collect ((res))
532     (let ((prev refs))
533       (dolist (op operands)
534         (let ((n-ref (operand-parse-temp op)))
535           (res `(,n-ref ,prev))
536           (setq prev `(tn-ref-across ,n-ref))))
537
538       (when more-operand
539         (res `(,(operand-parse-name more-operand) ,prev))))
540     (res)))
541
542 ;;; This is used with ACCESS-OPERANDS to prevent warnings for TN-REF
543 ;;; temps not used by some particular function. It returns the name of
544 ;;; the last operand, or NIL if OPERANDS is NIL.
545 (defun ignore-unreferenced-temps (operands)
546   (when operands
547     (operand-parse-temp (car (last operands)))))
548
549 ;;; Grab an arg out of a VOP spec, checking the type and syntax and stuff.
550 (defun vop-spec-arg (spec type &optional (n 1) (last t))
551   (let ((len (length spec)))
552     (when (<= len n)
553       (error "~:R argument missing: ~S" n spec))
554     (when (and last (> len (1+ n)))
555       (error "extra junk at end of ~S" spec))
556     (let ((thing (elt spec n)))
557       (unless (typep thing type)
558         (error "~:R argument is not a ~S: ~S" n type spec))
559       thing)))
560 \f
561 ;;;; time specs
562
563 ;;; Return a time spec describing a time during the evaluation of a
564 ;;; VOP, used to delimit operand and temporary lifetimes. The
565 ;;; representation is a cons whose CAR is the number of the evaluation
566 ;;; phase and the CDR is the sub-phase. The sub-phase is 0 in the
567 ;;; :LOAD and :SAVE phases.
568 (defun parse-time-spec (spec)
569   (let ((dspec (if (atom spec) (list spec 0) spec)))
570     (unless (and (= (length dspec) 2)
571                  (typep (second dspec) 'unsigned-byte))
572       (error "malformed time specifier: ~S" spec))
573
574     (cons (case (first dspec)
575             (:load 0)
576             (:argument 1)
577             (:eval 2)
578             (:result 3)
579             (:save 4)
580             (t
581              (error "unknown phase in time specifier: ~S" spec)))
582           (second dspec))))
583
584 ;;; Return true if the time spec X is the same or later time than Y.
585 (defun time-spec-order (x y)
586   (or (> (car x) (car y))
587       (and (= (car x) (car y))
588            (>= (cdr x) (cdr y)))))
589 \f
590 ;;;; generation of emit functions
591
592 (defun compute-temporaries-description (parse)
593   (let ((temps (vop-parse-temps parse))
594         (element-type '(unsigned-byte 16)))
595     (when temps
596       (let ((results (make-specializable-array
597                       (length temps)
598                       :element-type element-type))
599             (index 0))
600         (dolist (temp temps)
601           (declare (type operand-parse temp))
602           (let ((sc (operand-parse-sc temp))
603                 (offset (operand-parse-offset temp)))
604             (aver sc)
605             (setf (aref results index)
606                   (if offset
607                       (+ (ash offset (1+ sc-bits))
608                          (ash (meta-sc-number-or-lose sc) 1)
609                          1)
610                       (ash (meta-sc-number-or-lose sc) 1))))
611           (incf index))
612         ;; KLUDGE: As in the other COERCEs wrapped around with
613         ;; MAKE-SPECIALIZABLE-ARRAY results in COMPUTE-REF-ORDERING,
614         ;; this coercion could be removed by a sufficiently smart
615         ;; compiler, but I dunno whether Python is that smart. It
616         ;; would be good to check this and help it if it's not smart
617         ;; enough to remove it for itself. However, it's probably not
618         ;; urgent, since the overhead of an extra no-op conversion is
619         ;; unlikely to be large compared to consing and corresponding
620         ;; GC. -- WHN ca. 19990701
621         `(coerce ,results '(specializable-vector ,element-type))))))
622
623 (defun compute-ref-ordering (parse)
624   (let* ((num-args (+ (length (vop-parse-args parse))
625                       (if (vop-parse-more-args parse) 1 0)))
626          (num-results (+ (length (vop-parse-results parse))
627                          (if (vop-parse-more-results parse) 1 0)))
628          (index 0))
629     (collect ((refs) (targets))
630       (dolist (op (vop-parse-operands parse))
631         (when (operand-parse-target op)
632           (unless (member (operand-parse-kind op) '(:argument :temporary))
633             (error "cannot target a ~S operand: ~S" (operand-parse-kind op)
634                    (operand-parse-name op)))
635           (let ((target (find-operand (operand-parse-target op) parse
636                                       '(:temporary :result))))
637             ;; KLUDGE: These formulas must be consistent with those in
638             ;; %EMIT-GENERIC-VOP, and this is currently maintained by
639             ;; hand. -- WHN 2002-01-30, paraphrasing APD
640             (targets (+ (* index max-vop-tn-refs)
641                         (ecase (operand-parse-kind target)
642                           (:result
643                            (+ (position-or-lose target
644                                                 (vop-parse-results parse))
645                               num-args))
646                           (:temporary
647                            (+ (* (position-or-lose target
648                                                    (vop-parse-temps parse))
649                                  2)
650                               1
651                               num-args
652                               num-results)))))))
653         (let ((born (operand-parse-born op))
654               (dies (operand-parse-dies op)))
655           (ecase (operand-parse-kind op)
656             (:argument
657              (refs (cons (cons dies nil) index)))
658             (:more-argument
659              (refs (cons (cons dies nil) index)))
660             (:result
661              (refs (cons (cons born t) index)))
662             (:more-result
663              (refs (cons (cons born t) index)))
664             (:temporary
665              (refs (cons (cons dies nil) index))
666              (incf index)
667              (refs (cons (cons born t) index))))
668           (incf index)))
669       (let* ((sorted (sort (refs)
670                            (lambda (x y)
671                              (let ((x-time (car x))
672                                    (y-time (car y)))
673                                (if (time-spec-order x-time y-time)
674                                    (if (time-spec-order y-time x-time)
675                                        (and (not (cdr x)) (cdr y))
676                                        nil)
677                                    t)))
678                            :key #'car))
679              ;; :REF-ORDERING element type
680              ;;
681              ;; KLUDGE: was (MOD #.MAX-VOP-TN-REFS), which is still right
682              (oe-type '(unsigned-byte 8))
683              ;; :TARGETS element-type
684              ;;
685              ;; KLUDGE: was (MOD #.(* MAX-VOP-TN-REFS 2)), which does
686              ;; not correspond to the definition in
687              ;; src/compiler/vop.lisp.
688              (te-type '(unsigned-byte 16))
689              (ordering (make-specializable-array
690                         (length sorted)
691                         :element-type oe-type)))
692         (let ((index 0))
693           (dolist (ref sorted)
694             (setf (aref ordering index) (cdr ref))
695             (incf index)))
696         `(:num-args ,num-args
697           :num-results ,num-results
698           ;; KLUDGE: The (COERCE .. (SPECIALIZABLE-VECTOR ..)) wrapper
699           ;; here around the result returned by
700           ;; MAKE-SPECIALIZABLE-ARRAY above was of course added to
701           ;; help with cross-compilation. "A sufficiently smart
702           ;; compiler" should be able to optimize all this away in the
703           ;; final target Lisp, leaving a single MAKE-ARRAY with no
704           ;; subsequent coercion. However, I don't know whether Python
705           ;; is that smart. (Can it figure out the return type of
706           ;; MAKE-ARRAY? Does it know that COERCE can be optimized
707           ;; away if the input type is known to be the same as the
708           ;; COERCEd-to type?) At some point it would be good to test
709           ;; to see whether this construct is in fact causing run-time
710           ;; overhead, and fix it if so. (Some declarations of the
711           ;; types returned by MAKE-ARRAY might be enough to fix it.)
712           ;; However, it's probably not urgent to fix this, since it's
713           ;; hard to imagine that any overhead caused by calling
714           ;; COERCE and letting it decide to bail out could be large
715           ;; compared to the cost of consing and GCing the vectors in
716           ;; the first place. -- WHN ca. 19990701
717           :ref-ordering (coerce ',ordering
718                                 '(specializable-vector ,oe-type))
719           ,@(when (targets)
720               `(:targets (coerce ',(targets)
721                                  '(specializable-vector ,te-type)))))))))
722
723 (defun make-emit-function-and-friends (parse)
724   `(:emit-function #'emit-generic-vop
725     :temps ,(compute-temporaries-description parse)
726     ,@(compute-ref-ordering parse)))
727 \f
728 ;;;; generator functions
729
730 ;;; Return an alist that translates from lists of SCs we can load OP
731 ;;; from to the move function used for loading those SCs. We quietly
732 ;;; ignore restrictions to :non-packed (constant) and :unbounded SCs,
733 ;;; since we don't load into those SCs.
734 (defun find-move-funs (op load-p)
735   (collect ((funs))
736     (dolist (sc-name (operand-parse-scs op))
737       (let* ((sc (meta-sc-or-lose sc-name))
738              (scn (sc-number sc))
739              (load-scs (append (when load-p
740                                  (sc-constant-scs sc))
741                                (sc-alternate-scs sc))))
742         (cond
743          (load-scs
744           (dolist (alt load-scs)
745             (unless (member (sc-name alt) (operand-parse-scs op) :test #'eq)
746               (let* ((altn (sc-number alt))
747                      (name (if load-p
748                                (svref (sc-move-funs sc) altn)
749                                (svref (sc-move-funs alt) scn)))
750                      (found (or (assoc alt (funs) :test #'member)
751                                 (rassoc name (funs)))))
752                 (unless name
753                   (error "no move function defined to ~:[save~;load~] SC ~S ~
754                           ~:[to~;from~] from SC ~S"
755                          load-p sc-name load-p (sc-name alt)))
756                 
757                 (cond (found
758                        (unless (eq (cdr found) name)
759                          (error "can't tell whether to ~:[save~;load~]~@
760                                  with ~S or ~S when operand is in SC ~S"
761                                 load-p name (cdr found) (sc-name alt)))
762                        (pushnew alt (car found)))
763                       (t
764                        (funs (cons (list alt) name))))))))
765          ((member (sb-kind (sc-sb sc)) '(:non-packed :unbounded)))
766          (t
767           (error "SC ~S has no alternate~:[~; or constant~] SCs, yet it is~@
768                   mentioned in the restriction for operand ~S"
769                  sc-name load-p (operand-parse-name op))))))
770     (funs)))
771
772 ;;; Return a form to load/save the specified operand when it has a
773 ;;; load TN. For any given SC that we can load from, there must be a
774 ;;; unique load function. If all SCs we can load from have the same
775 ;;; move function, then we just call that when there is a load TN. If
776 ;;; there are multiple possible move functions, then we dispatch off
777 ;;; of the operand TN's type to see which move function to use.
778 (defun call-move-fun (parse op load-p)
779   (let ((funs (find-move-funs op load-p))
780         (load-tn (operand-parse-load-tn op)))
781     (if funs
782         (let* ((tn `(tn-ref-tn ,(operand-parse-temp op)))
783                (n-vop (or (vop-parse-vop-var parse)
784                           (setf (vop-parse-vop-var parse) '.vop.)))
785                (form (if (rest funs)
786                          `(sc-case ,tn
787                             ,@(mapcar (lambda (x)
788                                         `(,(mapcar #'sc-name (car x))
789                                           ,(if load-p
790                                                `(,(cdr x) ,n-vop ,tn
791                                                  ,load-tn)
792                                                `(,(cdr x) ,n-vop ,load-tn
793                                                  ,tn))))
794                                       funs))
795                          (if load-p
796                              `(,(cdr (first funs)) ,n-vop ,tn ,load-tn)
797                              `(,(cdr (first funs)) ,n-vop ,load-tn ,tn)))))
798           (if (eq (operand-parse-load op) t)
799               `(when ,load-tn ,form)
800               `(when (eq ,load-tn ,(operand-parse-name op))
801                  ,form)))
802         `(when ,load-tn
803            (error "load TN allocated, but no move function?~@
804                    VM definition is inconsistent, recompile and try again.")))))
805
806 ;;; Return the TN that we should bind to the operand's var in the
807 ;;; generator body. In general, this involves evaluating the :LOAD-IF
808 ;;; test expression.
809 (defun decide-to-load (parse op)
810   (let ((load (operand-parse-load op))
811         (load-tn (operand-parse-load-tn op))
812         (temp (operand-parse-temp op)))
813     (if (eq load t)
814         `(or ,load-tn (tn-ref-tn ,temp))
815         (collect ((binds)
816                   (ignores))
817           (dolist (x (vop-parse-operands parse))
818             (when (member (operand-parse-kind x) '(:argument :result))
819               (let ((name (operand-parse-name x)))
820                 (binds `(,name (tn-ref-tn ,(operand-parse-temp x))))
821                 (ignores name))))
822           `(if (and ,load-tn
823                     (let ,(binds)
824                       (declare (ignorable ,@(ignores)))
825                       ,load))
826                ,load-tn
827                (tn-ref-tn ,temp))))))
828
829 ;;; Make a lambda that parses the VOP TN-REFS, does automatic operand
830 ;;; loading, and runs the appropriate code generator.
831 (defun make-generator-function (parse)
832   (declare (type vop-parse parse))
833   (let ((n-vop (vop-parse-vop-var parse))
834         (operands (vop-parse-operands parse))
835         (n-info (gensym)) (n-variant (gensym)))
836     (collect ((binds)
837               (loads)
838               (saves))
839       (dolist (op operands)
840         (ecase (operand-parse-kind op)
841           ((:argument :result)
842            (let ((temp (operand-parse-temp op))
843                  (name (operand-parse-name op)))
844              (cond ((and (operand-parse-load op) (operand-parse-scs op))
845                     (binds `(,(operand-parse-load-tn op)
846                              (tn-ref-load-tn ,temp)))
847                     (binds `(,name ,(decide-to-load parse op)))
848                     (if (eq (operand-parse-kind op) :argument)
849                         (loads (call-move-fun parse op t))
850                         (saves (call-move-fun parse op nil))))
851                    (t
852                     (binds `(,name (tn-ref-tn ,temp)))))))
853           (:temporary
854            (binds `(,(operand-parse-name op)
855                     (tn-ref-tn ,(operand-parse-temp op)))))
856           ((:more-argument :more-result))))
857
858       `(lambda (,n-vop)
859          (let* (,@(access-operands (vop-parse-args parse)
860                                    (vop-parse-more-args parse)
861                                    `(vop-args ,n-vop))
862                   ,@(access-operands (vop-parse-results parse)
863                                      (vop-parse-more-results parse)
864                                      `(vop-results ,n-vop))
865                   ,@(access-operands (vop-parse-temps parse) nil
866                                      `(vop-temps ,n-vop))
867                   ,@(when (vop-parse-info-args parse)
868                       `((,n-info (vop-codegen-info ,n-vop))
869                         ,@(mapcar (lambda (x) `(,x (pop ,n-info)))
870                                   (vop-parse-info-args parse))))
871                   ,@(when (vop-parse-variant-vars parse)
872                       `((,n-variant (vop-info-variant (vop-info ,n-vop)))
873                         ,@(mapcar (lambda (x) `(,x (pop ,n-variant)))
874                                   (vop-parse-variant-vars parse))))
875                   ,@(when (vop-parse-node-var parse)
876                       `((,(vop-parse-node-var parse) (vop-node ,n-vop))))
877                   ,@(binds))
878            (declare (ignore ,@(vop-parse-ignores parse)))
879            ,@(loads)
880            (sb!assem:assemble (*code-segment* ,n-vop)
881                               ,@(vop-parse-body parse))
882            ,@(saves))))))
883 \f
884 (defvar *parse-vop-operand-count*)
885 (defun make-operand-parse-temp ()
886   ;; FIXME: potentially causes breakage in contribs from locked
887   ;; packages.
888   (intern (format nil "OPERAND-PARSE-TEMP-~D" *parse-vop-operand-count*)
889           (symbol-package '*parse-vop-operand-count*)))
890 (defun make-operand-parse-load-tn ()
891   (intern (format nil "OPERAND-PARSE-LOAD-TN-~D" *parse-vop-operand-count*)
892           (symbol-package '*parse-vop-operand-count*)))
893
894 ;;; Given a list of operand specifications as given to DEFINE-VOP,
895 ;;; return a list of OPERAND-PARSE structures describing the fixed
896 ;;; operands, and a single OPERAND-PARSE describing any more operand.
897 ;;; If we are inheriting a VOP, we default attributes to the inherited
898 ;;; operand of the same name.
899 (defun !parse-vop-operands (parse specs kind)
900   (declare (list specs)
901            (type (member :argument :result) kind))
902   (let ((num -1)
903         (more nil))
904     (collect ((operands))
905       (dolist (spec specs)
906         (unless (and (consp spec) (symbolp (first spec)) (oddp (length spec)))
907           (error "malformed operand specifier: ~S" spec))
908         (when more
909           (error "The MORE operand isn't the last operand: ~S" specs))
910         (incf *parse-vop-operand-count*)
911         (let* ((name (first spec))
912                (old (if (vop-parse-inherits parse)
913                         (find-operand name
914                                       (vop-parse-or-lose
915                                        (vop-parse-inherits parse))
916                                       (list kind)
917                                       nil)
918                         nil))
919                (res (if old
920                         (make-operand-parse
921                          :name name
922                          :kind kind
923                          :target (operand-parse-target old)
924                          :born (operand-parse-born old)
925                          :dies (operand-parse-dies old)
926                          :scs (operand-parse-scs old)
927                          :load-tn (operand-parse-load-tn old)
928                          :load (operand-parse-load old))
929                         (ecase kind
930                           (:argument
931                            (make-operand-parse
932                             :name (first spec)
933                             :kind :argument
934                             :born (parse-time-spec :load)
935                             :dies (parse-time-spec `(:argument ,(incf num)))))
936                           (:result
937                            (make-operand-parse
938                             :name (first spec)
939                             :kind :result
940                             :born (parse-time-spec `(:result ,(incf num)))
941                             :dies (parse-time-spec :save)))))))
942           (do ((key (rest spec) (cddr key)))
943               ((null key))
944             (let ((value (second key)))
945               (case (first key)
946                 (:scs
947                  (aver (typep value 'list))
948                  (setf (operand-parse-scs res) (remove-duplicates value)))
949                 (:load-tn
950                  (aver (typep value 'symbol))
951                  (setf (operand-parse-load-tn res) value))
952                 (:load-if
953                  (setf (operand-parse-load res) value))
954                 (:more
955                  (aver (typep value 'boolean))
956                  (setf (operand-parse-kind res)
957                        (if (eq kind :argument) :more-argument :more-result))
958                  (setf (operand-parse-load res) nil)
959                  (setq more res))
960                 (:target
961                  (aver (typep value 'symbol))
962                  (setf (operand-parse-target res) value))
963                 (:from
964                  (unless (eq kind :result)
965                    (error "can only specify :FROM in a result: ~S" spec))
966                  (setf (operand-parse-born res) (parse-time-spec value)))
967                 (:to
968                  (unless (eq kind :argument)
969                    (error "can only specify :TO in an argument: ~S" spec))
970                  (setf (operand-parse-dies res) (parse-time-spec value)))
971                 (t
972                  (error "unknown keyword in operand specifier: ~S" spec)))))
973
974           (cond ((not more)
975                  (operands res))
976                 ((operand-parse-target more)
977                  (error "cannot specify :TARGET in a :MORE operand"))
978                 ((operand-parse-load more)
979                  (error "cannot specify :LOAD-IF in a :MORE operand")))))
980       (values (the list (operands)) more))))
981 \f
982 ;;; Parse a temporary specification, putting the OPERAND-PARSE
983 ;;; structures in the PARSE structure.
984 (defun parse-temporary (spec parse)
985   (declare (list spec)
986            (type vop-parse parse))
987   (let ((len (length spec)))
988     (unless (>= len 2)
989       (error "malformed temporary spec: ~S" spec))
990     (unless (listp (second spec))
991       (error "malformed options list: ~S" (second spec)))
992     (unless (evenp (length (second spec)))
993       (error "odd number of arguments in keyword options: ~S" spec))
994     (unless (consp (cddr spec))
995       (warn "temporary spec allocates no temps:~%  ~S" spec))
996     (dolist (name (cddr spec))
997       (unless (symbolp name)
998         (error "bad temporary name: ~S" name))
999       (incf *parse-vop-operand-count*)
1000       (let ((res (make-operand-parse :name name
1001                                      :kind :temporary
1002                                      :born (parse-time-spec :load)
1003                                      :dies (parse-time-spec :save))))
1004         (do ((opt (second spec) (cddr opt)))
1005             ((null opt))
1006           (case (first opt)
1007             (:target
1008              (setf (operand-parse-target res)
1009                    (vop-spec-arg opt 'symbol 1 nil)))
1010             (:sc
1011              (setf (operand-parse-sc res)
1012                    (vop-spec-arg opt 'symbol 1 nil)))
1013             (:offset
1014              (let ((offset (eval (second opt))))
1015                (aver (typep offset 'unsigned-byte))
1016                (setf (operand-parse-offset res) offset)))
1017             (:from
1018              (setf (operand-parse-born res) (parse-time-spec (second opt))))
1019             (:to
1020              (setf (operand-parse-dies res) (parse-time-spec (second opt))))
1021             ;; backward compatibility...
1022             (:scs
1023              (let ((scs (vop-spec-arg opt 'list 1 nil)))
1024                (unless (= (length scs) 1)
1025                  (error "must specify exactly one SC for a temporary"))
1026                (setf (operand-parse-sc res) (first scs))))
1027             (:type)
1028             (t
1029              (error "unknown temporary option: ~S" opt))))
1030
1031         (unless (and (time-spec-order (operand-parse-dies res)
1032                                       (operand-parse-born res))
1033                      (not (time-spec-order (operand-parse-born res)
1034                                            (operand-parse-dies res))))
1035           (error "Temporary lifetime doesn't begin before it ends: ~S" spec))
1036
1037         (unless (operand-parse-sc res)
1038           (error "must specify :SC for all temporaries: ~S" spec))
1039
1040         (setf (vop-parse-temps parse)
1041               (cons res
1042                     (remove name (vop-parse-temps parse)
1043                             :key #'operand-parse-name))))))
1044   (values))
1045 \f
1046 (defun compute-parse-vop-operand-count (parse)
1047   (declare (type vop-parse parse))
1048   (labels ((compute-count-aux (parse)
1049              (declare (type vop-parse parse))
1050              (if (null (vop-parse-inherits parse))
1051                  (length (vop-parse-operands parse))
1052                  (+ (length (vop-parse-operands parse))
1053                     (compute-count-aux 
1054                      (vop-parse-or-lose (vop-parse-inherits parse)))))))
1055     (if (null (vop-parse-inherits parse))
1056         0
1057         (compute-count-aux (vop-parse-or-lose (vop-parse-inherits parse))))))
1058
1059 ;;; the top level parse function: clobber PARSE to represent the
1060 ;;; specified options.
1061 (defun parse-define-vop (parse specs)
1062   (declare (type vop-parse parse) (list specs))
1063   (let ((*parse-vop-operand-count* (compute-parse-vop-operand-count parse)))
1064     (dolist (spec specs)
1065       (unless (consp spec)
1066         (error "malformed option specification: ~S" spec))
1067       (case (first spec)
1068         (:args
1069          (multiple-value-bind (fixed more)
1070              (!parse-vop-operands parse (rest spec) :argument)
1071            (setf (vop-parse-args parse) fixed)
1072            (setf (vop-parse-more-args parse) more)))
1073         (:results
1074          (multiple-value-bind (fixed more)
1075              (!parse-vop-operands parse (rest spec) :result)
1076            (setf (vop-parse-results parse) fixed)
1077            (setf (vop-parse-more-results parse) more))
1078          (setf (vop-parse-conditional-p parse) nil))
1079         (:conditional
1080          (setf (vop-parse-result-types parse) ())
1081          (setf (vop-parse-results parse) ())
1082          (setf (vop-parse-more-results parse) nil)
1083          (setf (vop-parse-conditional-p parse) t))
1084         (:temporary
1085          (parse-temporary spec parse))
1086         (:generator
1087             (setf (vop-parse-cost parse)
1088                   (vop-spec-arg spec 'unsigned-byte 1 nil))
1089           (setf (vop-parse-body parse) (cddr spec)))
1090         (:effects
1091          (setf (vop-parse-effects parse) (rest spec)))
1092         (:affected
1093          (setf (vop-parse-affected parse) (rest spec)))
1094         (:info
1095          (setf (vop-parse-info-args parse) (rest spec)))
1096         (:ignore
1097          (setf (vop-parse-ignores parse) (rest spec)))
1098         (:variant
1099          (setf (vop-parse-variant parse) (rest spec)))
1100         (:variant-vars
1101          (let ((vars (rest spec)))
1102            (setf (vop-parse-variant-vars parse) vars)
1103            (setf (vop-parse-variant parse)
1104                  (make-list (length vars) :initial-element nil))))
1105         (:variant-cost
1106          (setf (vop-parse-cost parse) (vop-spec-arg spec 'unsigned-byte)))
1107         (:vop-var
1108          (setf (vop-parse-vop-var parse) (vop-spec-arg spec 'symbol)))
1109         (:move-args
1110          (setf (vop-parse-move-args parse)
1111                (vop-spec-arg spec '(member nil :local-call :full-call
1112                                     :known-return))))
1113         (:node-var
1114          (setf (vop-parse-node-var parse) (vop-spec-arg spec 'symbol)))
1115         (:note
1116          (setf (vop-parse-note parse) (vop-spec-arg spec '(or string null))))
1117         (:arg-types
1118          (setf (vop-parse-arg-types parse)
1119                (!parse-vop-operand-types (rest spec) t)))
1120         (:result-types
1121          (setf (vop-parse-result-types parse)
1122                (!parse-vop-operand-types (rest spec) nil)))
1123         (:translate
1124          (setf (vop-parse-translate parse) (rest spec)))
1125         (:guard
1126          (setf (vop-parse-guard parse) (vop-spec-arg spec t)))
1127         ;; FIXME: :LTN-POLICY would be a better name for this. It
1128         ;; would probably be good to leave it unchanged for a while,
1129         ;; though, at least until the first port to some other
1130         ;; architecture, since the renaming would be a change to the
1131         ;; interface between
1132         (:policy
1133          (setf (vop-parse-ltn-policy parse)
1134                (vop-spec-arg spec 'ltn-policy)))
1135         (:save-p
1136          (setf (vop-parse-save-p parse)
1137                (vop-spec-arg spec
1138                              '(member t nil :compute-only :force-to-stack))))
1139         (t
1140          (error "unknown option specifier: ~S" (first spec)))))
1141     (values)))
1142 \f
1143 ;;;; making costs and restrictions
1144
1145 ;;; Given an operand, returns two values:
1146 ;;; 1. A SC-vector of the cost for the operand being in that SC,
1147 ;;;    including both the costs for move functions and coercion VOPs.
1148 ;;; 2. A SC-vector holding the SC that we load into, for any SC
1149 ;;;    that we can directly load from.
1150 ;;;
1151 ;;; In both vectors, unused entries are NIL. LOAD-P specifies the
1152 ;;; direction: if true, we are loading, if false we are saving.
1153 (defun compute-loading-costs (op load-p)
1154   (declare (type operand-parse op))
1155   (let ((scs (operand-parse-scs op))
1156         (costs (make-array sc-number-limit :initial-element nil))
1157         (load-scs (make-array sc-number-limit :initial-element nil)))
1158     (dolist (sc-name scs)
1159       (let* ((load-sc (meta-sc-or-lose sc-name))
1160              (load-scn (sc-number load-sc)))
1161         (setf (svref costs load-scn) 0)
1162         (setf (svref load-scs load-scn) t)
1163         (dolist (op-sc (append (when load-p
1164                                  (sc-constant-scs load-sc))
1165                                (sc-alternate-scs load-sc)))
1166           (let* ((op-scn (sc-number op-sc))
1167                  (load (if load-p
1168                            (aref (sc-load-costs load-sc) op-scn)
1169                            (aref (sc-load-costs op-sc) load-scn))))
1170             (unless load
1171               (error "no move function defined to move ~:[from~;to~] SC ~
1172                       ~S~%~:[to~;from~] alternate or constant SC ~S"
1173                      load-p sc-name load-p (sc-name op-sc)))
1174
1175             (let ((op-cost (svref costs op-scn)))
1176               (when (or (not op-cost) (< load op-cost))
1177                 (setf (svref costs op-scn) load)))
1178
1179             (let ((op-load (svref load-scs op-scn)))
1180               (unless (eq op-load t)
1181                 (pushnew load-scn (svref load-scs op-scn))))))
1182
1183         (dotimes (i sc-number-limit)
1184           (unless (svref costs i)
1185             (let ((op-sc (svref *backend-meta-sc-numbers* i)))
1186               (when op-sc
1187                 (let ((cost (if load-p
1188                                 (svref (sc-move-costs load-sc) i)
1189                                 (svref (sc-move-costs op-sc) load-scn))))
1190                   (when cost
1191                     (setf (svref costs i) cost)))))))))
1192
1193     (values costs load-scs)))
1194
1195 (defparameter *no-costs*
1196   (make-array sc-number-limit :initial-element 0))
1197
1198 (defparameter *no-loads*
1199   (make-array sc-number-limit :initial-element t))
1200
1201 ;;; Pick off the case of operands with no restrictions.
1202 (defun compute-loading-costs-if-any (op load-p)
1203   (declare (type operand-parse op))
1204   (if (operand-parse-scs op)
1205       (compute-loading-costs op load-p)
1206       (values *no-costs* *no-loads*)))
1207
1208 (defun compute-costs-and-restrictions-list (ops load-p)
1209   (declare (list ops))
1210   (collect ((costs)
1211             (scs))
1212     (dolist (op ops)
1213       (multiple-value-bind (costs scs) (compute-loading-costs-if-any op load-p)
1214         (costs costs)
1215         (scs scs)))
1216     (values (costs) (scs))))
1217
1218 (defun make-costs-and-restrictions (parse)
1219   (multiple-value-bind (arg-costs arg-scs)
1220       (compute-costs-and-restrictions-list (vop-parse-args parse) t)
1221     (multiple-value-bind (result-costs result-scs)
1222         (compute-costs-and-restrictions-list (vop-parse-results parse) nil)
1223       `(
1224         :cost ,(vop-parse-cost parse)
1225         
1226         :arg-costs ',arg-costs
1227         :arg-load-scs ',arg-scs
1228         :result-costs ',result-costs
1229         :result-load-scs ',result-scs
1230         
1231         :more-arg-costs
1232         ',(if (vop-parse-more-args parse)
1233               (compute-loading-costs-if-any (vop-parse-more-args parse) t)
1234               nil)
1235         
1236         :more-result-costs
1237         ',(if (vop-parse-more-results parse)
1238               (compute-loading-costs-if-any (vop-parse-more-results parse) nil)
1239               nil)))))
1240 \f
1241 ;;;; operand checking and stuff
1242
1243 ;;; Given a list of arg/result restrictions, check for valid syntax
1244 ;;; and convert to canonical form.
1245 (defun !parse-vop-operand-types (specs args-p)
1246   (declare (list specs))
1247   (labels ((parse-operand-type (spec)
1248              (cond ((eq spec '*) spec)
1249                    ((symbolp spec)
1250                     (let ((alias (gethash spec
1251                                           *backend-primitive-type-aliases*)))
1252                       (if alias
1253                           (parse-operand-type alias)
1254                           `(:or ,spec))))
1255                    ((atom spec)
1256                     (error "bad thing to be a operand type: ~S" spec))
1257                    (t
1258                     (case (first spec)
1259                       (:or
1260                        (collect ((results))
1261                          (results :or)
1262                          (dolist (item (cdr spec))
1263                            (unless (symbolp item)
1264                              (error "bad PRIMITIVE-TYPE name in ~S: ~S"
1265                                     spec item))
1266                            (let ((alias
1267                                   (gethash item
1268                                            *backend-primitive-type-aliases*)))
1269                              (if alias
1270                                  (let ((alias (parse-operand-type alias)))
1271                                    (unless (eq (car alias) :or)
1272                                      (error "can't include primitive-type ~
1273                                              alias ~S in an :OR restriction: ~S"
1274                                             item spec))
1275                                    (dolist (x (cdr alias))
1276                                      (results x)))
1277                                  (results item))))
1278                          (remove-duplicates (results)
1279                                             :test #'eq
1280                                             :start 1)))
1281                       (:constant
1282                        (unless args-p
1283                          (error "can't :CONSTANT for a result"))
1284                        (unless (= (length spec) 2)
1285                          (error "bad :CONSTANT argument type spec: ~S" spec))
1286                        spec)
1287                       (t
1288                        (error "bad thing to be a operand type: ~S" spec)))))))
1289     (mapcar #'parse-operand-type specs)))
1290
1291 ;;; Check the consistency of OP's SC restrictions with the specified
1292 ;;; primitive-type restriction. :CONSTANT operands have already been
1293 ;;; filtered out, so only :OR and * restrictions are left.
1294 ;;;
1295 ;;; We check that every representation allowed by the type can be
1296 ;;; directly loaded into some SC in the restriction, and that the type
1297 ;;; allows every SC in the restriction. With *, we require that T
1298 ;;; satisfy the first test, and omit the second.
1299 (defun check-operand-type-scs (parse op type load-p)
1300   (declare (type vop-parse parse) (type operand-parse op))
1301   (let ((ptypes (if (eq type '*) (list t) (rest type)))
1302         (scs (operand-parse-scs op)))
1303     (when scs
1304       (multiple-value-bind (costs load-scs) (compute-loading-costs op load-p)
1305         (declare (ignore costs))
1306         (dolist (ptype ptypes)
1307           (unless (dolist (rep (primitive-type-scs
1308                                 (meta-primitive-type-or-lose ptype))
1309                                nil)
1310                     (when (svref load-scs rep) (return t)))
1311             (error "In the ~A ~:[result~;argument~] to VOP ~S,~@
1312                     none of the SCs allowed by the operand type ~S can ~
1313                     directly be loaded~@
1314                     into any of the restriction's SCs:~%  ~S~:[~;~@
1315                     [* type operand must allow T's SCs.]~]"
1316                    (operand-parse-name op) load-p (vop-parse-name parse)
1317                    ptype
1318                    scs (eq type '*)))))
1319
1320       (dolist (sc scs)
1321         (unless (or (eq type '*)
1322                     (dolist (ptype ptypes nil)
1323                       (when (meta-sc-allowed-by-primitive-type
1324                              (meta-sc-or-lose sc)
1325                              (meta-primitive-type-or-lose ptype))
1326                         (return t))))
1327           (warn "~:[Result~;Argument~] ~A to VOP ~S~@
1328                  has SC restriction ~S which is ~
1329                  not allowed by the operand type:~%  ~S"
1330                 load-p (operand-parse-name op) (vop-parse-name parse)
1331                 sc type)))))
1332
1333   (values))
1334
1335 ;;; If the operand types are specified, then check the number specified
1336 ;;; against the number of defined operands.
1337 (defun check-operand-types (parse ops more-op types load-p)
1338   (declare (type vop-parse parse) (list ops)
1339            (type (or list (member :unspecified)) types)
1340            (type (or operand-parse null) more-op))
1341   (unless (eq types :unspecified)
1342     (let ((num (+ (length ops) (if more-op 1 0))))
1343       (unless (= (count-if-not (lambda (x)
1344                                  (and (consp x)
1345                                       (eq (car x) :constant)))
1346                                types)
1347                  num)
1348         (error "expected ~W ~:[result~;argument~] type~P: ~S"
1349                num load-p types num)))
1350
1351     (when more-op
1352       (let ((mtype (car (last types))))
1353         (when (and (consp mtype) (eq (first mtype) :constant))
1354           (error "can't use :CONSTANT on VOP more args")))))
1355
1356   (when (vop-parse-translate parse)
1357     (let ((types (specify-operand-types types ops more-op)))
1358       (mapc (lambda (x y)
1359               (check-operand-type-scs parse x y load-p))
1360             (if more-op (butlast ops) ops)
1361             (remove-if (lambda (x)
1362                          (and (consp x)
1363                               (eq (car x) ':constant)))
1364                        (if more-op (butlast types) types)))))
1365
1366   (values))
1367
1368 ;;; Compute stuff that can only be computed after we are done parsing
1369 ;;; everying. We set the VOP-PARSE-OPERANDS, and do various error checks.
1370 (defun !grovel-vop-operands (parse)
1371   (declare (type vop-parse parse))
1372
1373   (setf (vop-parse-operands parse)
1374         (append (vop-parse-args parse)
1375                 (if (vop-parse-more-args parse)
1376                     (list (vop-parse-more-args parse)))
1377                 (vop-parse-results parse)
1378                 (if (vop-parse-more-results parse)
1379                     (list (vop-parse-more-results parse)))
1380                 (vop-parse-temps parse)))
1381
1382   (check-operand-types parse
1383                        (vop-parse-args parse)
1384                        (vop-parse-more-args parse)
1385                        (vop-parse-arg-types parse)
1386                        t)
1387
1388   (check-operand-types parse
1389                        (vop-parse-results parse)
1390                        (vop-parse-more-results parse)
1391                        (vop-parse-result-types parse)
1392                        nil)
1393
1394   (values))
1395 \f
1396 ;;;; function translation stuff
1397
1398 ;;; Return forms to establish this VOP as a IR2 translation template
1399 ;;; for the :TRANSLATE functions specified in the VOP-PARSE. We also
1400 ;;; set the PREDICATE attribute for each translated function when the
1401 ;;; VOP is conditional, causing IR1 conversion to ensure that a call
1402 ;;; to the translated is always used in a predicate position.
1403 (defun !set-up-fun-translation (parse n-template)
1404   (declare (type vop-parse parse))
1405   (mapcar (lambda (name)
1406             `(let ((info (fun-info-or-lose ',name)))
1407                (setf (fun-info-templates info)
1408                      (adjoin-template ,n-template (fun-info-templates info)))
1409                ,@(when (vop-parse-conditional-p parse)
1410                    '((setf (fun-info-attributes info)
1411                            (attributes-union
1412                             (ir1-attributes predicate)
1413                             (fun-info-attributes info)))))))
1414           (vop-parse-translate parse)))
1415
1416 ;;; Return a form that can be evaluated to get the TEMPLATE operand type
1417 ;;; restriction from the given specification.
1418 (defun make-operand-type (type)
1419   (cond ((eq type '*) ''*)
1420         ((symbolp type)
1421          ``(:or ,(primitive-type-or-lose ',type)))
1422         (t
1423          (ecase (first type)
1424            (:or
1425             ``(:or ,,@(mapcar (lambda (type)
1426                                 `(primitive-type-or-lose ',type))
1427                               (rest type))))
1428            (:constant
1429             ``(:constant ,#'(lambda (x)
1430                               (typep x ',(second type)))
1431                          ,',(second type)))))))
1432
1433 (defun specify-operand-types (types ops more-ops)
1434   (if (eq types :unspecified)
1435       (make-list (+ (length ops) (if more-ops 1 0)) :initial-element '*)
1436       types))
1437
1438 ;;; Return a list of forms to use as &KEY args to MAKE-VOP-INFO for
1439 ;;; setting up the template argument and result types. Here we make an
1440 ;;; initial dummy TEMPLATE-TYPE, since it is awkward to compute the
1441 ;;; type until the template has been made.
1442 (defun make-vop-info-types (parse)
1443   (let* ((more-args (vop-parse-more-args parse))
1444          (all-args (specify-operand-types (vop-parse-arg-types parse)
1445                                           (vop-parse-args parse)
1446                                           more-args))
1447          (args (if more-args (butlast all-args) all-args))
1448          (more-arg (when more-args (car (last all-args))))
1449          (more-results (vop-parse-more-results parse))
1450          (all-results (specify-operand-types (vop-parse-result-types parse)
1451                                              (vop-parse-results parse)
1452                                              more-results))
1453          (results (if more-results (butlast all-results) all-results))
1454          (more-result (when more-results (car (last all-results))))
1455          (conditional (vop-parse-conditional-p parse)))
1456
1457     `(:type (specifier-type '(function () nil))
1458       :arg-types (list ,@(mapcar #'make-operand-type args))
1459       :more-args-type ,(when more-args (make-operand-type more-arg))
1460       :result-types ,(if conditional
1461                          :conditional
1462                          `(list ,@(mapcar #'make-operand-type results)))
1463       :more-results-type ,(when more-results
1464                             (make-operand-type more-result)))))
1465 \f
1466 ;;;; setting up VOP-INFO
1467
1468 (eval-when (:compile-toplevel :load-toplevel :execute)
1469   (defparameter *slot-inherit-alist*
1470     '((:generator-function . vop-info-generator-function))))
1471
1472 ;;; This is something to help with inheriting VOP-INFO slots. We
1473 ;;; return a keyword/value pair that can be passed to the constructor.
1474 ;;; SLOT is the keyword name of the slot, Parse is a form that
1475 ;;; evaluates to the VOP-PARSE structure for the VOP inherited. If
1476 ;;; PARSE is NIL, then we do nothing. If the TEST form evaluates to
1477 ;;; true, then we return a form that selects the named slot from the
1478 ;;; VOP-INFO structure corresponding to PARSE. Otherwise, we return
1479 ;;; the FORM so that the slot is recomputed.
1480 (defmacro inherit-vop-info (slot parse test form)
1481   `(if (and ,parse ,test)
1482        (list ,slot `(,',(or (cdr (assoc slot *slot-inherit-alist*))
1483                             (error "unknown slot ~S" slot))
1484                      (template-or-lose ',(vop-parse-name ,parse))))
1485        (list ,slot ,form)))
1486
1487 ;;; Return a form that creates a VOP-INFO structure which describes VOP.
1488 (defun set-up-vop-info (iparse parse)
1489   (declare (type vop-parse parse) (type (or vop-parse null) iparse))
1490   (let ((same-operands
1491          (and iparse
1492               (equal (vop-parse-operands parse)
1493                      (vop-parse-operands iparse))
1494               (equal (vop-parse-info-args iparse)
1495                      (vop-parse-info-args parse))))
1496         (variant (vop-parse-variant parse)))
1497
1498     (let ((nvars (length (vop-parse-variant-vars parse))))
1499       (unless (= (length variant) nvars)
1500         (error "expected ~W variant values: ~S" nvars variant)))
1501
1502     `(make-vop-info
1503       :name ',(vop-parse-name parse)
1504       ,@(make-vop-info-types parse)
1505       :guard ,(when (vop-parse-guard parse)
1506                 `(lambda () ,(vop-parse-guard parse)))
1507       :note ',(vop-parse-note parse)
1508       :info-arg-count ,(length (vop-parse-info-args parse))
1509       :ltn-policy ',(vop-parse-ltn-policy parse)
1510       :save-p ',(vop-parse-save-p parse)
1511       :move-args ',(vop-parse-move-args parse)
1512       :effects (vop-attributes ,@(vop-parse-effects parse))
1513       :affected (vop-attributes ,@(vop-parse-affected parse))
1514       ,@(make-costs-and-restrictions parse)
1515       ,@(make-emit-function-and-friends parse)
1516       ,@(inherit-vop-info :generator-function iparse
1517           (and same-operands
1518                (equal (vop-parse-body parse) (vop-parse-body iparse)))
1519           (unless (eq (vop-parse-body parse) :unspecified)
1520             (make-generator-function parse)))
1521       :variant (list ,@variant))))
1522 \f
1523 ;;; Define the symbol NAME to be a Virtual OPeration in the compiler.
1524 ;;; If specified, INHERITS is the name of a VOP that we default
1525 ;;; unspecified information from. Each SPEC is a list beginning with a
1526 ;;; keyword indicating the interpretation of the other forms in the
1527 ;;; SPEC:
1528 ;;;
1529 ;;; :ARGS {(Name {Key Value}*)}*
1530 ;;; :RESULTS {(Name {Key Value}*)}*
1531 ;;;     The Args and Results are specifications of the operand TNs passed
1532 ;;;     to the VOP. If there is an inherited VOP, any unspecified options
1533 ;;;     are defaulted from the inherited argument (or result) of the same
1534 ;;;     name. The following operand options are defined:
1535 ;;;
1536 ;;;     :SCs (SC*)
1537 ;;;         :SCs specifies good SCs for this operand. Other SCs will
1538 ;;;         be penalized according to move costs. A load TN will be
1539 ;;;         allocated if necessary, guaranteeing that the operand is
1540 ;;;         always one of the specified SCs.
1541 ;;;
1542 ;;;     :LOAD-TN Load-Name
1543 ;;;         Load-Name is bound to the load TN allocated for this
1544 ;;;         operand, or to NIL if no load TN was allocated.
1545 ;;;
1546 ;;;     :LOAD-IF EXPRESSION
1547 ;;;         Controls whether automatic operand loading is done.
1548 ;;;         EXPRESSION is evaluated with the fixed operand TNs bound.
1549 ;;;         If EXPRESSION is true,then loading is done and the variable
1550 ;;;         is bound to the load TN in the generator body. Otherwise,
1551 ;;;         loading is not done, and the variable is bound to the actual
1552 ;;;         operand.
1553 ;;;
1554 ;;;     :MORE T-or-NIL
1555 ;;;         If specified, NAME is bound to the TN-REF for the first
1556 ;;;         argument or result following the fixed arguments or results.
1557 ;;;         A :MORE operand must appear last, and cannot be targeted or
1558 ;;;         restricted.
1559 ;;;
1560 ;;;     :TARGET Operand
1561 ;;;         This operand is targeted to the named operand, indicating a
1562 ;;;         desire to pack in the same location. Not legal for results.
1563 ;;;
1564 ;;;     :FROM Time-Spec
1565 ;;;     :TO Time-Spec
1566 ;;;         Specify the beginning or end of the operand's lifetime.
1567 ;;;         :FROM can only be used with results, and :TO only with
1568 ;;;         arguments. The default for the N'th argument/result is
1569 ;;;         (:ARGUMENT N)/(:RESULT N). These options are necessary
1570 ;;;         primarily when operands are read or written out of order.
1571 ;;;
1572 ;;; :CONDITIONAL
1573 ;;;     This is used in place of :RESULTS with conditional branch VOPs.
1574 ;;;     There are no result values: the result is a transfer of control.
1575 ;;;     The target label is passed as the first :INFO arg. The second
1576 ;;;     :INFO arg is true if the sense of the test should be negated.
1577 ;;;     A side effect is to set the PREDICATE attribute for functions
1578 ;;;     in the :TRANSLATE option.
1579 ;;;
1580 ;;; :TEMPORARY ({Key Value}*) Name*
1581 ;;;     Allocate a temporary TN for each Name, binding that variable to
1582 ;;;     the TN within the body of the generators. In addition to :TARGET
1583 ;;;     (which is is the same as for operands), the following options are
1584 ;;;     defined:
1585 ;;;
1586 ;;;     :SC SC-Name
1587 ;;;     :OFFSET SB-Offset
1588 ;;;         Force the temporary to be allocated in the specified SC
1589 ;;;         with the specified offset. Offset is evaluated at
1590 ;;;         macroexpand time. If Offset is emitted, the register
1591 ;;;         allocator chooses a free location in SC. If both SC and
1592 ;;;         Offset are omitted, then the temporary is packed according
1593 ;;;         to its primitive type.
1594 ;;;
1595 ;;;     :FROM Time-Spec
1596 ;;;     :TO Time-Spec
1597 ;;;         Similar to the argument/result option, this specifies the
1598 ;;;         start and end of the temporaries' lives. The defaults are
1599 ;;;         :LOAD and :SAVE, i.e. the duration of the VOP. The other
1600 ;;;         intervening phases are :ARGUMENT,:EVAL and :RESULT.
1601 ;;;         Non-zero sub-phases can be specified by a list, e.g. by
1602 ;;;         default the second argument's life ends at (:ARGUMENT 1).
1603 ;;;
1604 ;;; :GENERATOR Cost Form*
1605 ;;;     Specifies the translation into assembly code. Cost is the
1606 ;;;     estimated cost of the code emitted by this generator. The body
1607 ;;;     is arbitrary Lisp code that emits the assembly language
1608 ;;;     translation of the VOP. An ASSEMBLE form is wrapped around
1609 ;;;     the body, so code may be emitted by using the local INST macro.
1610 ;;;     During the evaluation of the body, the names of the operands
1611 ;;;     and temporaries are bound to the actual TNs.
1612 ;;;
1613 ;;; :EFFECTS Effect*
1614 ;;; :AFFECTED Effect*
1615 ;;;     Specifies the side effects that this VOP has and the side
1616 ;;;     effects that effect its execution. If unspecified, these
1617 ;;;     default to the worst case.
1618 ;;;
1619 ;;; :INFO Name*
1620 ;;;     Define some magic arguments that are passed directly to the code
1621 ;;;     generator. The corresponding trailing arguments to VOP or
1622 ;;;     %PRIMITIVE are stored in the VOP structure. Within the body
1623 ;;;     of the generators, the named variables are bound to these
1624 ;;;     values. Except in the case of :CONDITIONAL VOPs, :INFO arguments
1625 ;;;     cannot be specified for VOPS that are the direct translation
1626 ;;;     for a function (specified by :TRANSLATE).
1627 ;;;
1628 ;;; :IGNORE Name*
1629 ;;;     Causes the named variables to be declared IGNORE in the
1630 ;;;     generator body.
1631 ;;;
1632 ;;; :VARIANT Thing*
1633 ;;; :VARIANT-VARS Name*
1634 ;;;     These options provide a way to parameterize families of VOPs
1635 ;;;     that differ only trivially. :VARIANT makes the specified
1636 ;;;     evaluated Things be the "variant" associated with this VOP.
1637 ;;;     :VARIANT-VARS causes the named variables to be bound to the
1638 ;;;     corresponding Things within the body of the generator.
1639 ;;;
1640 ;;; :VARIANT-COST Cost
1641 ;;;     Specifies the cost of this VOP, overriding the cost of any 
1642 ;;;     inherited generator.
1643 ;;;
1644 ;;; :NOTE {String | NIL}
1645 ;;;     A short noun-like phrase describing what this VOP "does", i.e.
1646 ;;;     the implementation strategy. If supplied, efficiency notes will
1647 ;;;     be generated when type uncertainty prevents :TRANSLATE from
1648 ;;;     working. NIL inhibits any efficiency note.
1649 ;;;
1650 ;;; :ARG-TYPES    {* | PType | (:OR PType*) | (:CONSTANT Type)}*
1651 ;;; :RESULT-TYPES {* | PType | (:OR PType*)}*
1652 ;;;     Specify the template type restrictions used for automatic
1653 ;;;     translation. If there is a :MORE operand, the last type is the
1654 ;;;     more type. :CONSTANT specifies that the argument must be a
1655 ;;;     compile-time constant of the specified Lisp type. The constant
1656 ;;;     values of :CONSTANT arguments are passed as additional :INFO
1657 ;;;     arguments rather than as :ARGS.
1658 ;;;
1659 ;;; :TRANSLATE Name*
1660 ;;;     This option causes the VOP template to be entered as an IR2
1661 ;;;     translation for the named functions.
1662 ;;;
1663 ;;; :POLICY {:SMALL | :FAST | :SAFE | :FAST-SAFE}
1664 ;;;     Specifies the policy under which this VOP is the best translation.
1665 ;;;
1666 ;;; :GUARD Form
1667 ;;;     Specifies a Form that is evaluated in the global environment.
1668 ;;;     If form returns NIL, then emission of this VOP is prohibited
1669 ;;;     even when all other restrictions are met.
1670 ;;;
1671 ;;; :VOP-VAR Name
1672 ;;; :NODE-VAR Name
1673 ;;;     In the generator, bind the specified variable to the VOP or
1674 ;;;     the Node that generated this VOP.
1675 ;;;
1676 ;;; :SAVE-P {NIL | T | :COMPUTE-ONLY | :FORCE-TO-STACK}
1677 ;;;     Indicates how a VOP wants live registers saved.
1678 ;;;
1679 ;;; :MOVE-ARGS {NIL | :FULL-CALL | :LOCAL-CALL | :KNOWN-RETURN}
1680 ;;;     Indicates if and how the more args should be moved into a
1681 ;;;     different frame.
1682 (def!macro define-vop ((name &optional inherits) &rest specs)
1683   (declare (type symbol name))
1684   ;; Parse the syntax into a VOP-PARSE structure, and then expand into
1685   ;; code that creates the appropriate VOP-INFO structure at load time.
1686   ;; We implement inheritance by copying the VOP-PARSE structure for
1687   ;; the inherited structure.
1688   (let* ((inherited-parse (when inherits
1689                             (vop-parse-or-lose inherits)))
1690          (parse (if inherits
1691                     (copy-vop-parse inherited-parse)
1692                     (make-vop-parse)))
1693          (n-res (gensym)))
1694     (setf (vop-parse-name parse) name)
1695     (setf (vop-parse-inherits parse) inherits)
1696
1697     (parse-define-vop parse specs)
1698     (!grovel-vop-operands parse)
1699
1700     `(progn
1701        (eval-when (:compile-toplevel :load-toplevel :execute)
1702          (setf (gethash ',name *backend-parsed-vops*)
1703                ',parse))
1704
1705        (let ((,n-res ,(set-up-vop-info inherited-parse parse)))
1706          (setf (gethash ',name *backend-template-names*) ,n-res)
1707          (setf (template-type ,n-res)
1708                (specifier-type (template-type-specifier ,n-res)))
1709          ,@(!set-up-fun-translation parse n-res))
1710        ',name)))
1711 \f
1712 ;;;; emission macros
1713
1714 ;;; Return code to make a list of VOP arguments or results, linked by
1715 ;;; TN-REF-ACROSS. The first value is code, the second value is LET*
1716 ;;; forms, and the third value is a variable that evaluates to the
1717 ;;; head of the list, or NIL if there are no operands. Fixed is a list
1718 ;;; of forms that evaluate to TNs for the fixed operands. TN-REFS will
1719 ;;; be made for these operands according using the specified value of
1720 ;;; WRITE-P. More is an expression that evaluates to a list of TN-REFS
1721 ;;; that will be made the tail of the list. If it is constant NIL,
1722 ;;; then we don't bother to set the tail.
1723 (defun make-operand-list (fixed more write-p)
1724   (collect ((forms)
1725             (binds))
1726     (let ((n-head nil)
1727           (n-prev nil))
1728       (dolist (op fixed)
1729         (let ((n-ref (gensym)))
1730           (binds `(,n-ref (reference-tn ,op ,write-p)))
1731           (if n-prev
1732               (forms `(setf (tn-ref-across ,n-prev) ,n-ref))
1733               (setq n-head n-ref))
1734           (setq n-prev n-ref)))
1735
1736       (when more
1737         (let ((n-more (gensym)))
1738           (binds `(,n-more ,more))
1739           (if n-prev
1740               (forms `(setf (tn-ref-across ,n-prev) ,n-more))
1741               (setq n-head n-more))))
1742
1743       (values (forms) (binds) n-head))))
1744
1745 ;;; Emit-Template Node Block Template Args Results [Info]
1746 ;;;
1747 ;;; Call the emit function for TEMPLATE, linking the result in at the
1748 ;;; end of BLOCK.
1749 (defmacro emit-template (node block template args results &optional info)
1750   (let ((n-first (gensym))
1751         (n-last (gensym)))
1752     (once-only ((n-node node)
1753                 (n-block block)
1754                 (n-template template))
1755       `(multiple-value-bind (,n-first ,n-last)
1756            (funcall (template-emit-function ,n-template)
1757                     ,n-node ,n-block ,n-template ,args ,results
1758                     ,@(when info `(,info)))
1759          (insert-vop-sequence ,n-first ,n-last ,n-block nil)))))
1760
1761 ;;; VOP Name Node Block Arg* Info* Result*
1762 ;;;
1763 ;;; Emit the VOP (or other template) NAME at the end of the IR2-BLOCK
1764 ;;; BLOCK, using NODE for the source context. The interpretation of
1765 ;;; the remaining arguments depends on the number of operands of
1766 ;;; various kinds that are declared in the template definition. VOP
1767 ;;; cannot be used for templates that have more-args or more-results,
1768 ;;; since the number of arguments and results is indeterminate for
1769 ;;; these templates. Use VOP* instead.
1770 ;;;
1771 ;;; ARGS and RESULTS are the TNs that are to be referenced by the
1772 ;;; template as arguments and results. If the template has
1773 ;;; codegen-info arguments, then the appropriate number of INFO forms
1774 ;;; following the arguments are used for codegen info.
1775 (defmacro vop (name node block &rest operands)
1776   (let* ((parse (vop-parse-or-lose name))
1777          (arg-count (length (vop-parse-args parse)))
1778          (result-count (length (vop-parse-results parse)))
1779          (info-count (length (vop-parse-info-args parse)))
1780          (noperands (+ arg-count result-count info-count))
1781          (n-node (gensym))
1782          (n-block (gensym))
1783          (n-template (gensym)))
1784
1785     (when (or (vop-parse-more-args parse) (vop-parse-more-results parse))
1786       (error "cannot use VOP with variable operand count templates"))
1787     (unless (= noperands (length operands))
1788       (error "called with ~W operands, but was expecting ~W"
1789              (length operands) noperands))
1790
1791     (multiple-value-bind (acode abinds n-args)
1792         (make-operand-list (subseq operands 0 arg-count) nil nil)
1793       (multiple-value-bind (rcode rbinds n-results)
1794           (make-operand-list (subseq operands (+ arg-count info-count)) nil t)
1795
1796         (collect ((ibinds)
1797                   (ivars))
1798           (dolist (info (subseq operands arg-count (+ arg-count info-count)))
1799             (let ((temp (gensym)))
1800               (ibinds `(,temp ,info))
1801               (ivars temp)))
1802
1803           `(let* ((,n-node ,node)
1804                   (,n-block ,block)
1805                   (,n-template (template-or-lose ',name))
1806                   ,@abinds
1807                   ,@(ibinds)
1808                   ,@rbinds)
1809              ,@acode
1810              ,@rcode
1811              (emit-template ,n-node ,n-block ,n-template ,n-args
1812                             ,n-results
1813                             ,@(when (ivars)
1814                                 `((list ,@(ivars)))))
1815              (values)))))))
1816
1817 ;;; VOP* Name Node Block (Arg* More-Args) (Result* More-Results) Info*
1818 ;;;
1819 ;;; This is like VOP, but allows for emission of templates with
1820 ;;; arbitrary numbers of arguments, and for emission of templates
1821 ;;; using already-created TN-REF lists.
1822 ;;;
1823 ;;; The ARGS and RESULTS are TNs to be referenced as the first
1824 ;;; arguments and results to the template. More-Args and More-Results
1825 ;;; are heads of TN-REF lists that are added onto the end of the
1826 ;;; TN-REFS for the explicitly supplied operand TNs. The TN-REFS for
1827 ;;; the more operands must have the TN and WRITE-P slots correctly
1828 ;;; initialized.
1829 ;;;
1830 ;;; As with VOP, the INFO forms are evaluated and passed as codegen
1831 ;;; info arguments.
1832 (defmacro vop* (name node block args results &rest info)
1833   (declare (type cons args results))
1834   (let* ((parse (vop-parse-or-lose name))
1835          (arg-count (length (vop-parse-args parse)))
1836          (result-count (length (vop-parse-results parse)))
1837          (info-count (length (vop-parse-info-args parse)))
1838          (fixed-args (butlast args))
1839          (fixed-results (butlast results))
1840          (n-node (gensym))
1841          (n-block (gensym))
1842          (n-template (gensym)))
1843
1844     (unless (or (vop-parse-more-args parse)
1845                 (<= (length fixed-args) arg-count))
1846       (error "too many fixed arguments"))
1847     (unless (or (vop-parse-more-results parse)
1848                 (<= (length fixed-results) result-count))
1849       (error "too many fixed results"))
1850     (unless (= (length info) info-count)
1851       (error "expected ~W info args" info-count))
1852
1853     (multiple-value-bind (acode abinds n-args)
1854         (make-operand-list fixed-args (car (last args)) nil)
1855       (multiple-value-bind (rcode rbinds n-results)
1856           (make-operand-list fixed-results (car (last results)) t)
1857
1858         `(let* ((,n-node ,node)
1859                 (,n-block ,block)
1860                 (,n-template (template-or-lose ',name))
1861                 ,@abinds
1862                 ,@rbinds)
1863            ,@acode
1864            ,@rcode
1865            (emit-template ,n-node ,n-block ,n-template ,n-args ,n-results
1866                           ,@(when info
1867                               `((list ,@info))))
1868            (values))))))
1869 \f
1870 ;;;; miscellaneous macros
1871
1872 ;;; SC-Case TN {({(SC-Name*) | SC-Name | T} Form*)}*
1873 ;;;
1874 ;;; Case off of TN's SC. The first clause containing TN's SC is
1875 ;;; evaluated, returning the values of the last form. A clause
1876 ;;; beginning with T specifies a default. If it appears, it must be
1877 ;;; last. If no default is specified, and no clause matches, then an
1878 ;;; error is signalled.
1879 (def!macro sc-case (tn &rest forms)
1880   (let ((n-sc (gensym))
1881         (n-tn (gensym)))
1882     (collect ((clauses))
1883       (do ((cases forms (rest cases)))
1884           ((null cases)
1885            (clauses `(t (error "unknown SC to SC-CASE for ~S:~%  ~S" ,n-tn
1886                                (sc-name (tn-sc ,n-tn))))))
1887         (let ((case (first cases)))
1888           (when (atom case)
1889             (error "illegal SC-CASE clause: ~S" case))
1890           (let ((head (first case)))
1891             (when (eq head t)
1892               (when (rest cases)
1893                 (error "T case is not last in SC-CASE."))
1894               (clauses `(t nil ,@(rest case)))
1895               (return))
1896             (clauses `((or ,@(mapcar (lambda (x)
1897                                        `(eql ,(meta-sc-number-or-lose x)
1898                                              ,n-sc))
1899                                      (if (atom head) (list head) head)))
1900                        nil ,@(rest case))))))
1901
1902       `(let* ((,n-tn ,tn)
1903               (,n-sc (sc-number (tn-sc ,n-tn))))
1904          (cond ,@(clauses))))))
1905
1906 ;;; Return true if TNs SC is any of the named SCs, false otherwise.
1907 (defmacro sc-is (tn &rest scs)
1908   (once-only ((n-sc `(sc-number (tn-sc ,tn))))
1909     `(or ,@(mapcar (lambda (x)
1910                      `(eql ,n-sc ,(meta-sc-number-or-lose x)))
1911                    scs))))
1912
1913 ;;; Iterate over the IR2 blocks in component, in emission order.
1914 (defmacro do-ir2-blocks ((block-var component &optional result)
1915                          &body forms)
1916   `(do ((,block-var (block-info (component-head ,component))
1917                     (ir2-block-next ,block-var)))
1918        ((null ,block-var) ,result)
1919      ,@forms))
1920
1921 ;;; Iterate over all the TNs live at some point, with the live set
1922 ;;; represented by a local conflicts bit-vector and the IR2-BLOCK
1923 ;;; containing the location.
1924 (defmacro do-live-tns ((tn-var live block &optional result) &body body)
1925   (let ((n-conf (gensym))
1926         (n-bod (gensym))
1927         (i (gensym))
1928         (ltns (gensym)))
1929     (once-only ((n-live live)
1930                 (n-block block))
1931       `(block nil
1932          (flet ((,n-bod (,tn-var) ,@body))
1933            ;; Do component-live TNs.
1934            (dolist (,tn-var (ir2-component-component-tns
1935                              (component-info
1936                               (block-component
1937                                (ir2-block-block ,n-block)))))
1938              (,n-bod ,tn-var))
1939
1940            (let ((,ltns (ir2-block-local-tns ,n-block)))
1941              ;; Do TNs always-live in this block and live :MORE TNs.
1942              (do ((,n-conf (ir2-block-global-tns ,n-block)
1943                            (global-conflicts-next-blockwise ,n-conf)))
1944                  ((null ,n-conf))
1945                (when (or (eq (global-conflicts-kind ,n-conf) :live)
1946                          (let ((,i (global-conflicts-number ,n-conf)))
1947                            (and (eq (svref ,ltns ,i) :more)
1948                                 (not (zerop (sbit ,n-live ,i))))))
1949                  (,n-bod (global-conflicts-tn ,n-conf))))
1950              ;; Do TNs locally live in the designated live set.
1951              (dotimes (,i (ir2-block-local-tn-count ,n-block) ,result)
1952                (unless (zerop (sbit ,n-live ,i))
1953                  (let ((,tn-var (svref ,ltns ,i)))
1954                    (when (and ,tn-var (not (eq ,tn-var :more)))
1955                      (,n-bod ,tn-var)))))))))))
1956
1957 ;;; Iterate over all the IR2 blocks in PHYSENV, in emit order.
1958 (defmacro do-physenv-ir2-blocks ((block-var physenv &optional result)
1959                                  &body body)
1960   (once-only ((n-physenv physenv))
1961     (once-only ((n-first `(lambda-block (physenv-lambda ,n-physenv))))
1962       (once-only ((n-tail `(block-info
1963                             (component-tail
1964                              (block-component ,n-first)))))
1965         `(do ((,block-var (block-info ,n-first)
1966                           (ir2-block-next ,block-var)))
1967              ((or (eq ,block-var ,n-tail)
1968                   (not (eq (ir2-block-physenv ,block-var) ,n-physenv)))
1969               ,result)
1970            ,@body)))))