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