0.8.0.78.vector-nil-string.8:
[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 (gensym) :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-TEMP holds the write reference that begins a temporary's
469   ;; lifetime.
470   (temp (gensym) :type symbol)
471   (temp-temp nil :type (or symbol null))
472   ;; the time that this operand is first live and the time at which it
473   ;; becomes dead again. These are TIME-SPECs, as returned by
474   ;; PARSE-TIME-SPEC.
475   born
476   dies
477   ;; a list of the names of the SCs that this operand is allowed into.
478   ;; If false, there is no restriction.
479   (scs nil :type list)
480   ;; Variable that is bound to the load TN allocated for this operand, or to
481   ;; NIL if no load-TN was allocated.
482   (load-tn (gensym) :type symbol)
483   ;; an expression that tests whether to do automatic operand loading
484   (load t)
485   ;; In a wired or restricted temporary this is the SC the TN is to be
486   ;; packed in. Null otherwise.
487   (sc nil :type (or symbol null))
488   ;; If non-null, we are a temp wired to this offset in SC.
489   (offset nil :type (or unsigned-byte null)))
490 (defprinter (operand-parse)
491   name
492   kind
493   (target :test target)
494   born
495   dies
496   (scs :test scs)
497   (load :test load)
498   (sc :test sc)
499   (offset :test offset))
500 \f
501 ;;;; miscellaneous utilities
502
503 ;;; Find the operand or temporary with the specifed Name in the VOP
504 ;;; Parse. If there is no such operand, signal an error. Also error if
505 ;;; the operand kind isn't one of the specified Kinds. If Error-P is
506 ;;; NIL, just return NIL if there is no such operand.
507 (defun find-operand (name parse &optional
508                           (kinds '(:argument :result :temporary))
509                           (error-p t))
510   (declare (symbol name) (type vop-parse parse) (list kinds))
511   (let ((found (find name (vop-parse-operands parse)
512                      :key #'operand-parse-name)))
513     (if found
514         (unless (member (operand-parse-kind found) kinds)
515           (error "Operand ~S isn't one of these kinds: ~S." name kinds))
516         (when error-p
517           (error "~S is not an operand to ~S." name (vop-parse-name parse))))
518     found))
519
520 ;;; Get the VOP-PARSE structure for NAME or die trying. For all
521 ;;; meta-compile time uses, the VOP-PARSE should be used instead of
522 ;;; the VOP-INFO.
523 (defun vop-parse-or-lose (name)
524   (the vop-parse
525        (or (gethash name *backend-parsed-vops*)
526            (error "~S is not the name of a defined VOP." name))))
527
528 ;;; Return a list of LET-forms to parse a TN-REF list into the temps
529 ;;; specified by the operand-parse structures. MORE-OPERAND is the
530 ;;; Operand-Parse describing any more operand, or NIL if none. REFS is
531 ;;; an expression that evaluates into the first tn-ref.
532 (defun access-operands (operands more-operand refs)
533   (declare (list operands))
534   (collect ((res))
535     (let ((prev refs))
536       (dolist (op operands)
537         (let ((n-ref (operand-parse-temp op)))
538           (res `(,n-ref ,prev))
539           (setq prev `(tn-ref-across ,n-ref))))
540
541       (when more-operand
542         (res `(,(operand-parse-name more-operand) ,prev))))
543     (res)))
544
545 ;;; This is used with ACCESS-OPERANDS to prevent warnings for TN-REF
546 ;;; temps not used by some particular function. It returns the name of
547 ;;; the last operand, or NIL if Operands is NIL.
548 (defun ignore-unreferenced-temps (operands)
549   (when operands
550     (operand-parse-temp (car (last operands)))))
551
552 ;;; Grab an arg out of a VOP spec, checking the type and syntax and stuff.
553 (defun vop-spec-arg (spec type &optional (n 1) (last t))
554   (let ((len (length spec)))
555     (when (<= len n)
556       (error "~:R argument missing: ~S" n spec))
557     (when (and last (> len (1+ n)))
558       (error "extra junk at end of ~S" spec))
559     (let ((thing (elt spec n)))
560       (unless (typep thing type)
561         (error "~:R argument is not a ~S: ~S" n type spec))
562       thing)))
563 \f
564 ;;;; time specs
565
566 ;;; Return a time spec describing a time during the evaluation of a
567 ;;; VOP, used to delimit operand and temporary lifetimes. The
568 ;;; representation is a cons whose CAR is the number of the evaluation
569 ;;; phase and the CDR is the sub-phase. The sub-phase is 0 in the
570 ;;; :LOAD and :SAVE phases.
571 (defun parse-time-spec (spec)
572   (let ((dspec (if (atom spec) (list spec 0) spec)))
573     (unless (and (= (length dspec) 2)
574                  (typep (second dspec) 'unsigned-byte))
575       (error "malformed time specifier: ~S" spec))
576
577     (cons (case (first dspec)
578             (:load 0)
579             (:argument 1)
580             (:eval 2)
581             (:result 3)
582             (:save 4)
583             (t
584              (error "unknown phase in time specifier: ~S" spec)))
585           (second dspec))))
586
587 ;;; Return true if the time spec X is the same or later time than Y.
588 (defun time-spec-order (x y)
589   (or (> (car x) (car y))
590       (and (= (car x) (car y))
591            (>= (cdr x) (cdr y)))))
592 \f
593 ;;;; generation of emit functions
594
595 (defun compute-temporaries-description (parse)
596   (let ((temps (vop-parse-temps parse))
597         (element-type '(unsigned-byte 16)))
598     (when temps
599       (let ((results (make-specializable-array
600                       (length temps)
601                       :element-type element-type))
602             (index 0))
603         (dolist (temp temps)
604           (declare (type operand-parse temp))
605           (let ((sc (operand-parse-sc temp))
606                 (offset (operand-parse-offset temp)))
607             (aver sc)
608             (setf (aref results index)
609                   (if offset
610                       (+ (ash offset (1+ sc-bits))
611                          (ash (meta-sc-number-or-lose sc) 1)
612                          1)
613                       (ash (meta-sc-number-or-lose sc) 1))))
614           (incf index))
615         ;; KLUDGE: As in the other COERCEs wrapped around with
616         ;; MAKE-SPECIALIZABLE-ARRAY results in COMPUTE-REF-ORDERING,
617         ;; this coercion could be removed by a sufficiently smart
618         ;; compiler, but I dunno whether Python is that smart. It
619         ;; would be good to check this and help it if it's not smart
620         ;; enough to remove it for itself. However, it's probably not
621         ;; urgent, since the overhead of an extra no-op conversion is
622         ;; unlikely to be large compared to consing and corresponding
623         ;; GC. -- WHN ca. 19990701
624         `(coerce ,results '(specializable-vector ,element-type))))))
625
626 (defun compute-ref-ordering (parse)
627   (let* ((num-args (+ (length (vop-parse-args parse))
628                       (if (vop-parse-more-args parse) 1 0)))
629          (num-results (+ (length (vop-parse-results parse))
630                          (if (vop-parse-more-results parse) 1 0)))
631          (index 0))
632     (collect ((refs) (targets))
633       (dolist (op (vop-parse-operands parse))
634         (when (operand-parse-target op)
635           (unless (member (operand-parse-kind op) '(:argument :temporary))
636             (error "cannot target a ~S operand: ~S" (operand-parse-kind op)
637                    (operand-parse-name op)))
638           (let ((target (find-operand (operand-parse-target op) parse
639                                       '(:temporary :result))))
640             ;; KLUDGE: These formulas must be consistent with those in
641             ;; %EMIT-GENERIC-VOP, and this is currently maintained by
642             ;; hand. -- WHN 2002-01-30, paraphrasing APD
643             (targets (+ (* index max-vop-tn-refs)
644                         (ecase (operand-parse-kind target)
645                           (:result
646                            (+ (position-or-lose target
647                                                 (vop-parse-results parse))
648                               num-args))
649                           (:temporary
650                            (+ (* (position-or-lose target
651                                                    (vop-parse-temps parse))
652                                  2)
653                               1
654                               num-args
655                               num-results)))))))
656         (let ((born (operand-parse-born op))
657               (dies (operand-parse-dies op)))
658           (ecase (operand-parse-kind op)
659             (:argument
660              (refs (cons (cons dies nil) index)))
661             (:more-argument
662              (refs (cons (cons dies nil) index)))
663             (:result
664              (refs (cons (cons born t) index)))
665             (:more-result
666              (refs (cons (cons born t) index)))
667             (:temporary
668              (refs (cons (cons dies nil) index))
669              (incf index)
670              (refs (cons (cons born t) index))))
671           (incf index)))
672       (let* ((sorted (sort (refs)
673                            (lambda (x y)
674                              (let ((x-time (car x))
675                                    (y-time (car y)))
676                                (if (time-spec-order x-time y-time)
677                                    (if (time-spec-order y-time x-time)
678                                        (and (not (cdr x)) (cdr y))
679                                        nil)
680                                    t)))
681                            :key #'car))
682              (oe-type '(mod #.max-vop-tn-refs)) ; :REF-ORDERING element type
683              (te-type '(mod #.(* max-vop-tn-refs 2))) ; :TARGETS element type
684              (ordering (make-specializable-array
685                         (length sorted)
686                         :element-type oe-type)))
687         (let ((index 0))
688           (dolist (ref sorted)
689             (setf (aref ordering index) (cdr ref))
690             (incf index)))
691         `(:num-args ,num-args
692           :num-results ,num-results
693           ;; KLUDGE: The (COERCE .. (SPECIALIZABLE-VECTOR ..)) wrapper
694           ;; here around the result returned by
695           ;; MAKE-SPECIALIZABLE-ARRAY above was of course added to
696           ;; help with cross-compilation. "A sufficiently smart
697           ;; compiler" should be able to optimize all this away in the
698           ;; final target Lisp, leaving a single MAKE-ARRAY with no
699           ;; subsequent coercion. However, I don't know whether Python
700           ;; is that smart. (Can it figure out the return type of
701           ;; MAKE-ARRAY? Does it know that COERCE can be optimized
702           ;; away if the input type is known to be the same as the
703           ;; COERCEd-to type?) At some point it would be good to test
704           ;; to see whether this construct is in fact causing run-time
705           ;; overhead, and fix it if so. (Some declarations of the
706           ;; types returned by MAKE-ARRAY might be enough to fix it.)
707           ;; However, it's probably not urgent to fix this, since it's
708           ;; hard to imagine that any overhead caused by calling
709           ;; COERCE and letting it decide to bail out could be large
710           ;; compared to the cost of consing and GCing the vectors in
711           ;; the first place. -- WHN ca. 19990701
712           :ref-ordering (coerce ',ordering
713                                 '(specializable-vector ,oe-type))
714           ,@(when (targets)
715               `(:targets (coerce ',(targets)
716                                  '(specializable-vector ,te-type)))))))))
717
718 (defun make-emit-function-and-friends (parse)
719   `(:emit-function #'emit-generic-vop
720     :temps ,(compute-temporaries-description parse)
721     ,@(compute-ref-ordering parse)))
722 \f
723 ;;;; generator functions
724
725 ;;; Return an alist that translates from lists of SCs we can load OP
726 ;;; from to the move function used for loading those SCs. We quietly
727 ;;; ignore restrictions to :non-packed (constant) and :unbounded SCs,
728 ;;; since we don't load into those SCs.
729 (defun find-move-funs (op load-p)
730   (collect ((funs))
731     (dolist (sc-name (operand-parse-scs op))
732       (let* ((sc (meta-sc-or-lose sc-name))
733              (scn (sc-number sc))
734              (load-scs (append (when load-p
735                                  (sc-constant-scs sc))
736                                (sc-alternate-scs sc))))
737         (cond
738          (load-scs
739           (dolist (alt load-scs)
740             (unless (member (sc-name alt) (operand-parse-scs op) :test #'eq)
741               (let* ((altn (sc-number alt))
742                      (name (if load-p
743                                (svref (sc-move-funs sc) altn)
744                                (svref (sc-move-funs alt) scn)))
745                      (found (or (assoc alt (funs) :test #'member)
746                                 (rassoc name (funs)))))
747                 (unless name
748                   (error "no move function defined to ~:[save~;load~] SC ~S ~
749                           with ~S ~:[to~;from~] from SC ~S"
750                          load-p sc-name load-p (sc-name alt)))
751                 
752                 (cond (found
753                        (unless (eq (cdr found) name)
754                          (error "can't tell whether to ~:[save~;load~]~@
755                                  or ~S when operand is in SC ~S"
756                                 load-p name (cdr found) (sc-name alt)))
757                        (pushnew alt (car found)))
758                       (t
759                        (funs (cons (list alt) name))))))))
760          ((member (sb-kind (sc-sb sc)) '(:non-packed :unbounded)))
761          (t
762           (error "SC ~S has no alternate~:[~; or constant~] SCs, yet it is~@
763                   mentioned in the restriction for operand ~S"
764                  sc-name load-p (operand-parse-name op))))))
765     (funs)))
766
767 ;;; Return a form to load/save the specified operand when it has a
768 ;;; load TN. For any given SC that we can load from, there must be a
769 ;;; unique load function. If all SCs we can load from have the same
770 ;;; move function, then we just call that when there is a load TN. If
771 ;;; there are multiple possible move functions, then we dispatch off
772 ;;; of the operand TN's type to see which move function to use.
773 (defun call-move-fun (parse op load-p)
774   (let ((funs (find-move-funs op load-p))
775         (load-tn (operand-parse-load-tn op)))
776     (if funs
777         (let* ((tn `(tn-ref-tn ,(operand-parse-temp op)))
778                (n-vop (or (vop-parse-vop-var parse)
779                           (setf (vop-parse-vop-var parse) (gensym))))
780                (form (if (rest funs)
781                          `(sc-case ,tn
782                             ,@(mapcar (lambda (x)
783                                         `(,(mapcar #'sc-name (car x))
784                                           ,(if load-p
785                                                `(,(cdr x) ,n-vop ,tn
786                                                  ,load-tn)
787                                                `(,(cdr x) ,n-vop ,load-tn
788                                                  ,tn))))
789                                       funs))
790                          (if load-p
791                              `(,(cdr (first funs)) ,n-vop ,tn ,load-tn)
792                              `(,(cdr (first funs)) ,n-vop ,load-tn ,tn)))))
793           (if (eq (operand-parse-load op) t)
794               `(when ,load-tn ,form)
795               `(when (eq ,load-tn ,(operand-parse-name op))
796                  ,form)))
797         `(when ,load-tn
798            (error "load TN allocated, but no move function?~@
799                    VM definition is inconsistent, recompile and try again.")))))
800
801 ;;; Return the TN that we should bind to the operand's var in the
802 ;;; generator body. In general, this involves evaluating the :LOAD-IF
803 ;;; test expression.
804 (defun decide-to-load (parse op)
805   (let ((load (operand-parse-load op))
806         (load-tn (operand-parse-load-tn op))
807         (temp (operand-parse-temp op)))
808     (if (eq load t)
809         `(or ,load-tn (tn-ref-tn ,temp))
810         (collect ((binds)
811                   (ignores))
812           (dolist (x (vop-parse-operands parse))
813             (when (member (operand-parse-kind x) '(:argument :result))
814               (let ((name (operand-parse-name x)))
815                 (binds `(,name (tn-ref-tn ,(operand-parse-temp x))))
816                 (ignores name))))
817           `(if (and ,load-tn
818                     (let ,(binds)
819                       (declare (ignorable ,@(ignores)))
820                       ,load))
821                ,load-tn
822                (tn-ref-tn ,temp))))))
823
824 ;;; Make a lambda that parses the VOP TN-REFS, does automatic operand
825 ;;; loading, and runs the appropriate code generator.
826 (defun make-generator-function (parse)
827   (declare (type vop-parse parse))
828   (let ((n-vop (vop-parse-vop-var parse))
829         (operands (vop-parse-operands parse))
830         (n-info (gensym)) (n-variant (gensym)))
831     (collect ((binds)
832               (loads)
833               (saves))
834       (dolist (op operands)
835         (ecase (operand-parse-kind op)
836           ((:argument :result)
837            (let ((temp (operand-parse-temp op))
838                  (name (operand-parse-name op)))
839              (cond ((and (operand-parse-load op) (operand-parse-scs op))
840                     (binds `(,(operand-parse-load-tn op)
841                              (tn-ref-load-tn ,temp)))
842                     (binds `(,name ,(decide-to-load parse op)))
843                     (if (eq (operand-parse-kind op) :argument)
844                         (loads (call-move-fun parse op t))
845                         (saves (call-move-fun parse op nil))))
846                    (t
847                     (binds `(,name (tn-ref-tn ,temp)))))))
848           (:temporary
849            (binds `(,(operand-parse-name op)
850                     (tn-ref-tn ,(operand-parse-temp op)))))
851           ((:more-argument :more-result))))
852
853       `(lambda (,n-vop)
854          (let* (,@(access-operands (vop-parse-args parse)
855                                    (vop-parse-more-args parse)
856                                    `(vop-args ,n-vop))
857                   ,@(access-operands (vop-parse-results parse)
858                                      (vop-parse-more-results parse)
859                                      `(vop-results ,n-vop))
860                   ,@(access-operands (vop-parse-temps parse) nil
861                                      `(vop-temps ,n-vop))
862                   ,@(when (vop-parse-info-args parse)
863                       `((,n-info (vop-codegen-info ,n-vop))
864                         ,@(mapcar (lambda (x) `(,x (pop ,n-info)))
865                                   (vop-parse-info-args parse))))
866                   ,@(when (vop-parse-variant-vars parse)
867                       `((,n-variant (vop-info-variant (vop-info ,n-vop)))
868                         ,@(mapcar (lambda (x) `(,x (pop ,n-variant)))
869                                   (vop-parse-variant-vars parse))))
870                   ,@(when (vop-parse-node-var parse)
871                       `((,(vop-parse-node-var parse) (vop-node ,n-vop))))
872                   ,@(binds))
873            (declare (ignore ,@(vop-parse-ignores parse)))
874            ,@(loads)
875            (sb!assem:assemble (*code-segment* ,n-vop)
876                               ,@(vop-parse-body parse))
877            ,@(saves))))))
878 \f
879 ;;; Given a list of operand specifications as given to DEFINE-VOP,
880 ;;; return a list of OPERAND-PARSE structures describing the fixed
881 ;;; operands, and a single OPERAND-PARSE describing any more operand.
882 ;;; If we are inheriting a VOP, we default attributes to the inherited
883 ;;; operand of the same name.
884 (defun !parse-vop-operands (parse specs kind)
885   (declare (list specs)
886            (type (member :argument :result) kind))
887   (let ((num -1)
888         (more nil))
889     (collect ((operands))
890       (dolist (spec specs)
891         (unless (and (consp spec) (symbolp (first spec)) (oddp (length spec)))
892           (error "malformed operand specifier: ~S" spec))
893         (when more
894           (error "The MORE operand isn't the last operand: ~S" specs))
895         (let* ((name (first spec))
896                (old (if (vop-parse-inherits parse)
897                         (find-operand name
898                                       (vop-parse-or-lose
899                                        (vop-parse-inherits parse))
900                                       (list kind)
901                                       nil)
902                         nil))
903                (res (if old
904                         (make-operand-parse
905                          :name name
906                          :kind kind
907                          :target (operand-parse-target old)
908                          :born (operand-parse-born old)
909                          :dies (operand-parse-dies old)
910                          :scs (operand-parse-scs old)
911                          :load-tn (operand-parse-load-tn old)
912                          :load (operand-parse-load old))
913                         (ecase kind
914                           (:argument
915                            (make-operand-parse
916                             :name (first spec)
917                             :kind :argument
918                             :born (parse-time-spec :load)
919                             :dies (parse-time-spec `(:argument ,(incf num)))))
920                           (:result
921                            (make-operand-parse
922                             :name (first spec)
923                             :kind :result
924                             :born (parse-time-spec `(:result ,(incf num)))
925                             :dies (parse-time-spec :save)))))))
926           (do ((key (rest spec) (cddr key)))
927               ((null key))
928             (let ((value (second key)))
929               (case (first key)
930                 (:scs
931                  (aver (typep value 'list))
932                  (setf (operand-parse-scs res) (remove-duplicates value)))
933                 (:load-tn
934                  (aver (typep value 'symbol))
935                  (setf (operand-parse-load-tn res) value))
936                 (:load-if
937                  (setf (operand-parse-load res) value))
938                 (:more
939                  (aver (typep value 'boolean))
940                  (setf (operand-parse-kind res)
941                        (if (eq kind :argument) :more-argument :more-result))
942                  (setf (operand-parse-load res) nil)
943                  (setq more res))
944                 (:target
945                  (aver (typep value 'symbol))
946                  (setf (operand-parse-target res) value))
947                 (:from
948                  (unless (eq kind :result)
949                    (error "can only specify :FROM in a result: ~S" spec))
950                  (setf (operand-parse-born res) (parse-time-spec value)))
951                 (:to
952                  (unless (eq kind :argument)
953                    (error "can only specify :TO in an argument: ~S" spec))
954                  (setf (operand-parse-dies res) (parse-time-spec value)))
955                 (t
956                  (error "unknown keyword in operand specifier: ~S" spec)))))
957
958           (cond ((not more)
959                  (operands res))
960                 ((operand-parse-target more)
961                  (error "cannot specify :TARGET in a :MORE operand"))
962                 ((operand-parse-load more)
963                  (error "cannot specify :LOAD-IF in a :MORE operand")))))
964       (values (the list (operands)) more))))
965 \f
966 ;;; Parse a temporary specification, putting the OPERAND-PARSE
967 ;;; structures in the PARSE structure.
968 (defun parse-temporary (spec parse)
969   (declare (list spec)
970            (type vop-parse parse))
971   (let ((len (length spec)))
972     (unless (>= len 2)
973       (error "malformed temporary spec: ~S" spec))
974     (unless (listp (second spec))
975       (error "malformed options list: ~S" (second spec)))
976     (unless (evenp (length (second spec)))
977       (error "odd number of arguments in keyword options: ~S" spec))
978     (unless (consp (cddr spec))
979       (warn "temporary spec allocates no temps:~%  ~S" spec))
980     (dolist (name (cddr spec))
981       (unless (symbolp name)
982         (error "bad temporary name: ~S" name))
983       (let ((res (make-operand-parse :name name
984                                      :kind :temporary
985                                      :temp-temp (gensym)
986                                      :born (parse-time-spec :load)
987                                      :dies (parse-time-spec :save))))
988         (do ((opt (second spec) (cddr opt)))
989             ((null opt))
990           (case (first opt)
991             (:target
992              (setf (operand-parse-target res)
993                    (vop-spec-arg opt 'symbol 1 nil)))
994             (:sc
995              (setf (operand-parse-sc res)
996                    (vop-spec-arg opt 'symbol 1 nil)))
997             (:offset
998              (let ((offset (eval (second opt))))
999                (aver (typep offset 'unsigned-byte))
1000                (setf (operand-parse-offset res) offset)))
1001             (:from
1002              (setf (operand-parse-born res) (parse-time-spec (second opt))))
1003             (:to
1004              (setf (operand-parse-dies res) (parse-time-spec (second opt))))
1005             ;; backward compatibility...
1006             (:scs
1007              (let ((scs (vop-spec-arg opt 'list 1 nil)))
1008                (unless (= (length scs) 1)
1009                  (error "must specify exactly one SC for a temporary"))
1010                (setf (operand-parse-sc res) (first scs))))
1011             (:type)
1012             (t
1013              (error "unknown temporary option: ~S" opt))))
1014
1015         (unless (and (time-spec-order (operand-parse-dies res)
1016                                       (operand-parse-born res))
1017                      (not (time-spec-order (operand-parse-born res)
1018                                            (operand-parse-dies res))))
1019           (error "Temporary lifetime doesn't begin before it ends: ~S" spec))
1020
1021         (unless (operand-parse-sc res)
1022           (error "must specify :SC for all temporaries: ~S" spec))
1023
1024         (setf (vop-parse-temps parse)
1025               (cons res
1026                     (remove name (vop-parse-temps parse)
1027                             :key #'operand-parse-name))))))
1028   (values))
1029 \f
1030 ;;; the top level parse function: clobber PARSE to represent the
1031 ;;; specified options.
1032 (defun parse-define-vop (parse specs)
1033   (declare (type vop-parse parse) (list specs))
1034   (dolist (spec specs)
1035     (unless (consp spec)
1036       (error "malformed option specification: ~S" spec))
1037     (case (first spec)
1038       (:args
1039        (multiple-value-bind (fixed more)
1040            (!parse-vop-operands parse (rest spec) :argument)
1041          (setf (vop-parse-args parse) fixed)
1042          (setf (vop-parse-more-args parse) more)))
1043       (:results
1044        (multiple-value-bind (fixed more)
1045            (!parse-vop-operands parse (rest spec) :result)
1046          (setf (vop-parse-results parse) fixed)
1047          (setf (vop-parse-more-results parse) more))
1048        (setf (vop-parse-conditional-p parse) nil))
1049       (:conditional
1050        (setf (vop-parse-result-types parse) ())
1051        (setf (vop-parse-results parse) ())
1052        (setf (vop-parse-more-results parse) nil)
1053        (setf (vop-parse-conditional-p parse) t))
1054       (:temporary
1055        (parse-temporary spec parse))
1056       (:generator
1057        (setf (vop-parse-cost parse)
1058              (vop-spec-arg spec 'unsigned-byte 1 nil))
1059        (setf (vop-parse-body parse) (cddr spec)))
1060       (:effects
1061        (setf (vop-parse-effects parse) (rest spec)))
1062       (:affected
1063        (setf (vop-parse-affected parse) (rest spec)))
1064       (:info
1065        (setf (vop-parse-info-args parse) (rest spec)))
1066       (:ignore
1067        (setf (vop-parse-ignores parse) (rest spec)))
1068       (:variant
1069        (setf (vop-parse-variant parse) (rest spec)))
1070       (:variant-vars
1071        (let ((vars (rest spec)))
1072          (setf (vop-parse-variant-vars parse) vars)
1073          (setf (vop-parse-variant parse)
1074                (make-list (length vars) :initial-element nil))))
1075       (:variant-cost
1076        (setf (vop-parse-cost parse) (vop-spec-arg spec 'unsigned-byte)))
1077       (:vop-var
1078        (setf (vop-parse-vop-var parse) (vop-spec-arg spec 'symbol)))
1079       (:move-args
1080        (setf (vop-parse-move-args parse)
1081              (vop-spec-arg spec '(member nil :local-call :full-call
1082                                          :known-return))))
1083       (:node-var
1084        (setf (vop-parse-node-var parse) (vop-spec-arg spec 'symbol)))
1085       (:note
1086        (setf (vop-parse-note parse) (vop-spec-arg spec '(or string null))))
1087       (:arg-types
1088        (setf (vop-parse-arg-types parse)
1089              (!parse-vop-operand-types (rest spec) t)))
1090       (:result-types
1091        (setf (vop-parse-result-types parse)
1092              (!parse-vop-operand-types (rest spec) nil)))
1093       (:translate
1094        (setf (vop-parse-translate parse) (rest spec)))
1095       (:guard
1096        (setf (vop-parse-guard parse) (vop-spec-arg spec t)))
1097       ;; FIXME: :LTN-POLICY would be a better name for this. It would
1098       ;; probably be good to leave it unchanged for a while, though,
1099       ;; at least until the first port to some other architecture,
1100       ;; since the renaming would be a change to the interface between
1101       (:policy
1102        (setf (vop-parse-ltn-policy parse)
1103              (vop-spec-arg spec 'ltn-policy)))
1104       (:save-p
1105        (setf (vop-parse-save-p parse)
1106              (vop-spec-arg spec
1107                            '(member t nil :compute-only :force-to-stack))))
1108       (t
1109        (error "unknown option specifier: ~S" (first spec)))))
1110   (values))
1111 \f
1112 ;;;; making costs and restrictions
1113
1114 ;;; Given an operand, returns two values:
1115 ;;; 1. A SC-vector of the cost for the operand being in that SC,
1116 ;;;    including both the costs for move functions and coercion VOPs.
1117 ;;; 2. A SC-vector holding the SC that we load into, for any SC
1118 ;;;    that we can directly load from.
1119 ;;;
1120 ;;; In both vectors, unused entries are NIL. LOAD-P specifies the
1121 ;;; direction: if true, we are loading, if false we are saving.
1122 (defun compute-loading-costs (op load-p)
1123   (declare (type operand-parse op))
1124   (let ((scs (operand-parse-scs op))
1125         (costs (make-array sc-number-limit :initial-element nil))
1126         (load-scs (make-array sc-number-limit :initial-element nil)))
1127     (dolist (sc-name scs)
1128       (let* ((load-sc (meta-sc-or-lose sc-name))
1129              (load-scn (sc-number load-sc)))
1130         (setf (svref costs load-scn) 0)
1131         (setf (svref load-scs load-scn) t)
1132         (dolist (op-sc (append (when load-p
1133                                  (sc-constant-scs load-sc))
1134                                (sc-alternate-scs load-sc)))
1135           (let* ((op-scn (sc-number op-sc))
1136                  (load (if load-p
1137                            (aref (sc-load-costs load-sc) op-scn)
1138                            (aref (sc-load-costs op-sc) load-scn))))
1139             (unless load
1140               (error "no move function defined to move ~:[from~;to~] SC ~
1141                       ~S~%~:[to~;from~] alternate or constant SC ~S"
1142                      load-p sc-name load-p (sc-name op-sc)))
1143
1144             (let ((op-cost (svref costs op-scn)))
1145               (when (or (not op-cost) (< load op-cost))
1146                 (setf (svref costs op-scn) load)))
1147
1148             (let ((op-load (svref load-scs op-scn)))
1149               (unless (eq op-load t)
1150                 (pushnew load-scn (svref load-scs op-scn))))))
1151
1152         (dotimes (i sc-number-limit)
1153           (unless (svref costs i)
1154             (let ((op-sc (svref *backend-meta-sc-numbers* i)))
1155               (when op-sc
1156                 (let ((cost (if load-p
1157                                 (svref (sc-move-costs load-sc) i)
1158                                 (svref (sc-move-costs op-sc) load-scn))))
1159                   (when cost
1160                     (setf (svref costs i) cost)))))))))
1161
1162     (values costs load-scs)))
1163
1164 (defparameter *no-costs*
1165   (make-array sc-number-limit :initial-element 0))
1166
1167 (defparameter *no-loads*
1168   (make-array sc-number-limit :initial-element t))
1169
1170 ;;; Pick off the case of operands with no restrictions.
1171 (defun compute-loading-costs-if-any (op load-p)
1172   (declare (type operand-parse op))
1173   (if (operand-parse-scs op)
1174       (compute-loading-costs op load-p)
1175       (values *no-costs* *no-loads*)))
1176
1177 (defun compute-costs-and-restrictions-list (ops load-p)
1178   (declare (list ops))
1179   (collect ((costs)
1180             (scs))
1181     (dolist (op ops)
1182       (multiple-value-bind (costs scs) (compute-loading-costs-if-any op load-p)
1183         (costs costs)
1184         (scs scs)))
1185     (values (costs) (scs))))
1186
1187 (defun make-costs-and-restrictions (parse)
1188   (multiple-value-bind (arg-costs arg-scs)
1189       (compute-costs-and-restrictions-list (vop-parse-args parse) t)
1190     (multiple-value-bind (result-costs result-scs)
1191         (compute-costs-and-restrictions-list (vop-parse-results parse) nil)
1192       `(
1193         :cost ,(vop-parse-cost parse)
1194         
1195         :arg-costs ',arg-costs
1196         :arg-load-scs ',arg-scs
1197         :result-costs ',result-costs
1198         :result-load-scs ',result-scs
1199         
1200         :more-arg-costs
1201         ',(if (vop-parse-more-args parse)
1202               (compute-loading-costs-if-any (vop-parse-more-args parse) t)
1203               nil)
1204         
1205         :more-result-costs
1206         ',(if (vop-parse-more-results parse)
1207               (compute-loading-costs-if-any (vop-parse-more-results parse) nil)
1208               nil)))))
1209 \f
1210 ;;;; operand checking and stuff
1211
1212 ;;; Given a list of arg/result restrictions, check for valid syntax
1213 ;;; and convert to canonical form.
1214 (defun !parse-vop-operand-types (specs args-p)
1215   (declare (list specs))
1216   (labels ((parse-operand-type (spec)
1217              (cond ((eq spec '*) spec)
1218                    ((symbolp spec)
1219                     (let ((alias (gethash spec
1220                                           *backend-primitive-type-aliases*)))
1221                       (if alias
1222                           (parse-operand-type alias)
1223                           `(:or ,spec))))
1224                    ((atom spec)
1225                     (error "bad thing to be a operand type: ~S" spec))
1226                    (t
1227                     (case (first spec)
1228                       (:or
1229                        (collect ((results))
1230                          (results :or)
1231                          (dolist (item (cdr spec))
1232                            (unless (symbolp item)
1233                              (error "bad PRIMITIVE-TYPE name in ~S: ~S"
1234                                     spec item))
1235                            (let ((alias
1236                                   (gethash item
1237                                            *backend-primitive-type-aliases*)))
1238                              (if alias
1239                                  (let ((alias (parse-operand-type alias)))
1240                                    (unless (eq (car alias) :or)
1241                                      (error "can't include primitive-type ~
1242                                              alias ~S in an :OR restriction: ~S"
1243                                             item spec))
1244                                    (dolist (x (cdr alias))
1245                                      (results x)))
1246                                  (results item))))
1247                          (remove-duplicates (results)
1248                                             :test #'eq
1249                                             :start 1)))
1250                       (:constant
1251                        (unless args-p
1252                          (error "can't :CONSTANT for a result"))
1253                        (unless (= (length spec) 2)
1254                          (error "bad :CONSTANT argument type spec: ~S" spec))
1255                        spec)
1256                       (t
1257                        (error "bad thing to be a operand type: ~S" spec)))))))
1258     (mapcar #'parse-operand-type specs)))
1259
1260 ;;; Check the consistency of Op's Sc restrictions with the specified
1261 ;;; primitive-type restriction. :CONSTANT operands have already been
1262 ;;; filtered out, so only :OR and * restrictions are left.
1263 ;;;
1264 ;;; We check that every representation allowed by the type can be
1265 ;;; directly loaded into some SC in the restriction, and that the type
1266 ;;; allows every SC in the restriction. With *, we require that T
1267 ;;; satisfy the first test, and omit the second.
1268 (defun check-operand-type-scs (parse op type load-p)
1269   (declare (type vop-parse parse) (type operand-parse op))
1270   (let ((ptypes (if (eq type '*) (list t) (rest type)))
1271         (scs (operand-parse-scs op)))
1272     (when scs
1273       (multiple-value-bind (costs load-scs) (compute-loading-costs op load-p)
1274         (declare (ignore costs))
1275         (dolist (ptype ptypes)
1276           (unless (dolist (rep (primitive-type-scs
1277                                 (meta-primitive-type-or-lose ptype))
1278                                nil)
1279                     (when (svref load-scs rep) (return t)))
1280             (error "In the ~A ~:[result~;argument~] to VOP ~S,~@
1281                     none of the SCs allowed by the operand type ~S can ~
1282                     directly be loaded~@
1283                     into any of the restriction's SCs:~%  ~S~:[~;~@
1284                     [* type operand must allow T's SCs.]~]"
1285                    (operand-parse-name op) load-p (vop-parse-name parse)
1286                    ptype
1287                    scs (eq type '*)))))
1288
1289       (dolist (sc scs)
1290         (unless (or (eq type '*)
1291                     (dolist (ptype ptypes nil)
1292                       (when (meta-sc-allowed-by-primitive-type
1293                              (meta-sc-or-lose sc)
1294                              (meta-primitive-type-or-lose ptype))
1295                         (return t))))
1296           (warn "~:[Result~;Argument~] ~A to VOP ~S~@
1297                  has SC restriction ~S which is ~
1298                  not allowed by the operand type:~%  ~S"
1299                 load-p (operand-parse-name op) (vop-parse-name parse)
1300                 sc type)))))
1301
1302   (values))
1303
1304 ;;; If the operand types are specified, then check the number specified
1305 ;;; against the number of defined operands.
1306 (defun check-operand-types (parse ops more-op types load-p)
1307   (declare (type vop-parse parse) (list ops)
1308            (type (or list (member :unspecified)) types)
1309            (type (or operand-parse null) more-op))
1310   (unless (eq types :unspecified)
1311     (let ((num (+ (length ops) (if more-op 1 0))))
1312       (unless (= (count-if-not (lambda (x)
1313                                  (and (consp x)
1314                                       (eq (car x) :constant)))
1315                                types)
1316                  num)
1317         (error "expected ~W ~:[result~;argument~] type~P: ~S"
1318                num load-p types num)))
1319
1320     (when more-op
1321       (let ((mtype (car (last types))))
1322         (when (and (consp mtype) (eq (first mtype) :constant))
1323           (error "can't use :CONSTANT on VOP more args")))))
1324
1325   (when (vop-parse-translate parse)
1326     (let ((types (specify-operand-types types ops more-op)))
1327       (mapc (lambda (x y)
1328               (check-operand-type-scs parse x y load-p))
1329             (if more-op (butlast ops) ops)
1330             (remove-if (lambda (x)
1331                          (and (consp x)
1332                               (eq (car x) ':constant)))
1333                        (if more-op (butlast types) types)))))
1334
1335   (values))
1336
1337 ;;; Compute stuff that can only be computed after we are done parsing
1338 ;;; everying. We set the VOP-PARSE-OPERANDS, and do various error checks.
1339 (defun !grovel-vop-operands (parse)
1340   (declare (type vop-parse parse))
1341
1342   (setf (vop-parse-operands parse)
1343         (append (vop-parse-args parse)
1344                 (if (vop-parse-more-args parse)
1345                     (list (vop-parse-more-args parse)))
1346                 (vop-parse-results parse)
1347                 (if (vop-parse-more-results parse)
1348                     (list (vop-parse-more-results parse)))
1349                 (vop-parse-temps parse)))
1350
1351   (check-operand-types parse
1352                        (vop-parse-args parse)
1353                        (vop-parse-more-args parse)
1354                        (vop-parse-arg-types parse)
1355                        t)
1356
1357   (check-operand-types parse
1358                        (vop-parse-results parse)
1359                        (vop-parse-more-results parse)
1360                        (vop-parse-result-types parse)
1361                        nil)
1362
1363   (values))
1364 \f
1365 ;;;; function translation stuff
1366
1367 ;;; Return forms to establish this VOP as a IR2 translation template
1368 ;;; for the :TRANSLATE functions specified in the VOP-PARSE. We also
1369 ;;; set the PREDICATE attribute for each translated function when the
1370 ;;; VOP is conditional, causing IR1 conversion to ensure that a call
1371 ;;; to the translated is always used in a predicate position.
1372 (defun !set-up-fun-translation (parse n-template)
1373   (declare (type vop-parse parse))
1374   (mapcar (lambda (name)
1375             `(let ((info (fun-info-or-lose ',name)))
1376                (setf (fun-info-templates info)
1377                      (adjoin-template ,n-template (fun-info-templates info)))
1378                ,@(when (vop-parse-conditional-p parse)
1379                    '((setf (fun-info-attributes info)
1380                            (attributes-union
1381                             (ir1-attributes predicate)
1382                             (fun-info-attributes info)))))))
1383           (vop-parse-translate parse)))
1384
1385 ;;; Return a form that can be evaluated to get the TEMPLATE operand type
1386 ;;; restriction from the given specification.
1387 (defun make-operand-type (type)
1388   (cond ((eq type '*) ''*)
1389         ((symbolp type)
1390          ``(:or ,(primitive-type-or-lose ',type)))
1391         (t
1392          (ecase (first type)
1393            (:or
1394             ``(:or ,,@(mapcar (lambda (type)
1395                                 `(primitive-type-or-lose ',type))
1396                               (rest type))))
1397            (:constant
1398             ``(:constant ,#'(lambda (x)
1399                               (typep x ',(second type)))
1400                          ,',(second type)))))))
1401
1402 (defun specify-operand-types (types ops more-ops)
1403   (if (eq types :unspecified)
1404       (make-list (+ (length ops) (if more-ops 1 0)) :initial-element '*)
1405       types))
1406
1407 ;;; Return a list of forms to use as &KEY args to MAKE-VOP-INFO for
1408 ;;; setting up the template argument and result types. Here we make an
1409 ;;; initial dummy TEMPLATE-TYPE, since it is awkward to compute the
1410 ;;; type until the template has been made.
1411 (defun make-vop-info-types (parse)
1412   (let* ((more-args (vop-parse-more-args parse))
1413          (all-args (specify-operand-types (vop-parse-arg-types parse)
1414                                           (vop-parse-args parse)
1415                                           more-args))
1416          (args (if more-args (butlast all-args) all-args))
1417          (more-arg (when more-args (car (last all-args))))
1418          (more-results (vop-parse-more-results parse))
1419          (all-results (specify-operand-types (vop-parse-result-types parse)
1420                                              (vop-parse-results parse)
1421                                              more-results))
1422          (results (if more-results (butlast all-results) all-results))
1423          (more-result (when more-results (car (last all-results))))
1424          (conditional (vop-parse-conditional-p parse)))
1425
1426     `(:type (specifier-type '(function () nil))
1427       :arg-types (list ,@(mapcar #'make-operand-type args))
1428       :more-args-type ,(when more-args (make-operand-type more-arg))
1429       :result-types ,(if conditional
1430                          :conditional
1431                          `(list ,@(mapcar #'make-operand-type results)))
1432       :more-results-type ,(when more-results
1433                             (make-operand-type more-result)))))
1434 \f
1435 ;;;; setting up VOP-INFO
1436
1437 (eval-when (:compile-toplevel :load-toplevel :execute)
1438   (defparameter *slot-inherit-alist*
1439     '((:generator-function . vop-info-generator-function))))
1440
1441 ;;; This is something to help with inheriting VOP-INFO slots. We
1442 ;;; return a keyword/value pair that can be passed to the constructor.
1443 ;;; SLOT is the keyword name of the slot, Parse is a form that
1444 ;;; evaluates to the VOP-PARSE structure for the VOP inherited. If
1445 ;;; PARSE is NIL, then we do nothing. If the TEST form evaluates to
1446 ;;; true, then we return a form that selects the named slot from the
1447 ;;; VOP-INFO structure corresponding to PARSE. Otherwise, we return
1448 ;;; the FORM so that the slot is recomputed.
1449 (defmacro inherit-vop-info (slot parse test form)
1450   `(if (and ,parse ,test)
1451        (list ,slot `(,',(or (cdr (assoc slot *slot-inherit-alist*))
1452                             (error "unknown slot ~S" slot))
1453                      (template-or-lose ',(vop-parse-name ,parse))))
1454        (list ,slot ,form)))
1455
1456 ;;; Return a form that creates a VOP-INFO structure which describes VOP.
1457 (defun set-up-vop-info (iparse parse)
1458   (declare (type vop-parse parse) (type (or vop-parse null) iparse))
1459   (let ((same-operands
1460          (and iparse
1461               (equal (vop-parse-operands parse)
1462                      (vop-parse-operands iparse))
1463               (equal (vop-parse-info-args iparse)
1464                      (vop-parse-info-args parse))))
1465         (variant (vop-parse-variant parse)))
1466
1467     (let ((nvars (length (vop-parse-variant-vars parse))))
1468       (unless (= (length variant) nvars)
1469         (error "expected ~W variant values: ~S" nvars variant)))
1470
1471     `(make-vop-info
1472       :name ',(vop-parse-name parse)
1473       ,@(make-vop-info-types parse)
1474       :guard ,(when (vop-parse-guard parse)
1475                 `(lambda () ,(vop-parse-guard parse)))
1476       :note ',(vop-parse-note parse)
1477       :info-arg-count ,(length (vop-parse-info-args parse))
1478       :ltn-policy ',(vop-parse-ltn-policy parse)
1479       :save-p ',(vop-parse-save-p parse)
1480       :move-args ',(vop-parse-move-args parse)
1481       :effects (vop-attributes ,@(vop-parse-effects parse))
1482       :affected (vop-attributes ,@(vop-parse-affected parse))
1483       ,@(make-costs-and-restrictions parse)
1484       ,@(make-emit-function-and-friends parse)
1485       ,@(inherit-vop-info :generator-function iparse
1486           (and same-operands
1487                (equal (vop-parse-body parse) (vop-parse-body iparse)))
1488           (unless (eq (vop-parse-body parse) :unspecified)
1489             (make-generator-function parse)))
1490       :variant (list ,@variant))))
1491 \f
1492 ;;; Define the symbol NAME to be a Virtual OPeration in the compiler.
1493 ;;; If specified, INHERITS is the name of a VOP that we default
1494 ;;; unspecified information from. Each SPEC is a list beginning with a
1495 ;;; keyword indicating the interpretation of the other forms in the
1496 ;;; SPEC:
1497 ;;;
1498 ;;; :ARGS {(Name {Key Value}*)}*
1499 ;;; :RESULTS {(Name {Key Value}*)}*
1500 ;;;     The Args and Results are specifications of the operand TNs passed
1501 ;;;     to the VOP. If there is an inherited VOP, any unspecified options
1502 ;;;     are defaulted from the inherited argument (or result) of the same
1503 ;;;     name. The following operand options are defined:
1504 ;;;
1505 ;;;     :SCs (SC*)
1506 ;;;         :SCs specifies good SCs for this operand. Other SCs will
1507 ;;;         be penalized according to move costs. A load TN will be
1508 ;;;         allocated if necessary, guaranteeing that the operand is
1509 ;;;         always one of the specified SCs.
1510 ;;;
1511 ;;;     :LOAD-TN Load-Name
1512 ;;;         Load-Name is bound to the load TN allocated for this
1513 ;;;         operand, or to NIL if no load TN was allocated.
1514 ;;;
1515 ;;;     :LOAD-IF EXPRESSION
1516 ;;;         Controls whether automatic operand loading is done.
1517 ;;;         EXPRESSION is evaluated with the fixed operand TNs bound.
1518 ;;;         If EXPRESSION is true,then loading is done and the variable
1519 ;;;         is bound to the load TN in the generator body. Otherwise,
1520 ;;;         loading is not done, and the variable is bound to the actual
1521 ;;;         operand.
1522 ;;;
1523 ;;;     :MORE T-or-NIL
1524 ;;;         If specified, NAME is bound to the TN-REF for the first
1525 ;;;         argument or result following the fixed arguments or results.
1526 ;;;         A :MORE operand must appear last, and cannot be targeted or
1527 ;;;         restricted.
1528 ;;;
1529 ;;;     :TARGET Operand
1530 ;;;         This operand is targeted to the named operand, indicating a
1531 ;;;         desire to pack in the same location. Not legal for results.
1532 ;;;
1533 ;;;     :FROM Time-Spec
1534 ;;;     :TO Time-Spec
1535 ;;;         Specify the beginning or end of the operand's lifetime.
1536 ;;;         :FROM can only be used with results, and :TO only with
1537 ;;;         arguments. The default for the N'th argument/result is
1538 ;;;         (:ARGUMENT N)/(:RESULT N). These options are necessary
1539 ;;;         primarily when operands are read or written out of order.
1540 ;;;
1541 ;;; :CONDITIONAL
1542 ;;;     This is used in place of :RESULTS with conditional branch VOPs.
1543 ;;;     There are no result values: the result is a transfer of control.
1544 ;;;     The target label is passed as the first :INFO arg. The second
1545 ;;;     :INFO arg is true if the sense of the test should be negated.
1546 ;;;     A side effect is to set the PREDICATE attribute for functions
1547 ;;;     in the :TRANSLATE option.
1548 ;;;
1549 ;;; :TEMPORARY ({Key Value}*) Name*
1550 ;;;     Allocate a temporary TN for each Name, binding that variable to
1551 ;;;     the TN within the body of the generators. In addition to :TARGET
1552 ;;;     (which is is the same as for operands), the following options are
1553 ;;;     defined:
1554 ;;;
1555 ;;;     :SC SC-Name
1556 ;;;     :OFFSET SB-Offset
1557 ;;;         Force the temporary to be allocated in the specified SC
1558 ;;;         with the specified offset. Offset is evaluated at
1559 ;;;         macroexpand time. If Offset is emitted, the register
1560 ;;;         allocator chooses a free location in SC. If both SC and
1561 ;;;         Offset are omitted, then the temporary is packed according
1562 ;;;         to its primitive type.
1563 ;;;
1564 ;;;     :FROM Time-Spec
1565 ;;;     :TO Time-Spec
1566 ;;;         Similar to the argument/result option, this specifies the
1567 ;;;         start and end of the temporaries' lives. The defaults are
1568 ;;;         :LOAD and :SAVE, i.e. the duration of the VOP. The other
1569 ;;;         intervening phases are :ARGUMENT,:EVAL and :RESULT.
1570 ;;;         Non-zero sub-phases can be specified by a list, e.g. by
1571 ;;;         default the second argument's life ends at (:ARGUMENT 1).
1572 ;;;
1573 ;;; :GENERATOR Cost Form*
1574 ;;;     Specifies the translation into assembly code. Cost is the
1575 ;;;     estimated cost of the code emitted by this generator. The body
1576 ;;;     is arbitrary Lisp code that emits the assembly language
1577 ;;;     translation of the VOP. An ASSEMBLE form is wrapped around
1578 ;;;     the body, so code may be emitted by using the local INST macro.
1579 ;;;     During the evaluation of the body, the names of the operands
1580 ;;;     and temporaries are bound to the actual TNs.
1581 ;;;
1582 ;;; :EFFECTS Effect*
1583 ;;; :AFFECTED Effect*
1584 ;;;     Specifies the side effects that this VOP has and the side
1585 ;;;     effects that effect its execution. If unspecified, these
1586 ;;;     default to the worst case.
1587 ;;;
1588 ;;; :INFO Name*
1589 ;;;     Define some magic arguments that are passed directly to the code
1590 ;;;     generator. The corresponding trailing arguments to VOP or
1591 ;;;     %PRIMITIVE are stored in the VOP structure. Within the body
1592 ;;;     of the generators, the named variables are bound to these
1593 ;;;     values. Except in the case of :CONDITIONAL VOPs, :INFO arguments
1594 ;;;     cannot be specified for VOPS that are the direct translation
1595 ;;;     for a function (specified by :TRANSLATE).
1596 ;;;
1597 ;;; :IGNORE Name*
1598 ;;;     Causes the named variables to be declared IGNORE in the
1599 ;;;     generator body.
1600 ;;;
1601 ;;; :VARIANT Thing*
1602 ;;; :VARIANT-VARS Name*
1603 ;;;     These options provide a way to parameterize families of VOPs
1604 ;;;     that differ only trivially. :VARIANT makes the specified
1605 ;;;     evaluated Things be the "variant" associated with this VOP.
1606 ;;;     :VARIANT-VARS causes the named variables to be bound to the
1607 ;;;     corresponding Things within the body of the generator.
1608 ;;;
1609 ;;; :VARIANT-COST Cost
1610 ;;;     Specifies the cost of this VOP, overriding the cost of any 
1611 ;;;     inherited generator.
1612 ;;;
1613 ;;; :NOTE {String | NIL}
1614 ;;;     A short noun-like phrase describing what this VOP "does", i.e.
1615 ;;;     the implementation strategy. If supplied, efficiency notes will
1616 ;;;     be generated when type uncertainty prevents :TRANSLATE from
1617 ;;;     working. NIL inhibits any efficiency note.
1618 ;;;
1619 ;;; :ARG-TYPES    {* | PType | (:OR PType*) | (:CONSTANT Type)}*
1620 ;;; :RESULT-TYPES {* | PType | (:OR PType*)}*
1621 ;;;     Specify the template type restrictions used for automatic
1622 ;;;     translation. If there is a :MORE operand, the last type is the
1623 ;;;     more type. :CONSTANT specifies that the argument must be a
1624 ;;;     compile-time constant of the specified Lisp type. The constant
1625 ;;;     values of :CONSTANT arguments are passed as additional :INFO
1626 ;;;     arguments rather than as :ARGS.
1627 ;;;
1628 ;;; :TRANSLATE Name*
1629 ;;;     This option causes the VOP template to be entered as an IR2
1630 ;;;     translation for the named functions.
1631 ;;;
1632 ;;; :POLICY {:SMALL | :FAST | :SAFE | :FAST-SAFE}
1633 ;;;     Specifies the policy under which this VOP is the best translation.
1634 ;;;
1635 ;;; :GUARD Form
1636 ;;;     Specifies a Form that is evaluated in the global environment.
1637 ;;;     If form returns NIL, then emission of this VOP is prohibited
1638 ;;;     even when all other restrictions are met.
1639 ;;;
1640 ;;; :VOP-VAR Name
1641 ;;; :NODE-VAR Name
1642 ;;;     In the generator, bind the specified variable to the VOP or
1643 ;;;     the Node that generated this VOP.
1644 ;;;
1645 ;;; :SAVE-P {NIL | T | :COMPUTE-ONLY | :FORCE-TO-STACK}
1646 ;;;     Indicates how a VOP wants live registers saved.
1647 ;;;
1648 ;;; :MOVE-ARGS {NIL | :FULL-CALL | :LOCAL-CALL | :KNOWN-RETURN}
1649 ;;;     Indicates if and how the more args should be moved into a
1650 ;;;     different frame.
1651 (def!macro define-vop ((name &optional inherits) &rest specs)
1652   (declare (type symbol name))
1653   ;; Parse the syntax into a VOP-PARSE structure, and then expand into
1654   ;; code that creates the appropriate VOP-INFO structure at load time.
1655   ;; We implement inheritance by copying the VOP-PARSE structure for
1656   ;; the inherited structure.
1657   (let* ((inherited-parse (when inherits
1658                             (vop-parse-or-lose inherits)))
1659          (parse (if inherits
1660                     (copy-vop-parse inherited-parse)
1661                     (make-vop-parse)))
1662          (n-res (gensym)))
1663     (setf (vop-parse-name parse) name)
1664     (setf (vop-parse-inherits parse) inherits)
1665
1666     (parse-define-vop parse specs)
1667     (!grovel-vop-operands parse)
1668
1669     `(progn
1670        (eval-when (:compile-toplevel :load-toplevel :execute)
1671          (setf (gethash ',name *backend-parsed-vops*)
1672                ',parse))
1673
1674        (let ((,n-res ,(set-up-vop-info inherited-parse parse)))
1675          (setf (gethash ',name *backend-template-names*) ,n-res)
1676          (setf (template-type ,n-res)
1677                (specifier-type (template-type-specifier ,n-res)))
1678          ,@(!set-up-fun-translation parse n-res))
1679        ',name)))
1680 \f
1681 ;;;; emission macros
1682
1683 ;;; Return code to make a list of VOP arguments or results, linked by
1684 ;;; TN-REF-ACROSS. The first value is code, the second value is LET*
1685 ;;; forms, and the third value is a variable that evaluates to the
1686 ;;; head of the list, or NIL if there are no operands. Fixed is a list
1687 ;;; of forms that evaluate to TNs for the fixed operands. TN-REFS will
1688 ;;; be made for these operands according using the specified value of
1689 ;;; WRITE-P. More is an expression that evaluates to a list of TN-REFS
1690 ;;; that will be made the tail of the list. If it is constant NIL,
1691 ;;; then we don't bother to set the tail.
1692 (defun make-operand-list (fixed more write-p)
1693   (collect ((forms)
1694             (binds))
1695     (let ((n-head nil)
1696           (n-prev nil))
1697       (dolist (op fixed)
1698         (let ((n-ref (gensym)))
1699           (binds `(,n-ref (reference-tn ,op ,write-p)))
1700           (if n-prev
1701               (forms `(setf (tn-ref-across ,n-prev) ,n-ref))
1702               (setq n-head n-ref))
1703           (setq n-prev n-ref)))
1704
1705       (when more
1706         (let ((n-more (gensym)))
1707           (binds `(,n-more ,more))
1708           (if n-prev
1709               (forms `(setf (tn-ref-across ,n-prev) ,n-more))
1710               (setq n-head n-more))))
1711
1712       (values (forms) (binds) n-head))))
1713
1714 ;;; Emit-Template Node Block Template Args Results [Info]
1715 ;;;
1716 ;;; Call the emit function for TEMPLATE, linking the result in at the
1717 ;;; end of BLOCK.
1718 (defmacro emit-template (node block template args results &optional info)
1719   (let ((n-first (gensym))
1720         (n-last (gensym)))
1721     (once-only ((n-node node)
1722                 (n-block block)
1723                 (n-template template))
1724       `(multiple-value-bind (,n-first ,n-last)
1725            (funcall (template-emit-function ,n-template)
1726                     ,n-node ,n-block ,n-template ,args ,results
1727                     ,@(when info `(,info)))
1728          (insert-vop-sequence ,n-first ,n-last ,n-block nil)))))
1729
1730 ;;; VOP Name Node Block Arg* Info* Result*
1731 ;;;
1732 ;;; Emit the VOP (or other template) NAME at the end of the IR2-BLOCK
1733 ;;; BLOCK, using NODE for the source context. The interpretation of
1734 ;;; the remaining arguments depends on the number of operands of
1735 ;;; various kinds that are declared in the template definition. VOP
1736 ;;; cannot be used for templates that have more-args or more-results,
1737 ;;; since the number of arguments and results is indeterminate for
1738 ;;; these templates. Use VOP* instead.
1739 ;;;
1740 ;;; ARGS and RESULTS are the TNs that are to be referenced by the
1741 ;;; template as arguments and results. If the template has
1742 ;;; codegen-info arguments, then the appropriate number of INFO forms
1743 ;;; following the arguments are used for codegen info.
1744 (defmacro vop (name node block &rest operands)
1745   (let* ((parse (vop-parse-or-lose name))
1746          (arg-count (length (vop-parse-args parse)))
1747          (result-count (length (vop-parse-results parse)))
1748          (info-count (length (vop-parse-info-args parse)))
1749          (noperands (+ arg-count result-count info-count))
1750          (n-node (gensym))
1751          (n-block (gensym))
1752          (n-template (gensym)))
1753
1754     (when (or (vop-parse-more-args parse) (vop-parse-more-results parse))
1755       (error "cannot use VOP with variable operand count templates"))
1756     (unless (= noperands (length operands))
1757       (error "called with ~W operands, but was expecting ~W"
1758              (length operands) noperands))
1759
1760     (multiple-value-bind (acode abinds n-args)
1761         (make-operand-list (subseq operands 0 arg-count) nil nil)
1762       (multiple-value-bind (rcode rbinds n-results)
1763           (make-operand-list (subseq operands (+ arg-count info-count)) nil t)
1764
1765         (collect ((ibinds)
1766                   (ivars))
1767           (dolist (info (subseq operands arg-count (+ arg-count info-count)))
1768             (let ((temp (gensym)))
1769               (ibinds `(,temp ,info))
1770               (ivars temp)))
1771
1772           `(let* ((,n-node ,node)
1773                   (,n-block ,block)
1774                   (,n-template (template-or-lose ',name))
1775                   ,@abinds
1776                   ,@(ibinds)
1777                   ,@rbinds)
1778              ,@acode
1779              ,@rcode
1780              (emit-template ,n-node ,n-block ,n-template ,n-args
1781                             ,n-results
1782                             ,@(when (ivars)
1783                                 `((list ,@(ivars)))))
1784              (values)))))))
1785
1786 ;;; VOP* Name Node Block (Arg* More-Args) (Result* More-Results) Info*
1787 ;;;
1788 ;;; This is like VOP, but allows for emission of templates with
1789 ;;; arbitrary numbers of arguments, and for emission of templates
1790 ;;; using already-created TN-REF lists.
1791 ;;;
1792 ;;; The ARGS and RESULTS are TNs to be referenced as the first
1793 ;;; arguments and results to the template. More-Args and More-Results
1794 ;;; are heads of TN-REF lists that are added onto the end of the
1795 ;;; TN-REFS for the explicitly supplied operand TNs. The TN-REFS for
1796 ;;; the more operands must have the TN and WRITE-P slots correctly
1797 ;;; initialized.
1798 ;;;
1799 ;;; As with VOP, the INFO forms are evaluated and passed as codegen
1800 ;;; info arguments.
1801 (defmacro vop* (name node block args results &rest info)
1802   (declare (type cons args results))
1803   (let* ((parse (vop-parse-or-lose name))
1804          (arg-count (length (vop-parse-args parse)))
1805          (result-count (length (vop-parse-results parse)))
1806          (info-count (length (vop-parse-info-args parse)))
1807          (fixed-args (butlast args))
1808          (fixed-results (butlast results))
1809          (n-node (gensym))
1810          (n-block (gensym))
1811          (n-template (gensym)))
1812
1813     (unless (or (vop-parse-more-args parse)
1814                 (<= (length fixed-args) arg-count))
1815       (error "too many fixed arguments"))
1816     (unless (or (vop-parse-more-results parse)
1817                 (<= (length fixed-results) result-count))
1818       (error "too many fixed results"))
1819     (unless (= (length info) info-count)
1820       (error "expected ~W info args" info-count))
1821
1822     (multiple-value-bind (acode abinds n-args)
1823         (make-operand-list fixed-args (car (last args)) nil)
1824       (multiple-value-bind (rcode rbinds n-results)
1825           (make-operand-list fixed-results (car (last results)) t)
1826
1827         `(let* ((,n-node ,node)
1828                 (,n-block ,block)
1829                 (,n-template (template-or-lose ',name))
1830                 ,@abinds
1831                 ,@rbinds)
1832            ,@acode
1833            ,@rcode
1834            (emit-template ,n-node ,n-block ,n-template ,n-args ,n-results
1835                           ,@(when info
1836                               `((list ,@info))))
1837            (values))))))
1838 \f
1839 ;;;; miscellaneous macros
1840
1841 ;;; SC-Case TN {({(SC-Name*) | SC-Name | T} Form*)}*
1842 ;;;
1843 ;;; Case off of TN's SC. The first clause containing TN's SC is
1844 ;;; evaluated, returning the values of the last form. A clause
1845 ;;; beginning with T specifies a default. If it appears, it must be
1846 ;;; last. If no default is specified, and no clause matches, then an
1847 ;;; error is signalled.
1848 (def!macro sc-case (tn &rest forms)
1849   (let ((n-sc (gensym))
1850         (n-tn (gensym)))
1851     (collect ((clauses))
1852       (do ((cases forms (rest cases)))
1853           ((null cases)
1854            (clauses `(t (error "unknown SC to SC-CASE for ~S:~%  ~S" ,n-tn
1855                                (sc-name (tn-sc ,n-tn))))))
1856         (let ((case (first cases)))
1857           (when (atom case)
1858             (error "illegal SC-CASE clause: ~S" case))
1859           (let ((head (first case)))
1860             (when (eq head t)
1861               (when (rest cases)
1862                 (error "T case is not last in SC-CASE."))
1863               (clauses `(t nil ,@(rest case)))
1864               (return))
1865             (clauses `((or ,@(mapcar (lambda (x)
1866                                        `(eql ,(meta-sc-number-or-lose x)
1867                                              ,n-sc))
1868                                      (if (atom head) (list head) head)))
1869                        nil ,@(rest case))))))
1870
1871       `(let* ((,n-tn ,tn)
1872               (,n-sc (sc-number (tn-sc ,n-tn))))
1873          (cond ,@(clauses))))))
1874
1875 ;;; Return true if TNs SC is any of the named SCs, false otherwise.
1876 (defmacro sc-is (tn &rest scs)
1877   (once-only ((n-sc `(sc-number (tn-sc ,tn))))
1878     `(or ,@(mapcar (lambda (x)
1879                      `(eql ,n-sc ,(meta-sc-number-or-lose x)))
1880                    scs))))
1881
1882 ;;; Iterate over the IR2 blocks in component, in emission order.
1883 (defmacro do-ir2-blocks ((block-var component &optional result)
1884                          &body forms)
1885   `(do ((,block-var (block-info (component-head ,component))
1886                     (ir2-block-next ,block-var)))
1887        ((null ,block-var) ,result)
1888      ,@forms))
1889
1890 ;;; Iterate over all the TNs live at some point, with the live set
1891 ;;; represented by a local conflicts bit-vector and the IR2-BLOCK
1892 ;;; containing the location.
1893 (defmacro do-live-tns ((tn-var live block &optional result) &body body)
1894   (let ((n-conf (gensym))
1895         (n-bod (gensym))
1896         (i (gensym))
1897         (ltns (gensym)))
1898     (once-only ((n-live live)
1899                 (n-block block))
1900       `(block nil
1901          (flet ((,n-bod (,tn-var) ,@body))
1902            ;; Do component-live TNs.
1903            (dolist (,tn-var (ir2-component-component-tns
1904                              (component-info
1905                               (block-component
1906                                (ir2-block-block ,n-block)))))
1907              (,n-bod ,tn-var))
1908
1909            (let ((,ltns (ir2-block-local-tns ,n-block)))
1910              ;; Do TNs always-live in this block and live :MORE TNs.
1911              (do ((,n-conf (ir2-block-global-tns ,n-block)
1912                            (global-conflicts-next-blockwise ,n-conf)))
1913                  ((null ,n-conf))
1914                (when (or (eq (global-conflicts-kind ,n-conf) :live)
1915                          (let ((,i (global-conflicts-number ,n-conf)))
1916                            (and (eq (svref ,ltns ,i) :more)
1917                                 (not (zerop (sbit ,n-live ,i))))))
1918                  (,n-bod (global-conflicts-tn ,n-conf))))
1919              ;; Do TNs locally live in the designated live set.
1920              (dotimes (,i (ir2-block-local-tn-count ,n-block) ,result)
1921                (unless (zerop (sbit ,n-live ,i))
1922                  (let ((,tn-var (svref ,ltns ,i)))
1923                    (when (and ,tn-var (not (eq ,tn-var :more)))
1924                      (,n-bod ,tn-var)))))))))))
1925
1926 ;;; Iterate over all the IR2 blocks in PHYSENV, in emit order.
1927 (defmacro do-physenv-ir2-blocks ((block-var physenv &optional result)
1928                                  &body body)
1929   (once-only ((n-physenv physenv))
1930     (once-only ((n-first `(lambda-block (physenv-lambda ,n-physenv))))
1931       (once-only ((n-tail `(block-info
1932                             (component-tail
1933                              (block-component ,n-first)))))
1934         `(do ((,block-var (block-info ,n-first)
1935                           (ir2-block-next ,block-var)))
1936              ((or (eq ,block-var ,n-tail)
1937                   (not (eq (ir2-block-physenv ,block-var) ,n-physenv)))
1938               ,result)
1939            ,@body)))))