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