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