/[cmucl]/src/compiler/macros.lisp
ViewVC logotype

Contents of /src/compiler/macros.lisp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.26 - (hide annotations)
Tue Nov 12 14:13:22 1991 UTC (22 years, 5 months ago) by ram
Branch: MAIN
Changes since 1.25: +7 -4 lines
Changed the :EVAL-NAME option to DEFTRANSFORM to also eval the argument and
result type specs.
1 wlott 1.1 ;;; -*- Package: C; Log: C.Log -*-
2     ;;;
3     ;;; **********************************************************************
4 ram 1.23 ;;; This code was written as part of the CMU Common Lisp project at
5     ;;; Carnegie Mellon University, and has been placed in the public domain.
6     ;;; If you want to use this code or any part of CMU Common Lisp, please contact
7     ;;; Scott Fahlman or slisp-group@cs.cmu.edu.
8     ;;;
9     (ext:file-comment
10 ram 1.26 "$Header: /tiger/var/lib/cvsroots/cmucl/src/compiler/macros.lisp,v 1.26 1991/11/12 14:13:22 ram Exp $")
11 ram 1.23 ;;;
12 wlott 1.1 ;;; **********************************************************************
13     ;;;
14     ;;; Random types and macros used in writing the compiler.
15     ;;;
16     ;;; Written by Rob MacLachlan
17     ;;;
18     (in-package 'c)
19    
20     (export '(lisp::with-compilation-unit) "LISP")
21    
22 wlott 1.12 (export '(policy symbolicate def-ir1-translator def-source-transform
23     def-primitive-translator deftransform defknown defoptimizer
24     derive-type optimizer ltn-annotate ir2-convert attributes
25     def-boolean-attribute attributes-union attributes-intersection
26     attributes=))
27    
28 wlott 1.1 (proclaim '(special *wild-type* *universal-type* *compiler-error-context*))
29    
30     ;;;; Deftypes:
31    
32     ;;;
33     ;;; Should be standard:
34     (deftype boolean () '(member t nil))
35    
36     ;;;
37     ;;; Inlinep is used to determine how a function is called. The values have
38     ;;; these meanings:
39     ;;; Nil No declaration seen: do whatever you feel like, but don't dump
40     ;;; an inline expansion.
41     ;;;
42     ;;; :Notinline Notinline declaration seen: always do full function call.
43     ;;;
44     ;;; :Inline Inline declaration seen: save expansion, expanding to it if
45     ;;; policy favors.
46     ;;;
47     ;;; :Maybe-Inline
48     ;;; Retain expansion, but only use it opportunistically.
49     ;;;
50     (deftype inlinep () '(member :inline :maybe-inline :notinline nil))
51    
52    
53     ;;;; The Policy macro:
54    
55 ram 1.7 (proclaim '(special *lexical-environment*))
56 wlott 1.1
57 ram 1.22 (eval-when (compile load eval)
58 wlott 1.1 (defconstant policy-parameter-slots
59     '((speed . cookie-speed) (space . cookie-space) (safety . cookie-safety)
60     (cspeed . cookie-cspeed) (brevity . cookie-brevity)
61     (debug . cookie-debug)))
62    
63     ;;; Find-Used-Parameters -- Internal
64     ;;;
65     ;;; Find all the policy parameters which are actually mentioned in Stuff,
66     ;;; returning the names in a list. We assume everything is evaluated.
67     ;;;
68     (defun find-used-parameters (stuff)
69     (if (atom stuff)
70     (if (assoc stuff policy-parameter-slots) (list stuff) ())
71     (collect ((res () nunion))
72     (dolist (arg (cdr stuff) (res))
73     (res (find-used-parameters arg))))))
74    
75     ); Eval-When (Compile Load Eval)
76    
77     ;;; Policy -- Public
78     ;;;
79     ;;; This macro provides some syntactic sugar for querying the settings of
80     ;;; the compiler policy parameters.
81     ;;;
82     (defmacro policy (node &rest conditions)
83     "Policy Node Condition*
84     Test whether some conditions apply to the current compiler policy for Node.
85     Each condition is a predicate form which accesses the policy values by
86     referring to them as the variables SPEED, SPACE, SAFETY, CSPEED, BREVITY and
87     DEBUG. The results of all the conditions are combined with AND and returned
88     as the result.
89    
90     Node is a form which is evaluated to obtain the node which the policy is for.
91     If Node is NIL, then we use the current policy as defined by *default-cookie*
92     and *current-cookie*. This option is only well defined during IR1
93     conversion."
94     (let* ((form `(and ,@conditions))
95 ram 1.7 (n-cookie (gensym))
96 wlott 1.1 (binds (mapcar
97     #'(lambda (name)
98     (let ((slot (cdr (assoc name policy-parameter-slots))))
99 ram 1.7 `(,name (,slot ,n-cookie))))
100 wlott 1.1 (find-used-parameters form))))
101 ram 1.7 `(let* ((,n-cookie (lexenv-cookie
102     ,(if node
103     `(node-lexenv ,node)
104     '*lexical-environment*)))
105     ,@binds)
106     ,form)))
107 wlott 1.1
108    
109     ;;;; Source-hacking defining forms:
110    
111 ram 1.22 (eval-when (compile load eval)
112 wlott 1.1
113     ;;; Symbolicate -- Interface
114     ;;;
115     ;;; Concatenate together the names of some strings and symbols, producing
116     ;;; a symbol in the current package.
117     ;;;
118     (proclaim '(function symbolicate (&rest (or string symbol)) symbol))
119     (defun symbolicate (&rest things)
120     (values (intern (reduce #'(lambda (x y)
121     (concatenate 'string (string x) (string y)))
122     things))))
123    
124     ); Eval-When (Compile Load Eval)
125    
126 ram 1.10 ;;; SPECIAL-FORM-FUNCTION -- Internal
127     ;;;
128     ;;; This function is stored in the SYMBOL-FUNCTION of special form names so
129     ;;; that they are FBOUND.
130     ;;;
131     (defun special-form-function (&rest stuff)
132     (declare (ignore stuff))
133     (error "Can't funcall the SYMBOL-FUNCTION of special forms."))
134    
135 wlott 1.19 ;;; CONVERT-CONDITION-INTO-COMPILER-ERROR -- Internal
136 wlott 1.16 ;;;
137 wlott 1.19 ;;; Passed to parse-defmacro when we want compiler errors instead of real
138     ;;; errors.
139     ;;;
140     (proclaim '(inline convert-condition-into-compiler-error))
141     (defun convert-condition-into-compiler-error (datum &rest stuff)
142     (if (stringp datum)
143     (apply #'compiler-error datum stuff)
144     (compiler-error "~A"
145     (if (symbolp datum)
146     (apply #'make-condition datum stuff)
147     datum))))
148 wlott 1.16
149 wlott 1.1 ;;; Def-IR1-Translator -- Interface
150     ;;;
151     ;;; Parse defmacro style lambda-list, setting things up so that a compiler
152     ;;; error happens if the syntax is invalid.
153     ;;;
154     (defmacro def-ir1-translator (name (lambda-list start-var cont-var
155     &key (kind :special-form))
156     &body body)
157     "Def-IR1-Translator Name (Lambda-List Start-Var Cont-Var {Key Value}*)
158     [Doc-String] Form*
159     Define a function that converts a Special-Form or other magical thing into
160     IR1. Lambda-List is a defmacro style lambda list. Start-Var and Cont-Var
161     are bound to the start and result continuations for the resulting IR1.
162     This keyword is defined:
163     Kind
164     The function kind to associate with Name (default :special-form)."
165     (let ((fn-name (symbolicate "IR1-CONVERT-" name))
166     (n-form (gensym))
167     (n-env (gensym)))
168 wlott 1.15 (multiple-value-bind
169     (body decls doc)
170 wlott 1.17 (lisp::parse-defmacro lambda-list n-form body name "special form"
171 wlott 1.15 :doc-string-allowed t
172 wlott 1.16 :environment n-env
173 wlott 1.19 :error-fun 'convert-condition-into-compiler-error)
174 wlott 1.1 `(progn
175     (proclaim '(function ,fn-name (continuation continuation t) void))
176     (defun ,fn-name (,start-var ,cont-var ,n-form)
177 ram 1.7 (let ((,n-env *lexical-environment*))
178 wlott 1.1 ,@decls
179 wlott 1.16 ,body))
180 wlott 1.1 ,@(when doc
181     `((setf (documentation ',name 'function) ,doc)))
182     (setf (info function ir1-convert ',name) #',fn-name)
183 ram 1.10 (setf (info function kind ',name) ,kind)
184     #+new-compiler
185     ,@(when (eq kind :special-form)
186     `((setf (symbol-function ',name) #'special-form-function)))))))
187 wlott 1.1
188    
189     ;;; Def-Source-Transform -- Interface
190     ;;;
191     ;;; Similar to Def-IR1-Translator, except that we pass if the syntax is
192     ;;; invalid.
193     ;;;
194     (defmacro def-source-transform (name lambda-list &body body)
195     "Def-Source-Transform Name Lambda-List Form*
196     Define a macro-like source-to-source transformation for the function Name.
197     A source transform may \"pass\" by returning a non-nil second value. If the
198     transform passes, then the form is converted as a normal function call. If
199     the supplied arguments are not compatible with the specified lambda-list,
200     then the transform automatically passes.
201    
202     Source-Transforms may only be defined for functions. Source transformation
203     is not attempted if the function is declared Notinline. Source transforms
204     should not examine their arguments. If it matters how the function is used,
205     then Deftransform should be used to define an IR1 transformation.
206    
207     If the desirability of the transformation depends on the current Optimize
208     parameters, then the Policy macro should be used to determine when to pass."
209     (let ((fn-name (symbolicate "SOURCE-TRANSFORM-" name))
210     (n-form (gensym))
211     (n-env (gensym)))
212 wlott 1.15 (multiple-value-bind
213     (body decls)
214 wlott 1.17 (lisp::parse-defmacro lambda-list n-form body name "form"
215 wlott 1.16 :environment n-env
216     :error-fun `(lambda (&rest stuff)
217     (declare (ignore stuff))
218     (return-from ,fn-name
219     (values nil t))))
220 wlott 1.1 `(progn
221     (defun ,fn-name (,n-form)
222 ram 1.7 (let ((,n-env *lexical-environment*))
223 wlott 1.1 ,@decls
224 wlott 1.16 ,body))
225 wlott 1.1 (setf (info function source-transform ',name) #',fn-name)))))
226    
227    
228     (defmacro def-primitive-translator (name lambda-list &body body)
229     "Def-Primitive-Translator Name Lambda-List Form*
230     Define a function that converts a use of (%PRIMITIVE Name ...) into Lisp
231     code. Lambda-List is a defmacro style lambda list."
232     (let ((fn-name (symbolicate "PRIMITIVE-TRANSLATE-" name))
233     (n-form (gensym))
234     (n-env (gensym)))
235 wlott 1.15 (multiple-value-bind
236     (body decls)
237 wlott 1.17 (lisp::parse-defmacro lambda-list n-form body name "%primitive"
238 wlott 1.16 :environment n-env
239 wlott 1.19 :error-fun 'convert-condition-into-compiler-error)
240 wlott 1.1 `(progn
241     (defun ,fn-name (,n-form)
242 ram 1.7 (let ((,n-env *lexical-environment*))
243 wlott 1.1 ,@decls
244 wlott 1.16 ,body))
245 wlott 1.1 (setf (gethash ',name *primitive-translators*) ',fn-name)))))
246    
247    
248     ;;;; Lambda-list parsing utilities:
249     ;;;
250     ;;; IR1 transforms, optimizers and type inferencers need to be able to parse
251     ;;; the IR1 representation of a function call using a standard function
252     ;;; lambda-list.
253    
254    
255 ram 1.22 (eval-when (compile load eval)
256 wlott 1.1
257     ;;; Parse-Deftransform -- Internal
258     ;;;
259     ;;; Given a deftransform style lambda-list, generate code that parses the
260     ;;; arguments of a combination with respect to that lambda-list. Body is the
261     ;;; the list of forms which are to be evaluated within the bindings. Args is
262     ;;; the variable that holds list of argument continuations. Error-Form is a
263     ;;; form which is evaluated when the syntax of the supplied arguments is
264     ;;; incorrect or a non-constant argument keyword is supplied. Defaults and
265     ;;; other gunk are ignored. The second value is a list of all the arguments
266     ;;; bound. We make the variables IGNORABLE so that we don't have to manually
267     ;;; declare them Ignore if their only purpose is to make the syntax work.
268     ;;;
269     (proclaim '(function parse-deftransform (list list symbol t) list))
270     (defun parse-deftransform (lambda-list body args error-form)
271     (multiple-value-bind (req opt restp rest keyp keys allowp)
272     (parse-lambda-list lambda-list)
273     (let* ((min-args (length req))
274     (max-args (+ min-args (length opt)))
275     (n-keys (gensym)))
276     (collect ((binds)
277     (vars)
278     (pos 0 +)
279     (keywords))
280     (dolist (arg req)
281     (vars arg)
282     (binds `(,arg (nth ,(pos) ,args)))
283     (pos 1))
284    
285     (dolist (arg opt)
286     (let ((var (if (atom arg) arg (first arg))))
287     (vars var)
288     (binds `(,var (nth ,(pos) ,args)))
289     (pos 1)))
290    
291     (when restp
292     (vars rest)
293     (binds `(,rest (nthcdr ,(pos) ,args))))
294    
295     (dolist (spec keys)
296     (if (or (atom spec) (atom (first spec)))
297     (let* ((var (if (atom spec) spec (first spec)))
298     (key (intern (symbol-name var) "KEYWORD")))
299     (vars var)
300     (binds `(,var (find-keyword-continuation ,n-keys ,key)))
301     (keywords key))
302     (let* ((head (first spec))
303     (var (second head))
304     (key (first head)))
305     (vars var)
306     (binds `(,var (find-keyword-continuation ,n-keys ,key)))
307     (keywords key))))
308    
309     (let ((n-length (gensym))
310     (limited-legal (not (or restp keyp))))
311     (values
312     `(let ((,n-length (length ,args))
313     ,@(when keyp `((,n-keys (nthcdr ,(pos) ,args)))))
314     (unless (and
315     ,(if limited-legal
316     `(<= ,min-args ,n-length ,max-args)
317     `(<= ,min-args ,n-length))
318     ,@(when keyp
319     (if allowp
320     `((check-keywords-constant ,n-keys))
321     `((check-transform-keys ,n-keys ',(keywords))))))
322     ,error-form)
323     (let ,(binds)
324     ;;; ### Bootstrap hack...
325     #+new-compiler
326     (declare (ignorable ,@(vars)))
327     #-new-compiler
328     (progn ,@(vars))
329     ,@body))
330     (vars)))))))
331    
332     ); Eval-When (Compile Load Eval)
333    
334    
335     ;;;; Utilities used at run-time for parsing keyword args in IR1:
336    
337     ;;; Find-Keyword-Continuation -- Internal
338     ;;;
339     ;;; This function is used by the result of Parse-Deftransform to find the
340     ;;; continuation for the value of the keyword argument Key in the list of
341     ;;; continuations Args. It returns the continuation if the keyword is present,
342     ;;; or NIL otherwise. The legality and constantness of the keywords should
343     ;;; already have been checked.
344     ;;;
345     (proclaim '(function find-keyword-continuation (list keyword) (or continuation null)))
346     (defun find-keyword-continuation (args key)
347     (do ((arg args (cddr arg)))
348     ((null arg) nil)
349     (when (eq (continuation-value (first arg)) key)
350     (return (second arg)))))
351    
352    
353     ;;; Check-Keywords-Constant -- Internal
354     ;;;
355     ;;; This function is used by the result of Parse-Deftransform to verify that
356     ;;; alternating continuations in Args are constant and that there is an even
357     ;;; number of args.
358     ;;;
359     (proclaim '(function check-keywords-constant (list) boolean))
360     (defun check-keywords-constant (args)
361     (do ((arg args (cddr arg)))
362     ((null arg) t)
363     (unless (and (rest arg)
364     (constant-continuation-p (first arg)))
365     (return nil))))
366    
367    
368     ;;; Check-Transform-Keys -- Internal
369     ;;;
370     ;;; This function is used by the result of Parse-Deftransform to verify that
371     ;;; the list of continuations Args is a well-formed keyword arglist and that
372     ;;; only keywords present in the list Keys are supplied.
373     ;;;
374     (proclaim '(function check-transform-keys (list list) boolean))
375     (defun check-transform-keys (args keys)
376     (and (check-keywords-constant args)
377     (do ((arg args (cddr arg)))
378     ((null arg) t)
379     (unless (member (continuation-value (first arg)) keys)
380     (return nil)))))
381    
382    
383     ;;;; Deftransform:
384    
385     ;;; Deftransform -- Interface
386     ;;;
387     ;;; Parse the lambda-list and generate code to test the policy and
388     ;;; automatically create the result lambda.
389     ;;;
390     (defmacro deftransform (name (lambda-list &optional (arg-types '*) (result-type '*)
391 ram 1.21 &key result policy node defun-only
392     eval-name)
393 ram 1.25 &body (body decls doc))
394 wlott 1.1 "Deftransform Name (Lambda-List [Arg-Types] [Result-Type] {Key Value}*)
395 ram 1.25 Declaration* [Doc-String] Form*
396 wlott 1.1 Define an IR1 transformation for Name. An IR1 transformation computes a
397     lambda that replaces the function variable reference for the call. A
398     transform may pass (decide not to transform the call) by calling the Give-Up
399     function. Lambda-List both determines how the current call is parsed and
400     specifies the Lambda-List for the resulting lambda.
401    
402     We parse the call and bind each of the lambda-list variables to the
403     continuation which represents the value of the argument. When parsing the
404     call, we ignore the defaults, and always bind the variables for unsupplied
405     arguments to NIL. If a required argument is missing, an unknown keyword is
406     supplied, or an argument keyword is not a constant, then the transform
407     automatically passes. The Declarations apply to the bindings made by
408     Deftransform at transformation time, rather than to the variables of the
409     resulting lambda. Bound-but-not-referenced warnings are suppressed for the
410 ram 1.25 lambda-list variables. The Doc-String is used when printing efficiency notes
411     about the defined transform.
412 wlott 1.1
413     Normally, the body evaluates to a form which becomes the body of an
414     automatically constructed lambda. We make Lambda-List the lambda-list for
415     the lambda, and automatically insert declarations of the argument and result
416     types. If the second value of the body is non-null, then it is a list of
417     declarations which are to be inserted at the head of the lambda. Automatic
418     lambda generation may be inhibited by explicitly returning a lambda from the
419     body.
420    
421     The Arg-Types and Result-Type are used to create a function type which the
422     call must satisfy before transformation is attempted. The function type
423     specifier is constructed by wrapping (FUNCTION ...) around these values, so
424     the lack of a restriction may be specified by omitting the argument or
425     supplying *. The argument syntax specified in the Arg-Types need not be the
426     same as that in the Lambda-List, but the transform will never happen if
427     the syntaxes can't be satisfied simultaneously. If there is an existing
428     transform for the same function that has the same type, then it is replaced
429     with the new definition.
430    
431     These are the legal keyword options:
432     :Result - A variable which is bound to the result continuation.
433     :Node - A variable which is bound to the combination node for the call.
434     :Policy - A form which is supplied to the Policy macro to determine whether
435     this transformation is appropriate. If the result is false, then
436     the transform automatically passes.
437 ram 1.21 :Eval-Name
438 ram 1.26 - The name and argument/result types are actually forms to be
439     evaluated. Useful for getting closures that transform similar
440     functions.
441 wlott 1.1 :Defun-Only
442     - Don't actually instantiate a transform, instead just DEFUN
443     Name with the specified transform definition function. This may
444     be later instantiated with %Deftransform."
445    
446 ram 1.21 (when (and eval-name defun-only)
447     (error "Can't specify both DEFUN-ONLY and EVAL-NAME."))
448 wlott 1.1 (let ((n-args (gensym))
449     (n-node (or node (gensym)))
450     (n-decls (gensym))
451 ram 1.25 (n-lambda (gensym))
452     (body `(,@decls ,@body)))
453 wlott 1.1 (multiple-value-bind (parsed-form vars)
454     (parse-deftransform
455     lambda-list
456     (if policy
457 ram 1.11 `((unless (policy ,n-node ,policy) (give-up))
458 wlott 1.1 ,@body)
459     body)
460     n-args '(give-up))
461     (let ((stuff
462     `((,n-node)
463     (let* ((,n-args (basic-combination-args ,n-node))
464     ,@(when result
465     `((,result (node-cont ,n-node)))))
466     (multiple-value-bind (,n-lambda ,n-decls)
467     ,parsed-form
468     (if (and (consp ,n-lambda) (eq (car ,n-lambda) 'lambda))
469     ,n-lambda
470     `(lambda ,',lambda-list
471     (declare (ignorable ,@',vars))
472     ,@,n-decls
473     ,,n-lambda)))))))
474     (if defun-only
475 ram 1.25 `(defun ,name ,@(when doc `(,doc)) ,@stuff)
476 wlott 1.1 `(%deftransform
477 ram 1.21 ,(if eval-name name `',name)
478 ram 1.26 ,(if eval-name
479     ``(function ,,arg-types ,,result-type)
480     `'(function ,arg-types ,result-type))
481 ram 1.25 #'(lambda ,@stuff)
482     ,doc))))))
483 wlott 1.1
484     ;;;; Defknown, Defoptimizer:
485    
486     ;;; Defknown -- Interface
487     ;;;
488     ;;; This macro should be the way that all implementation independent
489     ;;; information about functions is made known to the compiler.
490     ;;;
491     (defmacro defknown (name arg-types result-type &optional (attributes '(any))
492     &rest keys)
493     "Defknown Name Arg-Types Result-Type [Attributes] {Key Value}*
494     Declare the function Name to be a known function. We construct a type
495     specifier for the function by wrapping (FUNCTION ...) around the Arg-Types
496     and Result-Type. Attributes is a an unevaluated list of the boolean
497     attributes that the function has. These attributes are meaningful here:
498     call
499     May call functions that are passed as arguments. In order to determine
500     what other effects are present, we must find the effects of all arguments
501     that may be functions.
502    
503     unsafe
504     May incorporate arguments in the result or somehow pass them upward.
505    
506     unwind
507     May fail to return during correct execution. Errors are O.K.
508    
509     any
510     The (default) worst case. Includes all the other bad things, plus any
511     other possible bad thing.
512    
513     foldable
514     May be constant-folded. The function has no side effects, but may be
515     affected by side effects on the arguments. e.g. SVREF, MAPC.
516    
517     flushable
518     May be eliminated if value is unused. The function has no side effects
519     except possibly CONS. If a function is defined to signal errors, then
520     it is not flushable even if it is movable or foldable.
521    
522     movable
523     May be moved with impunity. Has no side effects except possibly CONS,
524     and is affected only by its arguments.
525    
526     predicate
527     A true predicate likely to be open-coded. This is a hint to IR1
528     conversion that it should ensure calls always appear as an IF test.
529     Not usually specified to Defknown, since this is implementation
530     dependent, and is usually automatically set by the Define-VOP
531     :Conditional option.
532    
533     Name may also be a list of names, in which case the same information is given
534     to all the names. The keywords specify the initial values for various
535     optimizers that the function might have."
536     (when (and (intersection attributes '(any call unwind))
537     (intersection attributes '(movable)))
538     (error "Function cannot have both good and bad attributes: ~S" attributes))
539    
540     `(%defknown ',(if (and (consp name)
541     (not (eq (car name) 'setf)))
542     name
543     (list name))
544     '(function ,arg-types ,result-type)
545     (ir1-attributes ,@(if (member 'any attributes)
546     (union '(call unsafe unwind) attributes)
547     attributes))
548     ,@keys))
549    
550    
551     ;;; Defoptimizer -- Interface
552     ;;;
553     ;;; Create a function which parses combination args according to a
554     ;;; Lambda-List, optionally storing it in a function-info slot.
555     ;;;
556     (defmacro defoptimizer (what (lambda-list &optional (n-node (gensym))
557     &rest vars)
558     &body body)
559     "Defoptimizer (Function Kind) (Lambda-List [Node-Var] Var*)
560     Declaration* Form*
561     Define some Kind of optimizer for the named Function. Function must be a
562     known function. Lambda-List is used to parse the arguments to the
563     combination as in Deftransform. If the argument syntax is invalid or there
564     are non-constant keys, then we simply return NIL.
565    
566     The function is DEFUN'ed as Function-Kind-OPTIMIZER. Possible kinds are
567     DERIVE-TYPE, OPTIMIZER, LTN-ANNOTATE and IR2-CONVERT. If a symbol is
568     specified instead of a (Function Kind) list, then we just do a DEFUN with the
569     symbol as its name, and don't do anything with the definition. This is
570     useful for creating optimizers to be passed by name to DEFKNOWN.
571    
572     If supplied, Node-Var is bound to the combination node being optimized. If
573     additional Vars are supplied, then they are used as the rest of the optimizer
574     function's lambda-list. LTN-ANNOTATE methods are passed an additional POLICY
575     argument, and IR2-CONVERT methods are passed an additional IR2-BLOCK
576     argument."
577    
578     (let ((name (if (symbolp what) what
579     (symbolicate (first what) "-" (second what) "-OPTIMIZER"))))
580    
581     (let ((n-args (gensym)))
582     `(progn
583     (defun ,name (,n-node ,@vars)
584     (let ((,n-args (basic-combination-args ,n-node)))
585     ,(parse-deftransform lambda-list body n-args
586     `(return-from ,name nil))))
587     ,@(when (consp what)
588     `((setf (,(symbolicate "FUNCTION-INFO-" (second what))
589     (function-info-or-lose ',(first what)))
590     #',name)))))))
591    
592    
593     ;;;; IR groveling macros:
594    
595     ;;; Do-Blocks, Do-Blocks-Backwards -- Interface
596     ;;;
597     (defmacro do-blocks ((block-var component &optional ends result) &body body)
598     "Do-Blocks (Block-Var Component [Ends] [Result-Form]) {Declaration}* {Form}*
599     Iterate over the blocks in a component, binding Block-Var to each block in
600     turn. The value of Ends determines whether to iterate over dummy head and
601     tail blocks:
602     NIL -- Skip Head and Tail (the default)
603     :Head -- Do head but skip tail
604     :Tail -- Do tail but skip head
605     :Both -- Do both head and tail
606    
607     If supplied, Result-Form is the value to return."
608     (unless (member ends '(nil :head :tail :both))
609     (error "Losing Ends value: ~S." ends))
610     (let ((n-component (gensym))
611     (n-tail (gensym)))
612     `(let* ((,n-component ,component)
613     (,n-tail ,(if (member ends '(:both :tail))
614     nil
615     `(component-tail ,n-component))))
616     (do ((,block-var ,(if (member ends '(:both :head))
617     `(component-head ,n-component)
618     `(block-next (component-head ,n-component)))
619     (block-next ,block-var)))
620     ((eq ,block-var ,n-tail) ,result)
621     ,@body))))
622     ;;;
623     (defmacro do-blocks-backwards ((block-var component &optional ends result) &body body)
624     "Do-Blocks-Backwards (Block-Var Component [Ends] [Result-Form]) {Declaration}* {Form}*
625     Like Do-Blocks, only iterate over the blocks in reverse order."
626     (unless (member ends '(nil :head :tail :both))
627     (error "Losing Ends value: ~S." ends))
628     (let ((n-component (gensym))
629     (n-head (gensym)))
630     `(let* ((,n-component ,component)
631     (,n-head ,(if (member ends '(:both :head))
632     nil
633     `(component-head ,n-component))))
634     (do ((,block-var ,(if (member ends '(:both :tail))
635     `(component-tail ,n-component)
636     `(block-prev (component-tail ,n-component)))
637     (block-prev ,block-var)))
638     ((eq ,block-var ,n-head) ,result)
639     ,@body))))
640    
641    
642     ;;; Do-Uses -- Interface
643     ;;;
644     ;;; Could change it not to replicate the code someday perhaps...
645     ;;;
646     (defmacro do-uses ((node-var continuation &optional result) &body body)
647     "Do-Uses (Node-Var Continuation [Result]) {Declaration}* {Form}*
648     Iterate over the uses of Continuation, binding Node to each one succesively."
649     (once-only ((n-cont continuation))
650     `(ecase (continuation-kind ,n-cont)
651     (:unused)
652     (:inside-block
653     (block nil
654     (let ((,node-var (continuation-use ,n-cont)))
655     ,@body
656     ,result)))
657     ((:block-start :deleted-block-start)
658     (dolist (,node-var (block-start-uses (continuation-block ,n-cont))
659     ,result)
660     ,@body)))))
661    
662    
663     ;;; Do-Nodes, Do-Nodes-Backwards -- Interface
664     ;;;
665     ;;; In the forward case, we terminate on Last-Cont so that we don't have to
666     ;;; worry about our termination condition being changed when new code is added
667 ram 1.20 ;;; during the iteration. In the backward case, we do NODE-PREV before
668 wlott 1.1 ;;; evaluating the body so that we can keep going when the current node is
669     ;;; deleted.
670     ;;;
671 ram 1.20 ;;; When Restart-P is supplied to DO-NODES, we start iterating over again at
672     ;;; the beginning of the block when we run into a continuation whose block
673     ;;; differs from the one we are trying to iterate over, either beacuse the
674     ;;; block was split, or because a node was deleted out from under us (hence its
675     ;;; block is NIL.) If the block start is deleted, we just punt. With
676     ;;; Restart-P, we are also more careful about termination, re-indirecting the
677     ;;; BLOCK-LAST each time.
678     ;;;
679     (defmacro do-nodes ((node-var cont-var block &key restart-p) &body body)
680     "Do-Nodes (Node-Var Cont-Var Block {Key Value}*) {Declaration}* {Form}*
681 wlott 1.1 Iterate over the nodes in Block, binding Node-Var to the each node and
682 ram 1.20 Cont-Var to the node's Cont. The only keyword option is Restart-P, which
683     causes iteration to be restarted when a node is deleted out from under us (if
684     not supplied, this is an error.)"
685 wlott 1.1 (let ((n-block (gensym))
686 ram 1.20 (n-last-cont (gensym)))
687 wlott 1.1 `(let* ((,n-block ,block)
688 ram 1.20 ,@(unless restart-p
689     `((,n-last-cont (node-cont (block-last ,n-block))))))
690 wlott 1.1 (do* ((,node-var (continuation-next (block-start ,n-block))
691 ram 1.20 ,(if restart-p
692     `(cond
693     ((eq (continuation-block ,cont-var) ,n-block)
694     (assert (continuation-next ,cont-var))
695     (continuation-next ,cont-var))
696     (t
697     (let ((start (block-start ,n-block)))
698     (unless (eq (continuation-kind start)
699     :block-start)
700     (return nil))
701     (continuation-next start))))
702     `(continuation-next ,cont-var)))
703 wlott 1.1 (,cont-var (node-cont ,node-var) (node-cont ,node-var)))
704     (())
705     ,@body
706 ram 1.20 (when ,(if restart-p
707     `(eq ,node-var (block-last ,n-block))
708     `(eq ,cont-var ,n-last-cont))
709     (return nil))))))
710 wlott 1.1 ;;;
711 ram 1.20 (defmacro do-nodes-backwards ((node-var cont-var block) &body body)
712     "Do-Nodes-Backwards (Node-Var Cont-Var Block) {Declaration}* {Form}*
713 wlott 1.1 Like Do-Nodes, only iterates in reverse order."
714     (let ((n-block (gensym))
715     (n-start (gensym))
716     (n-last (gensym))
717     (n-next (gensym)))
718     `(let* ((,n-block ,block)
719     (,n-start (block-start ,n-block))
720     (,n-last (block-last ,n-block)))
721     (do* ((,cont-var (node-cont ,n-last) ,n-next)
722     (,node-var ,n-last (continuation-use ,cont-var))
723     (,n-next (node-prev ,node-var) (node-prev ,node-var)))
724     (())
725     ,@body
726     (when (eq ,n-next ,n-start)
727 ram 1.20 (return nil))))))
728 wlott 1.1
729    
730     ;;; With-IR1-Environment -- Interface
731     ;;;
732     ;;; The lexical environment is presumably already null...
733     ;;;
734     (defmacro with-ir1-environment (node &rest forms)
735     "With-IR1-Environment Node Form*
736     Bind the IR1 context variables so that IR1 conversion can be done after the
737 ram 1.7 main conversion pass has finished."
738     (let ((n-node (gensym)))
739 wlott 1.1 `(let* ((,n-node ,node)
740 ram 1.7 (*current-component* (block-component (node-block ,n-node)))
741     (*lexical-environment* (node-lexenv ,n-node))
742     (*current-path* (node-source-path ,n-node)))
743 wlott 1.1 ,@forms)))
744    
745    
746     ;;; WITH-IR1-NAMESPACE -- Interface
747     ;;;
748     ;;; Bind the hashtables used for keeping track of global variables,
749     ;;; functions, &c.
750     ;;;
751     (defmacro with-ir1-namespace (&body forms)
752     `(let ((*free-variables* (make-hash-table :test #'eq))
753     (*free-functions* (make-hash-table :test #'equal))
754     (*constants* (make-hash-table :test #'equal))
755 ram 1.9 (*source-paths* (make-hash-table :test #'eq))
756     (*failed-optimizations* (make-hash-table :test #'eq)))
757 wlott 1.1 ,@forms))
758    
759 ram 1.7
760     ;;; LEXENV-FIND -- Interface
761     ;;;
762     (defmacro lexenv-find (name slot &key test)
763     "LEXENV-FIND Name Slot {Key Value}*
764     Look up Name in the lexical environment namespace designated by Slot,
765     returning the <value, T>, or <NIL, NIL> if no entry. The :TEST keyword
766     may be used to determine the name equality predicate."
767     (once-only ((n-res `(assoc ,name (,(symbolicate "LEXENV-" slot)
768     *lexical-environment*)
769     ,@(when test `(:test ,test)))))
770     `(if ,n-res
771     (values (cdr ,n-res) t)
772     (values nil nil))))
773    
774 wlott 1.1
775     ;;;; The Defprinter macro:
776    
777     (defvar *defprint-pretty* nil
778     "If true, defprinter print functions print each slot on a separate line.")
779    
780    
781     ;;; Defprinter-Prin1, Defprinter-Princ -- Internal
782     ;;;
783     ;;; These functions are called by the expansion of the Defprinter
784     ;;; macro to do the actual printing.
785     ;;;
786 ram 1.20 (proclaim '(ftype (function (symbol t stream &optional t) void)
787 wlott 1.1 defprinter-prin1 defprinter-princ))
788 wlott 1.14 (defun defprinter-prin1 (name value stream &optional indent)
789     (declare (ignore indent))
790     (write-string " " stream)
791     (when *print-pretty*
792     (xp:pprint-newline :linear stream))
793     (princ name stream)
794     (write-string "= " stream)
795     (prin1 value stream))
796 wlott 1.1 ;;;
797 wlott 1.14 (defun defprinter-princ (name value stream &optional indent)
798 wlott 1.1 (declare (ignore indent))
799 wlott 1.14 (write-string " " stream)
800     (when *print-pretty*
801     (xp:pprint-newline :linear stream))
802     (princ name stream)
803     (write-string "= " stream)
804     (princ value stream))
805 wlott 1.1
806     (defmacro defprinter (name &rest slots)
807     "Defprinter Name Slot-Desc*
808     Define some kind of reasonable defstruct structure-print function. Name
809     is the name of the structure. We define a function %PRINT-name which
810     prints the slots in the structure in the way described by the Slot-Descs.
811     Each Slot-Desc can be a slot name, indicating that the slot should simply
812     be printed. A Slot-Desc may also be a list of a slot name and other stuff.
813     The other stuff is composed of keywords followed by expressions. The
814     expressions are evaluated with the variable which is the slot name bound
815     to the value of the slot. These keywords are defined:
816    
817     :PRIN1 Print the value of the expression instead of the slot value.
818     :PRINC Like :PRIN1, only princ the value
819     :TEST Only print something if the test is true.
820    
821     If no printing thing is specified then the slot value is printed as PRIN1.
822    
823     The structure being printed is bound to Structure and the stream is bound to
824     Stream."
825    
826 wlott 1.14 (flet ((sref (slot) `(,(symbolicate name "-" slot) structure)))
827     (collect ((prints))
828     (dolist (slot slots)
829     (if (atom slot)
830     (prints `(defprinter-prin1 ',slot ,(sref slot) stream))
831     (let ((sname (first slot))
832     (test t))
833     (collect ((stuff))
834     (do ((option (rest slot) (cddr option)))
835     ((null option)
836     (prints
837     `(let ((,sname ,(sref sname)))
838     (when ,test
839     ,@(or (stuff)
840     `((defprinter-prin1 ',sname ,sname
841     stream)))))))
842     (case (first option)
843     (:prin1
844     (stuff `(defprinter-prin1 ',sname ,(second option)
845     stream)))
846     (:princ
847     (stuff `(defprinter-princ ',sname ,(second option)
848     stream)))
849     (:test (setq test (second option)))
850     (t
851     (error "Losing Defprinter option: ~S."
852     (first option)))))))))
853    
854     `(defun ,(symbolicate "%PRINT-" name) (structure stream depth)
855     (flet ((do-prints ()
856     ,@(prints)))
857     (cond (*print-pretty*
858     (xp:pprint-logical-block
859     (stream nil :prefix "#<" :suffix ">")
860     (prin1 ',name stream)
861     (write-char #\space stream)
862     (xp:pprint-indent :current 0 stream)
863     (let ((*print-base* 16)
864     (*print-radix* t))
865     (prin1 (system:%primitive make-fixnum structure)
866     stream))
867     (unless (and *print-level*
868     (<= *print-level* (1+ depth)))
869     (do-prints))))
870     (t
871     (format stream "#<~S ~X"
872     ',name
873     (system:%primitive make-fixnum structure))
874     (let ((*print-level*
875     (if *print-level* (- *print-level* depth 1))))
876     (unless (and *print-level* (<= *print-level* 0))
877     (do-prints)))
878     (format stream ">"))))
879     nil))))
880 wlott 1.1
881    
882     ;;;; Boolean attribute utilities:
883     ;;;
884     ;;; We need to maintain various sets of boolean attributes for known
885     ;;; functions and VOPs. To save space and allow for quick set operations, we
886     ;;; represent them as bits in a fixnum.
887     ;;;
888    
889     (deftype attributes () 'fixnum)
890    
891 ram 1.7 (eval-when (compile load eval)
892 wlott 1.1 ;;; Compute-Attribute-Mask -- Internal
893     ;;;
894     ;;; Given a list of attribute names and an alist that translates them to
895     ;;; masks, return the OR of the masks.
896     ;;;
897     (defun compute-attribute-mask (names alist)
898     (collect ((res 0 logior))
899     (dolist (name names)
900     (let ((mask (cdr (assoc name alist))))
901     (unless mask
902     (error "Unknown attribute name: ~S." name))
903     (res mask)))
904     (res)))
905    
906     ); Eval-When (Compile Load Eval)
907    
908     ;;; Def-Boolean-Attribute -- Interface
909     ;;;
910     ;;; Parse the specification and generate some accessor macros.
911     ;;;
912     (defmacro def-boolean-attribute (name &rest attribute-names)
913     "Def-Boolean-Attribute Name Attribute-Name*
914     Define a new class of boolean attributes, with the attributes havin the
915     specified Attribute-Names. Name is the name of the class, which is used to
916     generate some macros to manipulate sets of the attributes:
917    
918     NAME-attributep attributes attribute-name*
919     Return true if one of the named attributes is present, false otherwise.
920 ram 1.7 When set with SETF, updates the place Attributes setting or clearing the
921     specified attributes.
922 wlott 1.1
923     NAME-attributes attribute-name*
924     Return a set of the named attributes."
925    
926 ram 1.7 (let ((const-name (symbolicate name "-ATTRIBUTE-TRANSLATIONS"))
927     (test-name (symbolicate name "-ATTRIBUTEP")))
928 wlott 1.1 (collect ((alist))
929     (do ((mask 1 (ash mask 1))
930     (names attribute-names (cdr names)))
931     ((null names))
932     (alist (cons (car names) mask)))
933    
934     `(progn
935 ram 1.7 (eval-when (compile load eval)
936     (defconstant ,const-name ',(alist)))
937    
938     (defmacro ,test-name (attributes &rest attribute-names)
939     "Automagically generated boolean attribute test function. See
940     Def-Boolean-Attribute."
941     `(logtest ,(compute-attribute-mask attribute-names ,const-name)
942     (the attributes ,attributes)))
943 wlott 1.1
944 ram 1.7 (define-setf-method ,test-name (place &rest attributes
945     &environment env)
946    
947     "Automagically generated boolean attribute setter. See
948     Def-Boolean-Attribute."
949     (multiple-value-bind (temps values stores set get)
950 ram 1.24 (get-setf-method place env)
951 ram 1.7 (let ((newval (gensym))
952     (n-place (gensym))
953     (mask (compute-attribute-mask attributes ,const-name)))
954     (values `(,@temps ,n-place)
955     `(,@values ,get)
956     `(,newval)
957     `(let ((,(first stores)
958     (if ,newval
959     (logior ,n-place ,mask)
960     (logand ,n-place ,(lognot mask)))))
961     ,set
962     ,newval)
963     `(,',test-name ,n-place ,@attributes)))))
964    
965     (defmacro ,(symbolicate name "-ATTRIBUTES") (&rest attribute-names)
966     "Automagically generated boolean attribute creation function. See
967     Def-Boolean-Attribute."
968     (compute-attribute-mask attribute-names ,const-name))))))
969 wlott 1.1
970    
971     ;;; Attributes-Union, Attributes-Intersection, Attributes= -- Interface
972     ;;;
973     ;;; And now for some gratuitous pseudo-abstraction...
974     ;;;
975     (defmacro attributes-union (&rest attributes)
976     "Returns the union of all the sets of boolean attributes which are its
977     arguments."
978     `(the attributes
979     (logior ,@(mapcar #'(lambda (x) `(the attributes ,x)) attributes))))
980     ;;;
981     (defmacro attributes-intersection (&rest attributes)
982     "Returns the intersection of all the sets of boolean attributes which are its
983     arguments."
984     `(the attributes
985     (logand ,@(mapcar #'(lambda (x) `(the attributes ,x)) attributes))))
986     ;;;
987     (proclaim '(inline attributes=))
988     (proclaim '(function attributes= (attributes attributes) boolean))
989     (defun attributes= (attr1 attr2)
990     "Returns true if the attributes present in Attr1 are indentical to those in
991     Attr2."
992     (eql attr1 attr2))
993    
994    
995     ;;;; The Event statistics/trace utility:
996    
997 ram 1.22 (eval-when (compile load eval)
998 wlott 1.1
999     (defstruct event-info
1000     ;;
1001     ;; The name of this event.
1002 ram 1.18 (name (required-argument) :type symbol)
1003 wlott 1.1 ;;
1004     ;; The string rescribing this event.
1005 ram 1.18 (description (required-argument) :type string)
1006 wlott 1.1 ;;
1007     ;; The name of the variable we stash this in.
1008 ram 1.18 (var (required-argument) :type symbol)
1009 wlott 1.1 ;;
1010     ;; The number of times this event has happened.
1011     (count 0 :type fixnum)
1012     ;;
1013     ;; The level of significance of this event.
1014 ram 1.18 (level (required-argument) :type unsigned-byte)
1015 wlott 1.1 ;;
1016     ;; If true, a function that gets called with the node that the event happened
1017     ;; to.
1018     (action nil :type (or function null)))
1019    
1020     ;;; A hashtable from event names to event-info structures.
1021     ;;;
1022     (defvar *event-info* (make-hash-table :test #'eq))
1023    
1024    
1025     ;;; Event-Info-Or-Lose -- Internal
1026     ;;;
1027     ;;; Return the event info for Name or die trying.
1028     ;;;
1029     (proclaim '(function event-info-or-lose (t) event-info))
1030     (defun event-info-or-lose (name)
1031     (let ((res (gethash name *event-info*)))
1032     (unless res
1033     (error "~S is not the name of an event." name))
1034     res))
1035    
1036     ); Eval-When (Compile Load Eval)
1037    
1038    
1039     ;;; Event-Count, Event-Action, Event-Level -- Interface
1040     ;;;
1041     (proclaim '(function event-count (symbol) fixnum))
1042     (defun event-count (name)
1043     "Return the number of times that Event has happened."
1044     (event-info-count (event-info-or-lose name)))
1045     ;;;
1046     (proclaim '(function event-action (symbol) (or function null)))
1047     (defun event-action (name)
1048     "Return the function that is called when Event happens. If this is null,
1049     there is no action. The function is passed the node to which the event
1050     happened, or NIL if there is no relevant node. This may be set with SETF."
1051     (event-info-action (event-info-or-lose name)))
1052     ;;;
1053     (proclaim '(function %set-event-action (symbol (or function null)) (or function null)))
1054     (defun %set-event-action (name new-value)
1055     (setf (event-info-action (event-info-or-lose name))
1056     new-value))
1057     ;;;
1058     (defsetf event-action %set-event-action)
1059     ;;;
1060     (proclaim '(function event-level (symbol) unsigned-byte))
1061     (defun event-level (name)
1062     "Return the non-negative integer which represents the level of significance
1063     of the event Name. This is used to determine whether to print a message when
1064     the event happens. This may be set with SETF."
1065     (event-info-level (event-info-or-lose name)))
1066     ;;;
1067     (proclaim '(function %set-event-level (symbol unsigned-byte) unsigned-byte))
1068     (defun %set-event-level (name new-value)
1069     (setf (event-info-level (event-info-or-lose name))
1070     new-value))
1071     ;;;
1072     (defsetf event-level %set-event-level)
1073    
1074    
1075     ;;; Defevent -- Interface
1076     ;;;
1077     ;;; Make an event-info structure and stash it in a variable so we can get at
1078     ;;; it quickly.
1079     ;;;
1080     (defmacro defevent (name description &optional (level 0))
1081     "Defevent Name Description
1082     Define a new kind of event. Name is a symbol which names the event and
1083     Description is a string which describes the event. Level (default 0) is the
1084     level of significance associated with this event; it is used to determine
1085     whether to print a Note when the event happens."
1086     (let ((var-name (symbolicate "*" name "-EVENT-INFO*")))
1087     `(eval-when (compile load eval)
1088     (defvar ,var-name
1089     (make-event-info :name ',name :description ',description :var ',var-name
1090     :level ,level))
1091     (setf (gethash ',name *event-info*) ,var-name)
1092     ',name)))
1093    
1094     (proclaim '(type unsigned-byte *event-note-threshold*))
1095     (defvar *event-note-threshold* 1
1096     "This variable is a non-negative integer specifying the lowest level of
1097     event that will print a Note when it occurs.")
1098    
1099     ;;; Event -- Interface
1100     ;;;
1101     ;;; Increment the counter and do any action. Mumble about the event if
1102     ;;; policy indicates.
1103     ;;;
1104     (defmacro event (name &optional node)
1105     "Event Name Node
1106     Note that the event with the specified Name has happened. Node is evaluated
1107     to determine the node to which the event happened."
1108     `(%event ,(event-info-var (event-info-or-lose name)) ,node))
1109     ;;;
1110     (proclaim '(function %event (event-info (or node null))))
1111     (defun %event (info node)
1112     (incf (event-info-count info))
1113     (when (and (>= (event-info-level info) *event-note-threshold*)
1114     (if node
1115     (policy node (= brevity 0))
1116     (policy nil (= brevity 0))))
1117     (let ((*compiler-error-context* node))
1118     (compiler-note (event-info-description info))))
1119    
1120     (let ((action (event-info-action info)))
1121     (when action (funcall action node))))
1122    
1123    
1124     ;;; Event-Statistics, Clear-Statistics -- Interface
1125     ;;;
1126     (proclaim '(function event-statistics (&optional unsigned-byte stream) void))
1127     (defun event-statistics (&optional (min-count 1) (stream *standard-output*))
1128     "Print a listing of events and their counts, sorted by the count. Events
1129     that happened fewer than Min-Count times will not be printed. Stream is the
1130     stream to write to."
1131     (collect ((info))
1132     (maphash #'(lambda (k v)
1133     (declare (ignore k))
1134     (when (>= (event-info-count v) min-count)
1135     (info v)))
1136     *event-info*)
1137     (dolist (event (sort (info) #'> :key #'event-info-count))
1138     (format stream "~6D: ~A~%" (event-info-count event)
1139     (event-info-description event)))
1140     (values)))
1141     ;;;
1142     (proclaim '(function clear-statistics () void))
1143     (defun clear-statistics ()
1144     (maphash #'(lambda (k v)
1145     (declare (ignore k))
1146     (setf (event-info-count v) 0))
1147     *event-info*)
1148     (values))
1149    

  ViewVC Help
Powered by ViewVC 1.1.5