Use flatteningization in package-data-list
[sbcl.git] / src / compiler / macros.lisp
blob07877a07bc53522cc429d583aaf622a488792fd2
1 ;;;; miscellaneous types and macros used in writing the compiler
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.
12 (in-package "SB!C")
14 ;;;; source-hacking defining forms
16 ;;; Parse a DEFMACRO-style lambda-list, setting things up so that a
17 ;;; compiler error happens if the syntax is invalid.
18 ;;;
19 ;;; Define a function that converts a special form or other magical
20 ;;; thing into IR1. LAMBDA-LIST is a defmacro style lambda
21 ;;; list. START-VAR, NEXT-VAR and RESULT-VAR are bound to the start and
22 ;;; result continuations for the resulting IR1. KIND is the function
23 ;;; kind to associate with NAME.
24 ;;; FIXME - Translators which accept implicit PROGNs fail on improper
25 ;;; input, e.g. (LAMBDA (X) (CATCH X (BAZ) . 3))
26 ;;; This is because &REST is defined to allow a dotted tail in macros,
27 ;;; and we have no implementation-specific workaround to disallow it.
28 (defmacro def-ir1-translator (name (lambda-list start-var next-var result-var)
29 &body body)
30 (binding* ((fn-name (symbolicate "IR1-CONVERT-" name))
31 (whole-var (make-symbol "FORM"))
32 ((lambda-expr doc)
33 (make-macro-lambda nil lambda-list body :special-form name
34 :doc-string-allowed :external
35 :wrap-block nil)))
36 (declare (ignorable doc))
37 `(progn
38 (declaim (ftype (function (ctran ctran (or lvar null) t) (values))
39 ,fn-name))
40 (defun ,fn-name (,start-var ,next-var ,result-var ,whole-var)
41 (declare (ignorable ,start-var ,next-var ,result-var))
42 ;; The guard function is a closure, which can't have its lambda-list
43 ;; changed independently of other closures based on the same
44 ;; simple-fun. So change it in the ir1-translator since the actual
45 ;; lambda-list is not terribly useful.
46 (declare (lambda-list ,lambda-list))
47 (,lambda-expr ,whole-var *lexenv*)
48 (values))
49 #-sb-xc-host
50 (install-guard-function ',name '(:special ,name) ,(or #!+sb-doc doc))
51 ;; FIXME: Evidently "there can only be one!" -- we overwrite any
52 ;; other :IR1-CONVERT value. This deserves a warning, I think.
53 (setf (info :function :ir1-convert ',name) #',fn-name)
54 ;; FIXME: rename this to SPECIAL-OPERATOR, to update it to
55 ;; the 1990s?
56 (setf (info :function :kind ',name) :special-form)
57 ',name)))
59 ;;; (This is similar to DEF-IR1-TRANSLATOR, except that we pass if the
60 ;;; syntax is invalid.)
61 ;;;
62 ;;; Define a macro-like source-to-source transformation for the
63 ;;; function NAME. A source transform may "pass" by returning a
64 ;;; non-nil second value. If the transform passes, then the form is
65 ;;; converted as a normal function call. If the supplied arguments are
66 ;;; not compatible with the specified LAMBDA-LIST, then the transform
67 ;;; automatically passes.
68 ;;;
69 ;;; Source transforms may only be defined for functions. Source
70 ;;; transformation is not attempted if the function is declared
71 ;;; NOTINLINE. Source transforms should not examine their arguments.
72 ;;; A macro lambda list which destructures more than one level would
73 ;;; be legal but suspicious, as inner list parsing "examines" arguments.
74 ;;; If it matters how the function is used, then DEFTRANSFORM should
75 ;;; be used to define an IR1 transformation.
76 ;;;
77 ;;; If the desirability of the transformation depends on the current
78 ;;; OPTIMIZE parameters, then the POLICY macro should be used to
79 ;;; determine when to pass.
80 ;;;
81 ;;; Note that while a compiler-macro must deal with being invoked when its
82 ;;; whole form matches (FUNCALL <f> ...) so that it must skip over <f> to find
83 ;;; the arguments, a source-transform need not worry about that situation.
84 ;;; Any FUNCALL which is eligible for a source-transform calls the expander
85 ;;; with the form's head replaced by a compiler representation of the function.
86 ;;; Internalizing the name avoids semantic problems resulting from syntactic
87 ;;; substitution. One problem would be that a source-transform can exist for
88 ;;; a function named (SETF X), but ((SETF X) arg ...) would be bad syntax.
89 ;;; Even if we decided that it is ok within the compiler - just not in code
90 ;;; given to the compiler - the problem remains that changing (FUNCALL 'F x)
91 ;;; to (F x) is wrong when F also names a local functionoid.
92 ;;; Hence, either a #<GLOBAL-VAR> or #<DEFINED-FUN> appears in the form head.
93 ;;;
94 (defmacro define-source-transform (fun-name lambda-list &body body)
95 ;; FIXME: this is redundant with what will become MAKE-MACRO-LAMBDA
96 ;; except that it needs a "silently do nothing" mode, which may or may not
97 ;; be a generally exposed feature.
98 (binding*
99 (((forms decls) (parse-body body nil))
100 ((llks req opt rest keys aux env whole)
101 (parse-lambda-list
102 lambda-list
103 :accept
104 (logandc2 (logior (lambda-list-keyword-mask '&environment)
105 (lambda-list-keyword-mask 'destructuring-bind))
106 ;; Function lambda lists shouldn't take &BODY.
107 (lambda-list-keyword-mask '&body))
108 :context "a source transform"))
109 ((outer-decl inner-decls) (extract-var-decls decls (append env whole)))
110 ;; With general macros, the user can declare (&WHOLE W &ENVIRONMENT E ..)
111 ;; and then (DECLARE (IGNORE W E)) which is a problem if system code
112 ;; touches user variables. But this is all system code, so it's fine.
113 (lambda-whole (if whole (car whole) (make-symbol "FORM")))
114 (lambda-env (if env (car env) (make-symbol "ENV")))
115 (new-ll (if (or whole env) ; strip them out if present
116 (make-lambda-list llks whole req opt rest keys aux)
117 lambda-list)) ; otherwise use the original list
118 (args (make-symbol "ARGS")))
119 `(setf (info :function :source-transform ',fun-name)
120 (named-lambda (:source-transform ,fun-name)
121 (,lambda-whole ,lambda-env &aux (,args (cdr ,lambda-whole)))
122 ,@(if (not env) `((declare (ignore ,lambda-env))))
123 ,@outer-decl ; SPECIALs or something? I hope not.
124 (if ,(emit-ds-lambda-list-match args new-ll)
125 ;; The body can return 1 or 2 values, but consistently
126 ;; returning 2 values from the XEP is stylistically
127 ;; preferable, and produces shorter assembly code too.
128 (multiple-value-bind (call pass)
129 (binding* ,(expand-ds-bind new-ll args nil 'truly-the)
130 ,@inner-decls ,@forms)
131 (values call pass))
132 (values nil t))))))
134 ;;;; lambda-list parsing utilities
135 ;;;;
136 ;;;; IR1 transforms, optimizers and type inferencers need to be able
137 ;;;; to parse the IR1 representation of a function call using a
138 ;;;; standard function lambda-list.
140 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
142 ;;; Given a DEFTRANSFORM-style lambda-list, generate code that parses
143 ;;; the arguments of a combination with respect to that lambda-list.
144 ;;; NODE-VAR the variable that holds the combination node.
145 ;;; ERROR-FORM is a form which is evaluated when the syntax of the
146 ;;; supplied arguments is incorrect or a non-constant argument keyword
147 ;;; is supplied. Defaults and other gunk are ignored. The second value
148 ;;; is a list of all the arguments bound, which the caller should make
149 ;;; IGNORABLE if their only purpose is to make the syntax work.
150 (defun parse-deftransform (lambda-list node-var error-form)
151 (multiple-value-bind (llks req opt rest keys) (parse-lambda-list lambda-list)
152 (let* ((tail (make-symbol "ARGS"))
153 (dummies (make-gensym-list 2))
154 (all-dummies (cons tail dummies))
155 (keyp (ll-kwds-keyp llks))
156 ;; FIXME: the logic for keywordicating a keyword arg specifier
157 ;; is repeated in a as many places as there are calls to
158 ;; parse-lambda-just, and more.
159 (keys (mapcar (lambda (spec)
160 (multiple-value-bind (key var)
161 (parse-key-arg-spec spec)
162 (cons var key)))
163 keys))
164 final-mandatory-arg)
165 (collect ((binds))
166 (binds `(,tail (basic-combination-args ,node-var)))
167 ;; The way this code checks for mandatory args is to verify that
168 ;; the last positional arg is not null (it should be an LVAR).
169 ;; But somebody could pedantically declare IGNORE on the last arg
170 ;; so bind a dummy for it and then bind from the dummy.
171 (mapl (lambda (args)
172 (cond ((cdr args)
173 (binds `(,(car args) (pop ,tail))))
175 (setq final-mandatory-arg (pop dummies))
176 (binds `(,final-mandatory-arg (pop ,tail))
177 `(,(car args) ,final-mandatory-arg)))))
178 req)
179 ;; Optionals are pretty easy.
180 (dolist (arg opt)
181 (binds `(,(if (atom arg) arg (car arg)) (pop ,tail))))
182 ;; Now if min or max # of args is incorrect,
183 ;; or there are unacceptable keywords, bail out
184 (when (or req keyp (not rest))
185 (binds `(,(pop dummies) ; binding is for effect, not value
186 (unless (and ,@(if req `(,final-mandatory-arg))
187 ,@(if (and (not rest) (not keyp))
188 `((endp ,tail)))
189 ,@(if keyp
190 (if (ll-kwds-allowp llks)
191 `((check-key-args-constant ,tail))
192 `((check-transform-keys
193 ,tail ',(mapcar #'cdr keys))))))
194 ,error-form))))
195 (when rest
196 (binds `(,(car rest) ,tail)))
197 ;; Return list of bindings, the list of user-specified symbols,
198 ;; and the list of gensyms to be declared ignorable.
199 (values (append (binds)
200 (mapcar (lambda (k)
201 `(,(car k)
202 (find-keyword-lvar ,tail ',(cdr k))))
203 keys))
204 (sort (append (nset-difference (mapcar #'car (binds)) all-dummies)
205 (mapcar #'car keys))
206 #'string<)
207 (sort (intersection (mapcar #'car (binds)) (cdr all-dummies))
208 #'string<))))))
209 ) ; EVAL-WHEN
211 ;;;; DEFTRANSFORM
213 ;;; Define an IR1 transformation for NAME. An IR1 transformation
214 ;;; computes a lambda that replaces the function variable reference
215 ;;; for the call. A transform may pass (decide not to transform the
216 ;;; call) by calling the GIVE-UP-IR1-TRANSFORM function. LAMBDA-LIST
217 ;;; both determines how the current call is parsed and specifies the
218 ;;; LAMBDA-LIST for the resulting lambda.
220 ;;; We parse the call and bind each of the lambda-list variables to
221 ;;; the lvar which represents the value of the argument. When parsing
222 ;;; the call, we ignore the defaults, and always bind the variables
223 ;;; for unsupplied arguments to NIL. If a required argument is
224 ;;; missing, an unknown keyword is supplied, or an argument keyword is
225 ;;; not a constant, then the transform automatically passes. The
226 ;;; DECLARATIONS apply to the bindings made by DEFTRANSFORM at
227 ;;; transformation time, rather than to the variables of the resulting
228 ;;; lambda. Bound-but-not-referenced warnings are suppressed for the
229 ;;; lambda-list variables. The DOC-STRING is used when printing
230 ;;; efficiency notes about the defined transform.
232 ;;; Normally, the body evaluates to a form which becomes the body of
233 ;;; an automatically constructed lambda. We make LAMBDA-LIST the
234 ;;; lambda-list for the lambda, and automatically insert declarations
235 ;;; of the argument and result types. If the second value of the body
236 ;;; is non-null, then it is a list of declarations which are to be
237 ;;; inserted at the head of the lambda. Automatic lambda generation
238 ;;; may be inhibited by explicitly returning a lambda from the body.
240 ;;; The ARG-TYPES and RESULT-TYPE are used to create a function type
241 ;;; which the call must satisfy before transformation is attempted.
242 ;;; The function type specifier is constructed by wrapping (FUNCTION
243 ;;; ...) around these values, so the lack of a restriction may be
244 ;;; specified by omitting the argument or supplying *. The argument
245 ;;; syntax specified in the ARG-TYPES need not be the same as that in
246 ;;; the LAMBDA-LIST, but the transform will never happen if the
247 ;;; syntaxes can't be satisfied simultaneously. If there is an
248 ;;; existing transform for the same function that has the same type,
249 ;;; then it is replaced with the new definition.
251 ;;; These are the legal keyword options:
252 ;;; :RESULT - A variable which is bound to the result lvar.
253 ;;; :NODE - A variable which is bound to the combination node for the call.
254 ;;; :POLICY - A form which is supplied to the POLICY macro to determine
255 ;;; whether this transformation is appropriate. If the result
256 ;;; is false, then the transform automatically gives up.
257 ;;; :EVAL-NAME
258 ;;; - The name and argument/result types are actually forms to be
259 ;;; evaluated. Useful for getting closures that transform similar
260 ;;; functions.
261 ;;; :DEFUN-ONLY
262 ;;; - Don't actually instantiate a transform, instead just DEFUN
263 ;;; Name with the specified transform definition function. This
264 ;;; may be later instantiated with %DEFTRANSFORM.
265 ;;; :IMPORTANT
266 ;;; - If the transform fails and :IMPORTANT is
267 ;;; NIL, then never print an efficiency note.
268 ;;; :SLIGHTLY, then print a note if SPEED>=INHIBIT-WARNINGS.
269 ;;; T, then print a note if SPEED>INHIBIT-WARNINGS.
270 ;;; :SLIGHTLY is the default.
271 (defmacro deftransform (name (lambda-list &optional (arg-types '*)
272 (result-type '*)
273 &key result policy node defun-only
274 eval-name (important :slightly))
275 &body body-decls-doc)
276 (declare (type (member nil :slightly t) important))
277 (when (and eval-name defun-only)
278 (error "can't specify both DEFUN-ONLY and EVAL-NAME"))
279 (multiple-value-bind (body decls doc) (parse-body body-decls-doc t)
280 (let ((n-node (or node (make-symbol "NODE")))
281 (n-decls (sb!xc:gensym))
282 (n-lambda (sb!xc:gensym)))
283 (multiple-value-bind (bindings vars)
284 (parse-deftransform lambda-list n-node
285 '(give-up-ir1-transform))
286 (let ((stuff
287 `((,n-node &aux ,@bindings
288 ,@(when result
289 `((,result (node-lvar ,n-node)))))
290 (declare (ignorable ,@(mapcar #'car bindings)))
291 (declare (lambda-list (node)))
292 ,@decls
293 ,@(if policy
294 `((unless (policy ,n-node ,policy)
295 (give-up-ir1-transform))))
296 ;; What purpose does it serve to allow the transform's body
297 ;; to return decls as a second value? They would go in the
298 ;; right place if simply returned as part of the expression.
299 (multiple-value-bind (,n-lambda ,n-decls)
300 (progn ,@body)
301 (if (and (consp ,n-lambda) (eq (car ,n-lambda) 'lambda))
302 ,n-lambda
303 `(lambda ,',lambda-list
304 (declare (ignorable ,@',vars))
305 ,@,n-decls
306 ,,n-lambda))))))
307 (if defun-only
308 `(defun ,name ,@(when doc `(,doc)) ,@stuff)
309 `(%deftransform
310 ,(if eval-name name `',name)
311 ,(if eval-name
312 ``(function ,,arg-types ,,result-type)
313 `'(function ,arg-types ,result-type))
314 (named-lambda ,(if eval-name "xform" `(deftransform ,name))
315 ,@stuff)
316 ,doc
317 ,important)))))))
319 ;;;; DEFKNOWN and DEFOPTIMIZER
321 ;;; This macro should be the way that all implementation independent
322 ;;; information about functions is made known to the compiler.
324 ;;; FIXME: The comment above suggests that perhaps some of my added
325 ;;; FTYPE declarations are in poor taste. Should I change my
326 ;;; declarations, or change the comment, or what?
328 ;;; FIXME: DEFKNOWN is needed only at build-the-system time. Figure
329 ;;; out some way to keep it from appearing in the target system.
331 ;;; Declare the function NAME to be a known function. We construct a
332 ;;; type specifier for the function by wrapping (FUNCTION ...) around
333 ;;; the ARG-TYPES and RESULT-TYPE. ATTRIBUTES is an unevaluated list
334 ;;; of boolean attributes of the function. See their description in
335 ;;; (!DEF-BOOLEAN-ATTRIBUTE IR1). NAME may also be a list of names, in
336 ;;; which case the same information is given to all the names. The
337 ;;; keywords specify the initial values for various optimizers that
338 ;;; the function might have.
339 (defmacro defknown (name arg-types result-type &optional (attributes '(any))
340 &body keys)
341 #-sb-xc-host
342 (when (member 'unsafe attributes)
343 (style-warn "Ignoring legacy attribute UNSAFE. Replaced by its inverse: DX-SAFE.")
344 (setf attributes (remove 'unsafe attributes)))
345 (when (and (intersection attributes '(any call unwind))
346 (intersection attributes '(movable)))
347 (error "function cannot have both good and bad attributes: ~S" attributes))
349 (when (member 'any attributes)
350 (setq attributes (union '(unwind) attributes)))
351 (when (member 'flushable attributes)
352 (pushnew 'unsafely-flushable attributes))
353 (multiple-value-bind (foldable-call callable arg-types)
354 (make-foldable-call-check arg-types attributes)
355 `(%defknown ',(if (and (consp name)
356 (not (legal-fun-name-p name)))
357 name
358 (list name))
359 '(sfunction ,arg-types ,result-type)
360 (ir1-attributes ,@attributes)
361 (source-location)
362 :foldable-call-check ,foldable-call
363 :callable-check ,callable
364 ,@keys)))
366 (defun make-foldable-call-check (arg-types attributes)
367 (let ((call (member 'call attributes))
368 (fold (member 'foldable attributes)))
369 (if (not call)
370 (values nil nil arg-types)
371 (multiple-value-bind (llks required optional rest keys)
372 (parse-lambda-list
373 arg-types
374 :context :function-type
375 :accept (lambda-list-keyword-mask
376 '(&optional &rest &key &allow-other-keys))
377 :silent t)
378 (let (vars
379 call-vars
380 arg-count-specified)
381 (labels ((callable-p (x)
382 (member x '(callable function)))
383 (process-var (x &optional (name (gensym)))
384 (if (callable-p (if (consp x)
385 (car x)
387 (push (cons name
388 (cond ((consp x)
389 (setf arg-count-specified t)
390 (cadr x))))
391 call-vars)
392 (push name vars))
393 name)
394 (process-type (type)
395 (if (and (consp type)
396 (callable-p (car type)))
397 (car type)
398 type))
399 (callable-rest-p (x)
400 (and (consp x)
401 (callable-p (car x))
402 (eql (cadr x) '&rest))))
403 (let* (rest-var
404 (lambda-list
405 (cond ((find-if #'callable-rest-p required)
406 (setf rest-var (gensym))
407 `(,@(loop for var in required
408 collect (process-var var)
409 until (callable-rest-p var))
410 &rest ,rest-var))
412 `(,@(mapcar #'process-var required)
413 ,@(and optional
414 `(&optional ,@(mapcar #'process-var optional)))
415 ,@(and rest
416 `(&rest ,@(mapcar #'process-var rest)))
417 ,@(and (ll-kwds-keyp llks)
418 `(&key ,@(loop for (key type) in keys
419 for var = (gensym)
420 do (process-var type var)
421 collect `((,key ,var))))))))))
423 (assert call-vars)
424 (values
425 (and fold
426 `(lambda ,lambda-list
427 (declare (ignore ,@vars))
428 (and ,@(loop for (x) in call-vars
429 collect `(constant-fold-arg-p ,x)))))
430 (and arg-count-specified
431 `(lambda ,lambda-list
432 (declare (ignore ,@vars))
433 ,@(loop for (x . arg-count) in call-vars
434 when arg-count
435 collect (if (eq arg-count '&rest)
436 `(valid-callable-argument ,x (length ,rest-var))
437 `(valid-callable-argument ,x ,arg-count)))))
438 `(,@(mapcar #'process-type required)
439 ,@(and optional
440 `(&optional ,@(mapcar #'process-type optional)))
441 ,@(and (ll-kwds-restp llks)
442 `(&rest ,@rest))
443 ,@(and (ll-kwds-keyp llks)
444 `(&key
445 ,@(loop for (key type) in keys
446 collect `(,key ,(process-type type)))))
447 ,@(and (ll-kwds-allowp llks)
448 '(&allow-other-keys)))))))))))
450 ;;; Create a function which parses combination args according to WHAT
451 ;;; and LAMBDA-LIST, where WHAT is either a function name or a list
452 ;;; (FUN-NAME KIND) and does some KIND of optimization.
454 ;;; The FUN-NAME must name a known function. LAMBDA-LIST is used
455 ;;; to parse the arguments to the combination as in DEFTRANSFORM. If
456 ;;; the argument syntax is invalid or there are non-constant keys,
457 ;;; then we simply return NIL.
459 ;;; The function is DEFUN'ed as FUNCTION-KIND-OPTIMIZER. Possible
460 ;;; kinds are DERIVE-TYPE, OPTIMIZER, LTN-ANNOTATE and IR2-CONVERT. If
461 ;;; a symbol is specified instead of a (FUNCTION KIND) list, then we
462 ;;; just do a DEFUN with the symbol as its name, and don't do anything
463 ;;; with the definition. This is useful for creating optimizers to be
464 ;;; passed by name to DEFKNOWN.
466 ;;; If supplied, NODE-VAR is bound to the combination node being
467 ;;; optimized. If additional VARS are supplied, then they are used as
468 ;;; the rest of the optimizer function's lambda-list. LTN-ANNOTATE
469 ;;; methods are passed an additional POLICY argument, and IR2-CONVERT
470 ;;; methods are passed an additional IR2-BLOCK argument.
471 (defmacro defoptimizer (what (lambda-list
472 &optional (node (sb!xc:gensym) node-p)
473 &rest vars)
474 &body body)
475 (binding* ((name
476 (flet ((function-name (name)
477 (etypecase name
478 (symbol name)
479 ((cons (eql setf) (cons symbol null))
480 (symbolicate (car name) "-" (cadr name))))))
481 (if (symbolp what)
482 what
483 (symbolicate (function-name (first what))
484 "-" (second what) "-OPTIMIZER"))))
485 ((forms decls) (parse-body body nil))
486 ((var-decls more-decls) (extract-var-decls decls vars))
487 ;; In case the BODY declares IGNORE of the formal NODE var,
488 ;; we rebind it from N-NODE and never reference it from BINDS.
489 (n-node (make-symbol "NODE"))
490 ((binds lambda-vars gensyms)
491 (parse-deftransform lambda-list n-node
492 `(return-from ,name nil))))
493 (declare (ignore lambda-vars))
494 `(progn
495 ;; We can't stuff the BINDS as &AUX vars into the lambda list
496 ;; because there can be a RETURN-FROM in there.
497 (defun ,name (,n-node ,@vars)
498 ,@(if var-decls (list var-decls))
499 (let* (,@binds ,@(if node-p `((,node ,n-node))))
500 ;; Syntax requires naming NODE even if undesired if VARS
501 ;; are present, so in that case make NODE ignorable.
502 (declare (ignorable ,@(if (and vars node-p) `(,node))
503 ,@gensyms))
504 ,@more-decls ,@forms))
505 ,@(when (consp what)
506 `((setf (,(let ((*package* (symbol-package 'fun-info)))
507 (symbolicate "FUN-INFO-" (second what)))
508 (fun-info-or-lose ',(first what)))
509 #',name))))))
511 ;;;; IR groveling macros
513 ;;; Iterate over the blocks in a component, binding BLOCK-VAR to each
514 ;;; block in turn. The value of ENDS determines whether to iterate
515 ;;; over dummy head and tail blocks:
516 ;;; NIL -- Skip Head and Tail (the default)
517 ;;; :HEAD -- Do head but skip tail
518 ;;; :TAIL -- Do tail but skip head
519 ;;; :BOTH -- Do both head and tail
521 ;;; If supplied, RESULT-FORM is the value to return.
522 (defmacro do-blocks ((block-var component &optional ends result) &body body)
523 (unless (member ends '(nil :head :tail :both))
524 (error "losing ENDS value: ~S" ends))
525 (let ((n-component (gensym))
526 (n-tail (gensym)))
527 `(let* ((,n-component ,component)
528 (,n-tail ,(if (member ends '(:both :tail))
530 `(component-tail ,n-component))))
531 (do ((,block-var ,(if (member ends '(:both :head))
532 `(component-head ,n-component)
533 `(block-next (component-head ,n-component)))
534 (block-next ,block-var)))
535 ((eq ,block-var ,n-tail) ,result)
536 ,@body))))
537 ;;; like DO-BLOCKS, only iterating over the blocks in reverse order
538 (defmacro do-blocks-backwards ((block-var component &optional ends result) &body body)
539 (unless (member ends '(nil :head :tail :both))
540 (error "losing ENDS value: ~S" ends))
541 (let ((n-component (gensym))
542 (n-head (gensym)))
543 `(let* ((,n-component ,component)
544 (,n-head ,(if (member ends '(:both :head))
546 `(component-head ,n-component))))
547 (do ((,block-var ,(if (member ends '(:both :tail))
548 `(component-tail ,n-component)
549 `(block-prev (component-tail ,n-component)))
550 (block-prev ,block-var)))
551 ((eq ,block-var ,n-head) ,result)
552 ,@body))))
554 ;;; Iterate over the uses of LVAR, binding NODE to each one
555 ;;; successively.
556 (defmacro do-uses ((node-var lvar &optional result) &body body)
557 (with-unique-names (uses)
558 `(let ((,uses (lvar-uses ,lvar)))
559 (block nil
560 (flet ((do-1-use (,node-var)
561 ,@body))
562 (if (listp ,uses)
563 (dolist (node ,uses)
564 (do-1-use node))
565 (do-1-use ,uses)))
566 ,result))))
568 ;;; Iterate over the nodes in BLOCK, binding NODE-VAR to the each node
569 ;;; and LVAR-VAR to the node's LVAR. The only keyword option is
570 ;;; RESTART-P, which causes iteration to be restarted when a node is
571 ;;; deleted out from under us. (If not supplied, this is an error.)
573 ;;; In the forward case, we terminate when NODE does not have NEXT, so
574 ;;; that we do not have to worry about our termination condition being
575 ;;; changed when new code is added during the iteration. In the
576 ;;; backward case, we do NODE-PREV before evaluating the body so that
577 ;;; we can keep going when the current node is deleted.
579 ;;; When RESTART-P is supplied to DO-NODES, we start iterating over
580 ;;; again at the beginning of the block when we run into a ctran whose
581 ;;; block differs from the one we are trying to iterate over, either
582 ;;; because the block was split, or because a node was deleted out
583 ;;; from under us (hence its block is NIL.) If the block start is
584 ;;; deleted, we just punt. With RESTART-P, we are also more careful
585 ;;; about termination, re-indirecting the BLOCK-LAST each time.
586 (defmacro do-nodes ((node-var lvar-var block &key restart-p)
587 &body body)
588 (with-unique-names (n-block n-start)
589 `(do* ((,n-block ,block)
590 (,n-start (block-start ,n-block))
592 (,node-var (ctran-next ,n-start)
593 ,(if restart-p
594 `(let ((next (node-next ,node-var)))
595 (cond
596 ((not next)
597 (return))
598 ((eq (ctran-block next) ,n-block)
599 (ctran-next next))
601 (let ((start (block-start ,n-block)))
602 (unless (eq (ctran-kind start)
603 :block-start)
604 (return nil))
605 (ctran-next start)))))
606 `(acond ((node-next ,node-var)
607 (ctran-next it))
608 (t (return)))))
609 ,@(when lvar-var
610 `((,lvar-var (when (valued-node-p ,node-var)
611 (node-lvar ,node-var))
612 (when (valued-node-p ,node-var)
613 (node-lvar ,node-var))))))
614 (nil)
615 ,@body
616 ,@(when restart-p
617 `((when (block-delete-p ,n-block)
618 (return)))))))
620 ;;; Like DO-NODES, only iterating in reverse order. Should be careful
621 ;;; with block being split under us.
622 (defmacro do-nodes-backwards ((node-var lvar block &key restart-p) &body body)
623 (let ((n-block (gensym))
624 (n-prev (gensym)))
625 `(loop with ,n-block = ,block
626 for ,node-var = (block-last ,n-block) then
627 ,(if restart-p
628 `(if (eq ,n-block (ctran-block ,n-prev))
629 (ctran-use ,n-prev)
630 (block-last ,n-block))
631 `(ctran-use ,n-prev))
632 for ,n-prev = (when ,node-var (node-prev ,node-var))
633 and ,lvar = (when (and ,node-var (valued-node-p ,node-var))
634 (node-lvar ,node-var))
635 while ,(if restart-p
636 `(and ,node-var (not (block-to-be-deleted-p ,n-block)))
637 node-var)
638 do (progn
639 ,@body))))
641 (defmacro do-nodes-carefully ((node-var block) &body body)
642 (with-unique-names (n-block n-ctran)
643 `(loop with ,n-block = ,block
644 for ,n-ctran = (block-start ,n-block) then (node-next ,node-var)
645 for ,node-var = (and ,n-ctran (ctran-next ,n-ctran))
646 while ,node-var
647 do (progn ,@body))))
649 (defmacro do-nested-cleanups ((cleanup-var block &optional return-value)
650 &body body)
651 `(block nil
652 (map-nested-cleanups
653 (lambda (,cleanup-var) ,@body) ,block ,return-value)))
655 ;;; Bind the IR1 context variables to the values associated with NODE,
656 ;;; so that new, extra IR1 conversion related to NODE can be done
657 ;;; after the original conversion pass has finished.
658 (defmacro with-ir1-environment-from-node (node &rest forms)
659 `(flet ((closure-needing-ir1-environment-from-node ()
660 ,@forms))
661 (%with-ir1-environment-from-node
662 ,node
663 #'closure-needing-ir1-environment-from-node)))
665 (defmacro with-source-paths (&body forms)
666 (with-unique-names (source-paths)
667 `(let* ((,source-paths (make-hash-table :test 'eq))
668 (*source-paths* ,source-paths))
669 (unwind-protect
670 (progn ,@forms)
671 (clrhash ,source-paths)))))
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 (unwind-protect
680 (progn ,@forms)
681 (clrhash *free-funs*)
682 (clrhash *free-vars*)
683 (clrhash *constants*))))
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))))
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))))))
711 ;;;; the EVENT statistics/trace utility
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.
717 (eval-when (#-sb-xc :compile-toplevel :load-toplevel :execute)
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)))
734 ;;; A hashtable from event names to event-info structures.
735 (defvar *event-info* (make-hash-table :test 'eq))
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))
745 ) ; EVAL-WHEN
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)))
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)
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)
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)))
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)
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))
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))
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))
831 ;;;; functions on directly-linked lists (linked through specialized
832 ;;;; NEXT operations)
834 #!-sb-fluid (declaim (inline find-in position-in))
836 ;;; Find ELEMENT in a null-terminated LIST linked by the accessor
837 ;;; function NEXT. KEY and TEST are the same as for generic sequence functions.
838 (defun find-in (next
839 element
840 list
841 &key
842 (key #'identity)
843 (test #'eql))
844 (declare (type function next key test))
845 (do ((current list (funcall next current)))
846 ((null current) nil)
847 (when (funcall test (funcall key current) element)
848 (return current))))
850 ;;; Return the position of ELEMENT (or NIL if absent) in a
851 ;;; null-terminated LIST linked by the accessor function NEXT.
852 ;;; KEY and TEST are the same as for generic sequence functions.
853 (defun position-in (next
854 element
855 list
856 &key
857 (key #'identity)
858 (test #'eql))
859 (declare (type function next key test))
860 (do ((current list (funcall next current))
861 (i 0 (1+ i)))
862 ((null current) nil)
863 (when (funcall test (funcall key current) element)
864 (return i))))
866 (defmacro deletef-in (next place item &environment env)
867 (multiple-value-bind (temps vals stores store access)
868 (#+sb-xc sb!xc:get-setf-expansion #-sb-xc get-setf-expansion place env)
869 (when (cdr stores)
870 (error "multiple store variables for ~S" place))
871 (let ((n-item (gensym))
872 (n-place (gensym))
873 (n-current (gensym))
874 (n-prev (gensym)))
875 `(let* (,@(mapcar #'list temps vals)
876 (,n-place ,access)
877 (,n-item ,item))
878 (if (eq ,n-place ,n-item)
879 (let ((,(first stores) (,next ,n-place)))
880 ,store)
881 (do ((,n-prev ,n-place ,n-current)
882 (,n-current (,next ,n-place)
883 (,next ,n-current)))
884 ((eq ,n-current ,n-item)
885 (setf (,next ,n-prev)
886 (,next ,n-current)))))
887 (values)))))
889 ;;; Push ITEM onto a list linked by the accessor function NEXT that is
890 ;;; stored in PLACE.
892 (defmacro push-in (next item place &environment env)
893 (multiple-value-bind (temps vals stores store access)
894 (#+sb-xc sb!xc:get-setf-expansion #-sb-xc get-setf-expansion place env)
895 (when (cdr stores)
896 (error "multiple store variables for ~S" place))
897 `(let (,@(mapcar #'list temps vals)
898 (,(first stores) ,item))
899 (setf (,next ,(first stores)) ,access)
900 ,store
901 (values))))
903 (defmacro position-or-lose (&rest args)
904 `(or (position ,@args)
905 (error "shouldn't happen?")))
907 ;;; user-definable compiler io syntax
909 ;;; We use WITH-SANE-IO-SYNTAX to provide safe defaults, and provide
910 ;;; *COMPILER-PRINT-VARIABLE-ALIST* for user customization.
911 (defvar *compiler-print-variable-alist* nil
912 #!+sb-doc
913 "an association list describing new bindings for special variables
914 to be used by the compiler for error-reporting, etc. Eg.
916 ((*PRINT-LENGTH* . 10) (*PRINT-LEVEL* . 6) (*PRINT-PRETTY* . NIL))
918 The variables in the CAR positions are bound to the values in the CDR
919 during the execution of some debug commands. When evaluating arbitrary
920 expressions in the debugger, the normal values of the printer control
921 variables are in effect.
923 Initially empty, *COMPILER-PRINT-VARIABLE-ALIST* is Typically used to
924 specify bindings for printer control variables.")
926 (defmacro with-compiler-io-syntax (&body forms)
927 `(with-sane-io-syntax
928 (progv
929 (nreverse (mapcar #'car *compiler-print-variable-alist*))
930 (nreverse (mapcar #'cdr *compiler-print-variable-alist*))
931 ,@forms)))