97be928e260dcfc82ffacb71d2390309b82d4441
[sbcl.git] / src / compiler / macros.lisp
1 ;;;; miscellaneous types and macros used in writing the compiler
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!C")
13
14 (declaim (special *wild-type* *universal-type* *compiler-error-context*))
15
16 ;;; An INLINEP value describes how a function is called. The values
17 ;;; have these meanings:
18 ;;;     NIL     No declaration seen: do whatever you feel like, but don't 
19 ;;;             dump an inline expansion.
20 ;;; :NOTINLINE  NOTINLINE declaration seen: always do full function call.
21 ;;;    :INLINE  INLINE declaration seen: save expansion, expanding to it 
22 ;;;             if policy favors.
23 ;;; :MAYBE-INLINE
24 ;;;             Retain expansion, but only use it opportunistically.
25 (deftype inlinep () '(member :inline :maybe-inline :notinline nil))
26 \f
27 ;;;; source-hacking defining forms
28
29 ;;; to be passed to PARSE-DEFMACRO when we want compiler errors
30 ;;; instead of real errors
31 #!-sb-fluid (declaim (inline convert-condition-into-compiler-error))
32 (defun convert-condition-into-compiler-error (datum &rest stuff)
33   (if (stringp datum)
34       (apply #'compiler-error datum stuff)
35       (compiler-error "~A"
36                       (if (symbolp datum)
37                           (apply #'make-condition datum stuff)
38                           datum))))
39
40 ;;; Parse a DEFMACRO-style lambda-list, setting things up so that a
41 ;;; compiler error happens if the syntax is invalid.
42 ;;;
43 ;;; Define a function that converts a special form or other magical
44 ;;; thing into IR1. LAMBDA-LIST is a defmacro style lambda list.
45 ;;; START-VAR and CONT-VAR are bound to the start and result
46 ;;; continuations for the resulting IR1. KIND is the function kind to
47 ;;; associate with NAME.
48 (defmacro def-ir1-translator (name (lambda-list start-var cont-var
49                                                 &key (kind :special-form))
50                                    &body body)
51   (let ((fn-name (symbolicate "IR1-CONVERT-" name))
52         (n-form (gensym))
53         (n-env (gensym)))
54     (multiple-value-bind (body decls doc)
55         (parse-defmacro lambda-list n-form body name "special form"
56                         :environment n-env
57                         :error-fun 'convert-condition-into-compiler-error)
58       `(progn
59          (declaim (ftype (function (continuation continuation t) (values))
60                          ,fn-name))
61          (defun ,fn-name (,start-var ,cont-var ,n-form)
62            (let ((,n-env *lexenv*))
63              ,@decls
64              ,body
65              (values)))
66          ,@(when doc
67              `((setf (fdocumentation ',name 'function) ,doc)))
68          ;; FIXME: Evidently "there can only be one!" -- we overwrite any
69          ;; other :IR1-CONVERT value. This deserves a warning, I think.
70          (setf (info :function :ir1-convert ',name) #',fn-name)
71          (setf (info :function :kind ',name) ,kind)
72          ;; It's nice to do this for error checking in the target
73          ;; SBCL, but it's not nice to do this when we're running in
74          ;; the cross-compilation host Lisp, which owns the
75          ;; SYMBOL-FUNCTION of its COMMON-LISP symbols.
76          #-sb-xc-host
77          ,@(when (eq kind :special-form)
78              `((setf (symbol-function ',name)
79                      (lambda (&rest rest)
80                        (declare (ignore rest))
81                        (error 'special-form-function
82                               :name ',name)))))))))
83
84 ;;; (This is similar to DEF-IR1-TRANSLATOR, except that we pass if the
85 ;;; syntax is invalid.)
86 ;;;
87 ;;; Define a macro-like source-to-source transformation for the
88 ;;; function NAME. A source transform may "pass" by returning a
89 ;;; non-nil second value. If the transform passes, then the form is
90 ;;; converted as a normal function call. If the supplied arguments are
91 ;;; not compatible with the specified LAMBDA-LIST, then the transform
92 ;;; automatically passes.
93 ;;;
94 ;;; Source transforms may only be defined for functions. Source
95 ;;; transformation is not attempted if the function is declared
96 ;;; NOTINLINE. Source transforms should not examine their arguments.
97 ;;; If it matters how the function is used, then DEFTRANSFORM should
98 ;;; be used to define an IR1 transformation.
99 ;;;
100 ;;; If the desirability of the transformation depends on the current
101 ;;; OPTIMIZE parameters, then the POLICY macro should be used to
102 ;;; determine when to pass.
103 (defmacro define-source-transform (name lambda-list &body body)
104   (let ((fn-name
105          (if (listp name)
106              (collect ((pieces))
107                (dolist (piece name)
108                  (pieces "-")
109                  (pieces piece))
110                (apply #'symbolicate "SOURCE-TRANSFORM" (pieces)))
111              (symbolicate "SOURCE-TRANSFORM-" name)))
112         (n-form (gensym))
113         (n-env (gensym)))
114     (multiple-value-bind (body decls)
115         (parse-defmacro lambda-list n-form body name "form"
116                         :environment n-env
117                         :error-fun `(lambda (&rest stuff)
118                                       (declare (ignore stuff))
119                                       (return-from ,fn-name
120                                         (values nil t))))
121       `(progn
122          (defun ,fn-name (,n-form)
123            (let ((,n-env *lexenv*))
124              ,@decls
125              ,body))
126          (setf (info :function :source-transform ',name) #',fn-name)))))
127 \f
128 ;;;; boolean attribute utilities
129 ;;;;
130 ;;;; We need to maintain various sets of boolean attributes for known
131 ;;;; functions and VOPs. To save space and allow for quick set
132 ;;;; operations, we represent the attributes as bits in a fixnum.
133
134 (deftype attributes () 'fixnum)
135
136 (eval-when (:compile-toplevel :load-toplevel :execute)
137
138 ;;; Given a list of attribute names and an alist that translates them
139 ;;; to masks, return the OR of the masks.
140 (defun compute-attribute-mask (names alist)
141   (collect ((res 0 logior))
142     (dolist (name names)
143       (let ((mask (cdr (assoc name alist))))
144         (unless mask
145           (error "unknown attribute name: ~S" name))
146         (res mask)))
147     (res)))
148
149 ) ; EVAL-WHEN
150
151 ;;; Define a new class of boolean attributes, with the attributes
152 ;;; having the specified ATTRIBUTE-NAMES. NAME is the name of the
153 ;;; class, which is used to generate some macros to manipulate sets of
154 ;;; the attributes:
155 ;;;
156 ;;;    NAME-attributep attributes attribute-name*
157 ;;;      Return true if one of the named attributes is present, false
158 ;;;      otherwise. When set with SETF, updates the place Attributes
159 ;;;      setting or clearing the specified attributes.
160 ;;;
161 ;;;    NAME-attributes attribute-name*
162 ;;;      Return a set of the named attributes.
163 ;;;
164 ;;; KLUDGE: This is expanded out twice, by cut-and-paste, in a
165 ;;;   (DEF!MACRO FOO (..) .. CL:GET-SETF-EXPANSION ..)
166 ;;;   #+SB-XC-HOST
167 ;;;   (SB!XC:DEFMACRO FOO (..) .. SB!XC:GET-SETF-EXPANSION ..)
168 ;;; arrangement, in order to get it to work in cross-compilation. This
169 ;;; duplication should be removed, perhaps by rewriting the macro in a
170 ;;; more cross-compiler-friendly way, or perhaps just by using some
171 ;;; (MACROLET ((FROB ..)) .. FROB .. FROB) form, but I don't want to
172 ;;; do it now, because the system isn't running yet, so it'd be too
173 ;;; hard to check that my changes were correct -- WHN 19990806
174 (def!macro def-boolean-attribute (name &rest attribute-names)
175
176   (let ((translations-name (symbolicate "*" name "-ATTRIBUTE-TRANSLATIONS*"))
177         (test-name (symbolicate name "-ATTRIBUTEP")))
178     (collect ((alist))
179       (do ((mask 1 (ash mask 1))
180            (names attribute-names (cdr names)))
181           ((null names))
182         (alist (cons (car names) mask)))
183
184       `(progn
185
186          (eval-when (:compile-toplevel :load-toplevel :execute)
187            (defparameter ,translations-name ',(alist)))
188
189          (defmacro ,test-name (attributes &rest attribute-names)
190            "Automagically generated boolean attribute test function. See
191             Def-Boolean-Attribute."
192            `(logtest ,(compute-attribute-mask attribute-names
193                                               ,translations-name)
194                      (the attributes ,attributes)))
195
196          (define-setf-expander ,test-name (place &rest attributes
197                                                  &environment env)
198            "Automagically generated boolean attribute setter. See
199             Def-Boolean-Attribute."
200            #-sb-xc-host (declare (type sb!c::lexenv env))
201            ;; FIXME: It would be better if &ENVIRONMENT arguments
202            ;; were automatically declared to have type LEXENV by the
203            ;; hairy-argument-handling code.
204            (multiple-value-bind (temps values stores set get)
205                (get-setf-expansion place env)
206              (when (cdr stores)
207                (error "multiple store variables for ~S" place))
208              (let ((newval (gensym))
209                    (n-place (gensym))
210                    (mask (compute-attribute-mask attributes
211                                                  ,translations-name)))
212                (values `(,@temps ,n-place)
213                        `(,@values ,get)
214                        `(,newval)
215                        `(let ((,(first stores)
216                                (if ,newval
217                                    (logior ,n-place ,mask)
218                                    (logand ,n-place ,(lognot mask)))))
219                           ,set
220                           ,newval)
221                        `(,',test-name ,n-place ,@attributes)))))
222
223          (defmacro ,(symbolicate name "-ATTRIBUTES") (&rest attribute-names)
224            "Automagically generated boolean attribute creation function. See
225             Def-Boolean-Attribute."
226            (compute-attribute-mask attribute-names ,translations-name))))))
227 ;;; #+SB-XC-HOST SB!XC:DEFMACRO version is in late-macros.lisp. -- WHN 19990806
228
229 ;;; And now for some gratuitous pseudo-abstraction...
230 ;;;
231 ;;; ATTRIBUTES-UNION 
232 ;;;   Return the union of all the sets of boolean attributes which are its
233 ;;;   arguments.
234 ;;; ATTRIBUTES-INTERSECTION
235 ;;;   Return the intersection of all the sets of boolean attributes which
236 ;;;   are its arguments.
237 ;;; ATTRIBUTES=
238 ;;;   True if the attributes present in Attr1 are identical to
239 ;;;   those in Attr2.
240 (defmacro attributes-union (&rest attributes)
241   `(the attributes
242         (logior ,@(mapcar (lambda (x) `(the attributes ,x)) attributes))))
243 (defmacro attributes-intersection (&rest attributes)
244   `(the attributes
245         (logand ,@(mapcar (lambda (x) `(the attributes ,x)) attributes))))
246 (declaim (ftype (function (attributes attributes) boolean) attributes=))
247 #!-sb-fluid (declaim (inline attributes=))
248 (defun attributes= (attr1 attr2)
249   (eql attr1 attr2))
250 \f
251 ;;;; lambda-list parsing utilities
252 ;;;;
253 ;;;; IR1 transforms, optimizers and type inferencers need to be able
254 ;;;; to parse the IR1 representation of a function call using a
255 ;;;; standard function lambda-list.
256
257 (eval-when (:compile-toplevel :load-toplevel :execute)
258
259 ;;; Given a DEFTRANSFORM-style lambda-list, generate code that parses
260 ;;; the arguments of a combination with respect to that lambda-list.
261 ;;; BODY is the the list of forms which are to be evaluated within the
262 ;;; bindings. ARGS is the variable that holds list of argument
263 ;;; continuations. ERROR-FORM is a form which is evaluated when the
264 ;;; syntax of the supplied arguments is incorrect or a non-constant
265 ;;; argument keyword is supplied. Defaults and other gunk are ignored.
266 ;;; The second value is a list of all the arguments bound. We make the
267 ;;; variables IGNORABLE so that we don't have to manually declare them
268 ;;; Ignore if their only purpose is to make the syntax work.
269 (defun parse-deftransform (lambda-list body args error-form)
270   (multiple-value-bind (req opt restp rest keyp keys allowp)
271       (parse-lambda-list lambda-list)
272     (let* ((min-args (length req))
273            (max-args (+ min-args (length opt)))
274            (n-keys (gensym)))
275       (collect ((binds)
276                 (vars)
277                 (pos 0 +)
278                 (keywords))
279         (dolist (arg req)
280           (vars arg)
281           (binds `(,arg (nth ,(pos) ,args)))
282           (pos 1))
283
284         (dolist (arg opt)
285           (let ((var (if (atom arg) arg (first  arg))))
286             (vars var)
287             (binds `(,var (nth ,(pos) ,args)))
288             (pos 1)))
289
290         (when restp
291           (vars rest)
292           (binds `(,rest (nthcdr ,(pos) ,args))))
293
294         (dolist (spec keys)
295           (if (or (atom spec) (atom (first spec)))
296               (let* ((var (if (atom spec) spec (first spec)))
297                      (key (keywordicate var)))
298                 (vars var)
299                 (binds `(,var (find-keyword-continuation ,n-keys ,key)))
300                 (keywords key))
301               (let* ((head (first spec))
302                      (var (second head))
303                      (key (first head)))
304                 (vars var)
305                 (binds `(,var (find-keyword-continuation ,n-keys ,key)))
306                 (keywords key))))
307
308         (let ((n-length (gensym))
309               (limited-legal (not (or restp keyp))))
310           (values
311            `(let ((,n-length (length ,args))
312                   ,@(when keyp `((,n-keys (nthcdr ,(pos) ,args)))))
313               (unless (and
314                        ;; FIXME: should be PROPER-LIST-OF-LENGTH-P
315                        ,(if limited-legal
316                             `(<= ,min-args ,n-length ,max-args)
317                             `(<= ,min-args ,n-length))
318                        ,@(when keyp
319                            (if allowp
320                                `((check-key-args-constant ,n-keys))
321                                `((check-transform-keys ,n-keys ',(keywords))))))
322                 ,error-form)
323               (let ,(binds)
324                 (declare (ignorable ,@(vars)))
325                 ,@body))
326            (vars)))))))
327
328 ) ; EVAL-WHEN
329 \f
330 ;;;; DEFTRANSFORM
331
332 ;;; Define an IR1 transformation for NAME. An IR1 transformation
333 ;;; computes a lambda that replaces the function variable reference
334 ;;; for the call. A transform may pass (decide not to transform the
335 ;;; call) by calling the GIVE-UP-IR1-TRANSFORM function. LAMBDA-LIST
336 ;;; both determines how the current call is parsed and specifies the
337 ;;; LAMBDA-LIST for the resulting lambda.
338 ;;;
339 ;;; We parse the call and bind each of the lambda-list variables to
340 ;;; the continuation which represents the value of the argument. When
341 ;;; parsing the call, we ignore the defaults, and always bind the
342 ;;; variables for unsupplied arguments to NIL. If a required argument
343 ;;; is missing, an unknown keyword is supplied, or an argument keyword
344 ;;; is not a constant, then the transform automatically passes. The
345 ;;; DECLARATIONS apply to the bindings made by DEFTRANSFORM at
346 ;;; transformation time, rather than to the variables of the resulting
347 ;;; lambda. Bound-but-not-referenced warnings are suppressed for the
348 ;;; lambda-list variables. The DOC-STRING is used when printing
349 ;;; efficiency notes about the defined transform.
350 ;;;
351 ;;; Normally, the body evaluates to a form which becomes the body of
352 ;;; an automatically constructed lambda. We make LAMBDA-LIST the
353 ;;; lambda-list for the lambda, and automatically insert declarations
354 ;;; of the argument and result types. If the second value of the body
355 ;;; is non-null, then it is a list of declarations which are to be
356 ;;; inserted at the head of the lambda. Automatic lambda generation
357 ;;; may be inhibited by explicitly returning a lambda from the body.
358 ;;;
359 ;;; The ARG-TYPES and RESULT-TYPE are used to create a function type
360 ;;; which the call must satisfy before transformation is attempted.
361 ;;; The function type specifier is constructed by wrapping (FUNCTION
362 ;;; ...) around these values, so the lack of a restriction may be
363 ;;; specified by omitting the argument or supplying *. The argument
364 ;;; syntax specified in the ARG-TYPES need not be the same as that in
365 ;;; the LAMBDA-LIST, but the transform will never happen if the
366 ;;; syntaxes can't be satisfied simultaneously. If there is an
367 ;;; existing transform for the same function that has the same type,
368 ;;; then it is replaced with the new definition.
369 ;;;
370 ;;; These are the legal keyword options:
371 ;;;   :RESULT - A variable which is bound to the result continuation.
372 ;;;   :NODE   - A variable which is bound to the combination node for the call.
373 ;;;   :POLICY - A form which is supplied to the POLICY macro to determine
374 ;;;             whether this transformation is appropriate. If the result
375 ;;;             is false, then the transform automatically gives up.
376 ;;;   :EVAL-NAME
377 ;;;           - The name and argument/result types are actually forms to be
378 ;;;             evaluated. Useful for getting closures that transform similar
379 ;;;             functions.
380 ;;;   :DEFUN-ONLY
381 ;;;           - Don't actually instantiate a transform, instead just DEFUN
382 ;;;             Name with the specified transform definition function. This
383 ;;;             may be later instantiated with %DEFTRANSFORM.
384 ;;;   :IMPORTANT
385 ;;;           - If supplied and non-NIL, note this transform as ``important,''
386 ;;;             which means efficiency notes will be generated when this
387 ;;;             transform fails even if INHIBIT-WARNINGS=SPEED (but not if
388 ;;;             INHIBIT-WARNINGS>SPEED).
389 (defmacro deftransform (name (lambda-list &optional (arg-types '*)
390                                           (result-type '*)
391                                           &key result policy node defun-only
392                                           eval-name important)
393                              &body body-decls-doc)
394   (when (and eval-name defun-only)
395     (error "can't specify both DEFUN-ONLY and EVAL-NAME"))
396   (multiple-value-bind (body decls doc) (parse-body body-decls-doc)
397     (let ((n-args (gensym))
398           (n-node (or node (gensym)))
399           (n-decls (gensym))
400           (n-lambda (gensym))
401           (decls-body `(,@decls ,@body)))
402       (multiple-value-bind (parsed-form vars)
403           (parse-deftransform lambda-list
404                               (if policy
405                                   `((unless (policy ,n-node ,policy)
406                                       (give-up-ir1-transform))
407                                     ,@decls-body)
408                                   body)
409                               n-args
410                               '(give-up-ir1-transform))
411         (let ((stuff
412                `((,n-node)
413                  (let* ((,n-args (basic-combination-args ,n-node))
414                         ,@(when result
415                             `((,result (node-cont ,n-node)))))
416                    (multiple-value-bind (,n-lambda ,n-decls)
417                        ,parsed-form
418                      (if (and (consp ,n-lambda) (eq (car ,n-lambda) 'lambda))
419                          ,n-lambda
420                        `(lambda ,',lambda-list
421                           (declare (ignorable ,@',vars))
422                           ,@,n-decls
423                           ,,n-lambda)))))))
424           (if defun-only
425               `(defun ,name ,@(when doc `(,doc)) ,@stuff)
426               `(%deftransform
427                 ,(if eval-name name `',name)
428                 ,(if eval-name
429                      ``(function ,,arg-types ,,result-type)
430                      `'(function ,arg-types ,result-type))
431                 (lambda ,@stuff)
432                 ,doc
433                 ,(if important t nil))))))))
434 \f
435 ;;;; DEFKNOWN and DEFOPTIMIZER
436
437 ;;; This macro should be the way that all implementation independent
438 ;;; information about functions is made known to the compiler.
439 ;;;
440 ;;; FIXME: The comment above suggests that perhaps some of my added
441 ;;; FTYPE declarations are in poor taste. Should I change my
442 ;;; declarations, or change the comment, or what?
443 ;;;
444 ;;; FIXME: DEFKNOWN is needed only at build-the-system time. Figure
445 ;;; out some way to keep it from appearing in the target system.
446 ;;;
447 ;;; Declare the function NAME to be a known function. We construct a
448 ;;; type specifier for the function by wrapping (FUNCTION ...) around
449 ;;; the ARG-TYPES and RESULT-TYPE. ATTRIBUTES is an unevaluated list
450 ;;; of boolean attributes of the function. See their description in
451 ;;; (DEF-BOOLEAN-ATTRIBUTE IR1). NAME may also be a list of names, in
452 ;;; which case the same information is given to all the names. The
453 ;;; keywords specify the initial values for various optimizers that
454 ;;; the function might have.
455 (defmacro defknown (name arg-types result-type &optional (attributes '(any))
456                          &rest keys)
457   (when (and (intersection attributes '(any call unwind))
458              (intersection attributes '(movable)))
459     (error "function cannot have both good and bad attributes: ~S" attributes))
460
461   (when (member 'any attributes)
462     (setf attributes (union '(call unsafe unwind) attributes)))
463   (when (member 'flushable attributes)
464     (pushnew 'unsafely-flushable attributes))
465
466   `(%defknown ',(if (and (consp name)
467                          (not (eq (car name) 'setf)))
468                     name
469                     (list name))
470               '(function ,arg-types ,result-type)
471               (ir1-attributes ,@attributes)
472               ,@keys))
473
474 ;;; Create a function which parses combination args according to WHAT
475 ;;; and LAMBDA-LIST, where WHAT is either a function name or a list
476 ;;; (FUN-NAME KIND) and does some KIND of optimization.
477 ;;;
478 ;;; The FUN-NAME must name a known function. LAMBDA-LIST is used
479 ;;; to parse the arguments to the combination as in DEFTRANSFORM. If
480 ;;; the argument syntax is invalid or there are non-constant keys,
481 ;;; then we simply return NIL.
482 ;;;
483 ;;; The function is DEFUN'ed as FUNCTION-KIND-OPTIMIZER. Possible
484 ;;; kinds are DERIVE-TYPE, OPTIMIZER, LTN-ANNOTATE and IR2-CONVERT. If
485 ;;; a symbol is specified instead of a (FUNCTION KIND) list, then we
486 ;;; just do a DEFUN with the symbol as its name, and don't do anything
487 ;;; with the definition. This is useful for creating optimizers to be
488 ;;; passed by name to DEFKNOWN.
489 ;;;
490 ;;; If supplied, NODE-VAR is bound to the combination node being
491 ;;; optimized. If additional VARS are supplied, then they are used as
492 ;;; the rest of the optimizer function's lambda-list. LTN-ANNOTATE
493 ;;; methods are passed an additional POLICY argument, and IR2-CONVERT
494 ;;; methods are passed an additional IR2-BLOCK argument.
495 (defmacro defoptimizer (what (lambda-list &optional (n-node (gensym))
496                                           &rest vars)
497                              &body body)
498   (let ((name (if (symbolp what) what
499                   (symbolicate (first what) "-" (second what) "-OPTIMIZER"))))
500
501     (let ((n-args (gensym)))
502       `(progn
503         (defun ,name (,n-node ,@vars)
504           (let ((,n-args (basic-combination-args ,n-node)))
505             ,(parse-deftransform lambda-list body n-args
506                                  `(return-from ,name nil))))
507         ,@(when (consp what)
508             `((setf (,(symbolicate "FUN-INFO-" (second what))
509                      (fun-info-or-lose ',(first what)))
510                     #',name)))))))
511 \f
512 ;;;; IR groveling macros
513
514 ;;; Iterate over the blocks in a component, binding BLOCK-VAR to each
515 ;;; block in turn. The value of ENDS determines whether to iterate
516 ;;; over dummy head and tail blocks:
517 ;;;    NIL  -- Skip Head and Tail (the default)
518 ;;;   :HEAD -- Do head but skip tail
519 ;;;   :TAIL -- Do tail but skip head
520 ;;;   :BOTH -- Do both head and tail
521 ;;;
522 ;;; If supplied, RESULT-FORM is the value to return.
523 (defmacro do-blocks ((block-var component &optional ends result) &body body)
524   (unless (member ends '(nil :head :tail :both))
525     (error "losing ENDS value: ~S" ends))
526   (let ((n-component (gensym))
527         (n-tail (gensym)))
528     `(let* ((,n-component ,component)
529             (,n-tail ,(if (member ends '(:both :tail))
530                           nil
531                           `(component-tail ,n-component))))
532        (do ((,block-var ,(if (member ends '(:both :head))
533                              `(component-head ,n-component)
534                              `(block-next (component-head ,n-component)))
535                         (block-next ,block-var)))
536            ((eq ,block-var ,n-tail) ,result)
537          ,@body))))
538 ;;; like DO-BLOCKS, only iterating over the blocks in reverse order
539 (defmacro do-blocks-backwards ((block-var component &optional ends result) &body body)
540   (unless (member ends '(nil :head :tail :both))
541     (error "losing ENDS value: ~S" ends))
542   (let ((n-component (gensym))
543         (n-head (gensym)))
544     `(let* ((,n-component ,component)
545             (,n-head ,(if (member ends '(:both :head))
546                           nil
547                           `(component-head ,n-component))))
548        (do ((,block-var ,(if (member ends '(:both :tail))
549                              `(component-tail ,n-component)
550                              `(block-prev (component-tail ,n-component)))
551                         (block-prev ,block-var)))
552            ((eq ,block-var ,n-head) ,result)
553          ,@body))))
554
555 ;;; Iterate over the uses of CONTINUATION, binding NODE to each one
556 ;;; successively.
557 ;;;
558 ;;; XXX Could change it not to replicate the code someday perhaps...
559 (defmacro do-uses ((node-var continuation &optional result) &body body)
560   (once-only ((n-cont continuation))
561     `(ecase (continuation-kind ,n-cont)
562        (:unused)
563        (:inside-block
564         (block nil
565           (let ((,node-var (continuation-use ,n-cont)))
566             ,@body
567             ,result)))
568        ((:block-start :deleted-block-start)
569         (dolist (,node-var (block-start-uses (continuation-block ,n-cont))
570                            ,result)
571           ,@body)))))
572
573 ;;; Iterate over the nodes in BLOCK, binding NODE-VAR to the each node
574 ;;; and CONT-VAR to the node's CONT. The only keyword option is
575 ;;; RESTART-P, which causes iteration to be restarted when a node is
576 ;;; deleted out from under us. (If not supplied, this is an error.)
577 ;;;
578 ;;; In the forward case, we terminate on LAST-CONT so that we don't
579 ;;; have to worry about our termination condition being changed when
580 ;;; new code is added during the iteration. In the backward case, we
581 ;;; do NODE-PREV before evaluating the body so that we can keep going
582 ;;; when the current node is deleted.
583 ;;;
584 ;;; When RESTART-P is supplied to DO-NODES, we start iterating over
585 ;;; again at the beginning of the block when we run into a
586 ;;; continuation whose block differs from the one we are trying to
587 ;;; iterate over, either because the block was split, or because a
588 ;;; node was deleted out from under us (hence its block is NIL.) If
589 ;;; the block start is deleted, we just punt. With RESTART-P, we are
590 ;;; also more careful about termination, re-indirecting the BLOCK-LAST
591 ;;; each time.
592 (defmacro do-nodes ((node-var cont-var block &key restart-p) &body body)
593   (let ((n-block (gensym))
594         (n-last-cont (gensym)))
595     `(let* ((,n-block ,block)
596             ,@(unless restart-p
597                 `((,n-last-cont (node-cont (block-last ,n-block))))))
598        (do* ((,node-var (continuation-next (block-start ,n-block))
599                         ,(if restart-p
600                              `(cond
601                                ((eq (continuation-block ,cont-var) ,n-block)
602                                 (aver (continuation-next ,cont-var))
603                                 (continuation-next ,cont-var))
604                                (t
605                                 (let ((start (block-start ,n-block)))
606                                   (unless (eq (continuation-kind start)
607                                               :block-start)
608                                     (return nil))
609                                   (continuation-next start))))
610                              `(continuation-next ,cont-var)))
611              (,cont-var (node-cont ,node-var) (node-cont ,node-var)))
612             (())
613          ,@body
614          (when ,(if restart-p
615                     `(eq ,node-var (block-last ,n-block))
616                     `(eq ,cont-var ,n-last-cont))
617            (return nil))))))
618 ;;; like DO-NODES, only iterating in reverse order
619 (defmacro do-nodes-backwards ((node-var cont-var block) &body body)
620   (let ((n-block (gensym))
621         (n-start (gensym))
622         (n-last (gensym))
623         (n-next (gensym)))
624     `(let* ((,n-block ,block)
625             (,n-start (block-start ,n-block))
626             (,n-last (block-last ,n-block)))
627        (do* ((,cont-var (node-cont ,n-last) ,n-next)
628              (,node-var ,n-last (continuation-use ,cont-var))
629              (,n-next (node-prev ,node-var) (node-prev ,node-var)))
630             (())
631          ,@body
632          (when (eq ,n-next ,n-start)
633            (return nil))))))
634
635 ;;; Bind the IR1 context variables to the values associated with NODE,
636 ;;; so that new, extra IR1 conversion related to NODE can be done
637 ;;; after the original conversion pass has finished.
638 (defmacro with-ir1-environment-from-node (node &rest forms)
639   `(flet ((closure-needing-ir1-environment-from-node ()
640             ,@forms))
641      (%with-ir1-environment-from-node
642       ,node
643       #'closure-needing-ir1-environment-from-node)))
644 (defun %with-ir1-environment-from-node (node fun)
645   (declare (type node node) (type function fun))
646   (let ((*current-component* (node-component node))
647         (*lexenv* (node-lexenv node))
648         (*current-path* (node-source-path node)))
649     (aver-live-component *current-component*)
650     (funcall fun)))
651
652 ;;; Bind the hashtables used for keeping track of global variables,
653 ;;; functions, etc. Also establish condition handlers.
654 (defmacro with-ir1-namespace (&body forms)
655   `(let ((*free-vars* (make-hash-table :test 'eq))
656          (*free-funs* (make-hash-table :test 'equal))
657          (*constants* (make-hash-table :test 'equal))
658          (*source-paths* (make-hash-table :test 'eq)))
659      (handler-bind ((compiler-error #'compiler-error-handler)
660                     (style-warning #'compiler-style-warning-handler)
661                     (warning #'compiler-warning-handler))
662        ,@forms)))
663
664 ;;; Look up NAME in the lexical environment namespace designated by
665 ;;; SLOT, returning the <value, T>, or <NIL, NIL> if no entry. The
666 ;;; :TEST keyword may be used to determine the name equality
667 ;;; predicate.
668 (defmacro lexenv-find (name slot &key test)
669   (once-only ((n-res `(assoc ,name (,(let ((*package* (symbol-package 'lexenv-funs)))
670                                           (symbolicate "LEXENV-" slot))
671                                      *lexenv*)
672                              :test ,(or test '#'eq))))
673     `(if ,n-res
674          (values (cdr ,n-res) t)
675          (values nil nil))))
676
677 ;;;
678 (defmacro with-continuation-type-assertion ((cont ctype context) &body body)
679   `(let ((*lexenv* (ir1ize-the-or-values ,ctype ,cont *lexenv* ,context)))
680      ,@body))
681 \f
682 ;;;; the EVENT statistics/trace utility
683
684 ;;; FIXME: This seems to be useful for troubleshooting and
685 ;;; experimentation, not for ordinary use, so it should probably
686 ;;; become conditional on SB-SHOW.
687
688 (eval-when (:compile-toplevel :load-toplevel :execute)
689
690 (defstruct (event-info (:copier nil))
691   ;; The name of this event.
692   (name (missing-arg) :type symbol)
693   ;; The string rescribing this event.
694   (description (missing-arg) :type string)
695   ;; The name of the variable we stash this in.
696   (var (missing-arg) :type symbol)
697   ;; The number of times this event has happened.
698   (count 0 :type fixnum)
699   ;; The level of significance of this event.
700   (level (missing-arg) :type unsigned-byte)
701   ;; If true, a function that gets called with the node that the event
702   ;; happened to.
703   (action nil :type (or function null)))
704
705 ;;; A hashtable from event names to event-info structures.
706 (defvar *event-info* (make-hash-table :test 'eq))
707
708 ;;; Return the event info for Name or die trying.
709 (declaim (ftype (function (t) event-info) event-info-or-lose))
710 (defun event-info-or-lose (name)
711   (let ((res (gethash name *event-info*)))
712     (unless res
713       (error "~S is not the name of an event." name))
714     res))
715
716 ) ; EVAL-WHEN
717
718 ;;; Return the number of times that EVENT has happened.
719 (declaim (ftype (function (symbol) fixnum) event-count))
720 (defun event-count (name)
721   (event-info-count (event-info-or-lose name)))
722
723 ;;; Return the function that is called when Event happens. If this is
724 ;;; null, there is no action. The function is passed the node to which
725 ;;; the event happened, or NIL if there is no relevant node. This may
726 ;;; be set with SETF.
727 (declaim (ftype (function (symbol) (or function null)) event-action))
728 (defun event-action (name)
729   (event-info-action (event-info-or-lose name)))
730 (declaim (ftype (function (symbol (or function null)) (or function null))
731                 %set-event-action))
732 (defun %set-event-action (name new-value)
733   (setf (event-info-action (event-info-or-lose name))
734         new-value))
735 (defsetf event-action %set-event-action)
736
737 ;;; Return the non-negative integer which represents the level of
738 ;;; significance of the event Name. This is used to determine whether
739 ;;; to print a message when the event happens. This may be set with
740 ;;; SETF.
741 (declaim (ftype (function (symbol) unsigned-byte) event-level))
742 (defun event-level (name)
743   (event-info-level (event-info-or-lose name)))
744 (declaim (ftype (function (symbol unsigned-byte) unsigned-byte) %set-event-level))
745 (defun %set-event-level (name new-value)
746   (setf (event-info-level (event-info-or-lose name))
747         new-value))
748 (defsetf event-level %set-event-level)
749
750 ;;; Define a new kind of event. Name is a symbol which names the event
751 ;;; and Description is a string which describes the event. Level
752 ;;; (default 0) is the level of significance associated with this
753 ;;; event; it is used to determine whether to print a Note when the
754 ;;; event happens.
755 (defmacro defevent (name description &optional (level 0))
756   (let ((var-name (symbolicate "*" name "-EVENT-INFO*")))
757     `(eval-when (:compile-toplevel :load-toplevel :execute)
758        (defvar ,var-name
759          (make-event-info :name ',name
760                           :description ',description
761                           :var ',var-name
762                           :level ,level))
763        (setf (gethash ',name *event-info*) ,var-name)
764        ',name)))
765
766 ;;; the lowest level of event that will print a note when it occurs
767 (declaim (type unsigned-byte *event-note-threshold*))
768 (defvar *event-note-threshold* 1)
769
770 ;;; Note that the event with the specified Name has happened. Node is
771 ;;; evaluated to determine the node to which the event happened.
772 (defmacro event (name &optional node)
773   ;; Increment the counter and do any action. Mumble about the event if
774   ;; policy indicates.
775   `(%event ,(event-info-var (event-info-or-lose name)) ,node))
776
777 ;;; Print a listing of events and their counts, sorted by the count.
778 ;;; Events that happened fewer than Min-Count times will not be
779 ;;; printed. Stream is the stream to write to.
780 (declaim (ftype (function (&optional unsigned-byte stream) (values)) event-statistics))
781 (defun event-statistics (&optional (min-count 1) (stream *standard-output*))
782   (collect ((info))
783     (maphash (lambda (k v)
784                (declare (ignore k))
785                (when (>= (event-info-count v) min-count)
786                  (info v)))
787              *event-info*)
788     (dolist (event (sort (info) #'> :key #'event-info-count))
789       (format stream "~6D: ~A~%" (event-info-count event)
790               (event-info-description event)))
791     (values))
792   (values))
793
794 (declaim (ftype (function nil (values)) clear-event-statistics))
795 (defun clear-event-statistics ()
796   (maphash (lambda (k v)
797              (declare (ignore k))
798              (setf (event-info-count v) 0))
799            *event-info*)
800   (values))
801 \f
802 ;;;; functions on directly-linked lists (linked through specialized
803 ;;;; NEXT operations)
804
805 #!-sb-fluid (declaim (inline find-in position-in map-in))
806
807 ;;; Find Element in a null-terminated List linked by the accessor
808 ;;; function Next. Key, Test and Test-Not are the same as for generic
809 ;;; sequence functions.
810 (defun find-in (next
811                 element
812                 list
813                 &key
814                 (key #'identity)
815                 (test #'eql test-p)
816                 (test-not nil not-p))
817   (when (and test-p not-p)
818     (error "It's silly to supply both :TEST and :TEST-NOT arguments."))
819   (if not-p
820       (do ((current list (funcall next current)))
821           ((null current) nil)
822         (unless (funcall test-not (funcall key current) element)
823           (return current)))
824       (do ((current list (funcall next current)))
825           ((null current) nil)
826         (when (funcall test (funcall key current) element)
827           (return current)))))
828
829 ;;; Return the position of Element (or NIL if absent) in a
830 ;;; null-terminated List linked by the accessor function Next. Key,
831 ;;; Test and Test-Not are the same as for generic sequence functions.
832 (defun position-in (next
833                     element
834                     list
835                     &key
836                     (key #'identity)
837                     (test #'eql test-p)
838                     (test-not nil not-p))
839   (when (and test-p not-p)
840     (error "It's silly to supply both :TEST and :TEST-NOT arguments."))
841   (if not-p
842       (do ((current list (funcall next current))
843            (i 0 (1+ i)))
844           ((null current) nil)
845         (unless (funcall test-not (funcall key current) element)
846           (return i)))
847       (do ((current list (funcall next current))
848            (i 0 (1+ i)))
849           ((null current) nil)
850         (when (funcall test (funcall key current) element)
851           (return i)))))
852
853 ;;; Map FUNCTION over the elements in a null-terminated LIST linked by the
854 ;;; accessor function NEXT, returning an ordinary list of the results.
855 (defun map-in (next function list)
856   (collect ((res))
857     (do ((current list (funcall next current)))
858         ((null current))
859       (res (funcall function current)))
860     (res)))
861
862 ;;; KLUDGE: This is expanded out twice, by cut-and-paste, in a
863 ;;;   (DEF!MACRO FOO (..) .. CL:GET-SETF-EXPANSION ..)
864 ;;;   #+SB-XC-HOST
865 ;;;   (SB!XC:DEFMACRO FOO (..) .. SB!XC:GET-SETF-EXPANSION ..)
866 ;;; arrangement, in order to get it to work in cross-compilation. This
867 ;;; duplication should be removed, perhaps by rewriting the macro in a more
868 ;;; cross-compiler-friendly way, or perhaps just by using some (MACROLET ((FROB
869 ;;; ..)) .. FROB .. FROB) form, or perhaps by completely eliminating this macro
870 ;;; and its partner PUSH-IN, but I don't want to do it now, because the system
871 ;;; isn't running yet, so it'd be too hard to check that my changes were
872 ;;; correct -- WHN 19990806
873 (def!macro deletef-in (next place item &environment env)
874   (multiple-value-bind (temps vals stores store access)
875       (get-setf-expansion place env)
876     (when (cdr stores)
877       (error "multiple store variables for ~S" place))
878     (let ((n-item (gensym))
879           (n-place (gensym))
880           (n-current (gensym))
881           (n-prev (gensym)))
882       `(let* (,@(mapcar #'list temps vals)
883               (,n-place ,access)
884               (,n-item ,item))
885          (if (eq ,n-place ,n-item)
886              (let ((,(first stores) (,next ,n-place)))
887                ,store)
888              (do ((,n-prev ,n-place ,n-current)
889                   (,n-current (,next ,n-place)
890                               (,next ,n-current)))
891                  ((eq ,n-current ,n-item)
892                   (setf (,next ,n-prev)
893                         (,next ,n-current)))))
894          (values)))))
895 ;;; #+SB-XC-HOST SB!XC:DEFMACRO version is in late-macros.lisp. -- WHN 19990806
896
897 ;;; Push ITEM onto a list linked by the accessor function NEXT that is
898 ;;; stored in PLACE.
899 ;;;
900 ;;; KLUDGE: This is expanded out twice, by cut-and-paste, in a
901 ;;;   (DEF!MACRO FOO (..) .. CL:GET-SETF-EXPANSION ..)
902 ;;;   #+SB-XC-HOST
903 ;;;   (SB!XC:DEFMACRO FOO (..) .. SB!XC:GET-SETF-EXPANSION ..)
904 ;;; arrangement, in order to get it to work in cross-compilation. This
905 ;;; duplication should be removed, perhaps by rewriting the macro in a more
906 ;;; cross-compiler-friendly way, or perhaps just by using some (MACROLET ((FROB
907 ;;; ..)) .. FROB .. FROB) form, or perhaps by completely eliminating this macro
908 ;;; and its partner DELETEF-IN, but I don't want to do it now, because the
909 ;;; system isn't running yet, so it'd be too hard to check that my changes were
910 ;;; correct -- WHN 19990806
911 (def!macro push-in (next item place &environment env)
912   (multiple-value-bind (temps vals stores store access)
913       (get-setf-expansion place env)
914     (when (cdr stores)
915       (error "multiple store variables for ~S" place))
916     `(let (,@(mapcar #'list temps vals)
917            (,(first stores) ,item))
918        (setf (,next ,(first stores)) ,access)
919        ,store
920        (values))))
921 ;;; #+SB-XC-HOST SB!XC:DEFMACRO version is in late-macros.lisp. -- WHN 19990806
922
923 (defmacro position-or-lose (&rest args)
924   `(or (position ,@args)
925        (error "shouldn't happen?")))