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