0.8.0.3:
[sbcl.git] / src / compiler / node.lisp
1 ;;;; structures for the first intermediate representation in the
2 ;;;; compiler, IR1
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!C")
14
15 ;;; The front-end data structure (IR1) is composed of nodes and
16 ;;; continuations. The general idea is that continuations contain
17 ;;; top-down information and nodes contain bottom-up, derived
18 ;;; information. A continuation represents a place in the code, while
19 ;;; a node represents code that does something.
20 ;;;
21 ;;; This representation is more of a flow-graph than an augmented
22 ;;; syntax tree. The evaluation order is explicitly represented in the
23 ;;; linkage by continuations, rather than being implicit in the nodes
24 ;;; which receive the the results of evaluation. This allows us to
25 ;;; decouple the flow of results from the flow of control. A
26 ;;; continuation represents both, but the continuation can represent
27 ;;; the case of a discarded result by having no DEST.
28
29 (def!struct (continuation
30              (:make-load-form-fun ignore-it)
31              (:constructor make-continuation (&optional dest)))
32   ;; an indication of the way that this continuation is currently used
33   ;;
34   ;; :UNUSED
35   ;;    A continuation for which all control-related slots have the
36   ;;    default values. A continuation is unused during IR1 conversion
37   ;;    until it is assigned a block, and may be also be temporarily
38   ;;    unused during later manipulations of IR1. In a consistent
39   ;;    state there should never be any mention of :UNUSED
40   ;;    continuations. NEXT can have a non-null value if the next node
41   ;;    has already been determined.
42   ;;
43   ;; :DELETED
44   ;;    A continuation that has been deleted from IR1. Any pointers into
45   ;;    IR1 are cleared. There are two conditions under which a deleted
46   ;;    continuation may appear in code:
47   ;;     -- The CONT of the LAST node in a block may be a deleted
48   ;;        continuation when the original receiver of the continuation's
49   ;;        value was deleted. Note that DEST in a deleted continuation is
50   ;;        null, so it is easy to know not to attempt delivering any
51   ;;        values to the continuation.
52   ;;     -- Unreachable code that hasn't been deleted yet may receive
53   ;;        deleted continuations. All such code will be in blocks that
54   ;;        have DELETE-P set. All unreachable code is deleted by control
55   ;;        optimization, so the backend doesn't have to worry about this.
56   ;;
57   ;; :BLOCK-START
58   ;;    The continuation that is the START of BLOCK. This is the only kind
59   ;;    of continuation that can have more than one use. The BLOCK's
60   ;;    START-USES is a list of all the uses.
61   ;;
62   ;; :DELETED-BLOCK-START
63   ;;    Like :BLOCK-START, but BLOCK has been deleted. A block
64   ;;    starting continuation is made into a deleted block start when
65   ;;    the block is deleted, but the continuation still may have
66   ;;    value semantics. Since there isn't any code left, next is
67   ;;    null.
68   ;;
69   ;; :INSIDE-BLOCK
70   ;;    A continuation that is the CONT of some node in BLOCK.
71   (kind :unused :type (member :unused :deleted :inside-block :block-start
72                               :deleted-block-start))
73   ;; The node which receives this value, if any. In a deleted
74   ;; continuation, this is null even though the node that receives
75   ;; this continuation may not yet be deleted.
76   (dest nil :type (or node null))
77   ;; If this is a NODE, then it is the node which is to be evaluated
78   ;; next. This is always null in :DELETED and :UNUSED continuations,
79   ;; and will be null in a :INSIDE-BLOCK continuation when this is the
80   ;; CONT of the LAST.
81   (next nil :type (or node null))
82   ;; cached type of this continuation's value. If NIL, then this must
83   ;; be recomputed: see CONTINUATION-DERIVED-TYPE.
84   (%derived-type nil :type (or ctype null))
85   ;; the node where this continuation is used, if unique. This is always
86   ;; null in :DELETED and :UNUSED continuations, and is never null in
87   ;; :INSIDE-BLOCK continuations. In a :BLOCK-START continuation, the
88   ;; BLOCK's START-USES indicate whether NIL means no uses or more
89   ;; than one use.
90   (use nil :type (or node null))
91   ;; the basic block this continuation is in. This is null only in
92   ;; :DELETED and :UNUSED continuations. Note that blocks that are
93   ;; unreachable but still in the DFO may receive deleted
94   ;; continuations, so it isn't o.k. to assume that any continuation
95   ;; that you pick up out of its DEST node has a BLOCK.
96   (block nil :type (or cblock null))
97   ;; set to true when something about this continuation's value has
98   ;; changed. See REOPTIMIZE-CONTINUATION. This provides a way for IR1
99   ;; optimize to determine which operands to a node have changed. If
100   ;; the optimizer for this node type doesn't care, it can elect not
101   ;; to clear this flag.
102   (reoptimize t :type boolean)
103   ;; Cached type which is checked by DEST. If NIL, then this must be
104   ;; recomputed: see CONTINUATION-EXTERNALLY-CHECKABLE-TYPE.
105   (%externally-checkable-type nil :type (or null ctype))
106   ;; something or other that the back end annotates this continuation with
107   (info nil)
108   ;; uses of this continuation in the lexical environment. They are
109   ;; recorded so that when one continuation is substituted for another
110   ;; the environment may be updated properly.
111   (lexenv-uses nil :type list))
112
113 (def!method print-object ((x continuation) stream)
114   (print-unreadable-object (x stream :type t :identity t)
115     (format stream " #~D" (cont-num x))))
116
117 (defstruct (node (:constructor nil)
118                  (:copier nil))
119   ;; unique ID for debugging
120   #!+sb-show (id (new-object-id) :read-only t)
121   ;; the bottom-up derived type for this node.
122   (derived-type *wild-type* :type ctype)
123   ;; True if this node needs to be optimized. This is set to true
124   ;; whenever something changes about the value of a continuation
125   ;; whose DEST is this node.
126   (reoptimize t :type boolean)
127   ;; the continuation which receives the value of this node. This also
128   ;; indicates what we do controlwise after evaluating this node. This
129   ;; may be null during IR1 conversion.
130   (cont nil :type (or continuation null))
131   ;; the continuation that this node is the NEXT of. This is null
132   ;; during IR1 conversion when we haven't linked the node in yet or
133   ;; in nodes that have been deleted from the IR1 by UNLINK-NODE.
134   (prev nil :type (or continuation null))
135   ;; the lexical environment this node was converted in
136   (lexenv *lexenv* :type lexenv)
137   ;; a representation of the source code responsible for generating
138   ;; this node
139   ;;
140   ;; For a form introduced by compilation (does not appear in the
141   ;; original source), the path begins with a list of all the
142   ;; enclosing introduced forms. This list is from the inside out,
143   ;; with the form immediately responsible for this node at the head
144   ;; of the list.
145   ;;
146   ;; Following the introduced forms is a representation of the
147   ;; location of the enclosing original source form. This transition
148   ;; is indicated by the magic ORIGINAL-SOURCE-START marker. The first
149   ;; element of the original source is the "form number", which is the
150   ;; ordinal number of this form in a depth-first, left-to-right walk
151   ;; of the truly-top-level form in which this appears.
152   ;;
153   ;; Following is a list of integers describing the path taken through
154   ;; the source to get to this point:
155   ;;     (K L M ...) => (NTH K (NTH L (NTH M ...)))
156   ;;
157   ;; The last element in the list is the top level form number, which
158   ;; is the ordinal number (in this call to the compiler) of the truly
159   ;; top level form containing the original source.
160   (source-path *current-path* :type list)
161   ;; If this node is in a tail-recursive position, then this is set to
162   ;; T. At the end of IR1 (in physical environment analysis) this is
163   ;; computed for all nodes (after cleanup code has been emitted).
164   ;; Before then, a non-null value indicates that IR1 optimization has
165   ;; converted a tail local call to a direct transfer.
166   ;;
167   ;; If the back-end breaks tail-recursion for some reason, then it
168   ;; can null out this slot.
169   (tail-p nil :type boolean))
170
171 ;;; Flags that are used to indicate various things about a block, such
172 ;;; as what optimizations need to be done on it:
173 ;;; -- REOPTIMIZE is set when something interesting happens the uses of a
174 ;;;    continuation whose DEST is in this block. This indicates that the
175 ;;;    value-driven (forward) IR1 optimizations should be done on this block.
176 ;;; -- FLUSH-P is set when code in this block becomes potentially flushable,
177 ;;;    usually due to a continuation's DEST becoming null.
178 ;;; -- TYPE-CHECK is true when the type check phase should be run on this
179 ;;;    block. IR1 optimize can introduce new blocks after type check has
180 ;;;    already run. We need to check these blocks, but there is no point in
181 ;;;    checking blocks we have already checked.
182 ;;; -- DELETE-P is true when this block is used to indicate that this block
183 ;;;    has been determined to be unreachable and should be deleted. IR1
184 ;;;    phases should not attempt to examine or modify blocks with DELETE-P
185 ;;;    set, since they may:
186 ;;;     - be in the process of being deleted, or
187 ;;;     - have no successors, or
188 ;;;     - receive :DELETED continuations.
189 ;;; -- TYPE-ASSERTED, TEST-MODIFIED
190 ;;;    These flags are used to indicate that something in this block
191 ;;;    might be of interest to constraint propagation. TYPE-ASSERTED
192 ;;;    is set when a continuation type assertion is strengthened.
193 ;;;    TEST-MODIFIED is set whenever the test for the ending IF has
194 ;;;    changed (may be true when there is no IF.)
195 (!def-boolean-attribute block
196   reoptimize flush-p type-check delete-p type-asserted test-modified)
197
198 ;;; FIXME: Tweak so that definitions of e.g. BLOCK-DELETE-P is
199 ;;; findable by grep for 'def.*block-delete-p'.
200 (macrolet ((frob (slot)
201              `(defmacro ,(symbolicate "BLOCK-" slot) (block)
202                 `(block-attributep (block-flags ,block) ,',slot))))
203   (frob reoptimize)
204   (frob flush-p)
205   (frob type-check)
206   (frob delete-p)
207   (frob type-asserted)
208   (frob test-modified))
209
210 ;;; The CBLOCK structure represents a basic block. We include
211 ;;; SSET-ELEMENT so that we can have sets of blocks. Initially the
212 ;;; SSET-ELEMENT-NUMBER is null, DFO analysis numbers in reverse DFO.
213 ;;; During IR2 conversion, IR1 blocks are re-numbered in forward emit
214 ;;; order. This latter numbering also forms the basis of the block
215 ;;; numbering in the debug-info (though that is relative to the start
216 ;;; of the function.)
217 (defstruct (cblock (:include sset-element)
218                    (:constructor make-block (start))
219                    (:constructor make-block-key)
220                    (:conc-name block-)
221                    (:predicate block-p)
222                    (:copier copy-block))
223   ;; a list of all the blocks that are predecessors/successors of this
224   ;; block. In well-formed IR1, most blocks will have one successor.
225   ;; The only exceptions are:
226   ;;  1. component head blocks (any number)
227   ;;  2. blocks ending in an IF (1 or 2)
228   ;;  3. blocks with DELETE-P set (zero)
229   (pred nil :type list)
230   (succ nil :type list)
231   ;; the continuation which heads this block (either a :BLOCK-START or
232   ;; :DELETED-BLOCK-START), or NIL when we haven't made the start
233   ;; continuation yet (and in the dummy component head and tail
234   ;; blocks)
235   (start nil :type (or continuation null))
236   ;; a list of all the nodes that have START as their CONT
237   (start-uses nil :type list)
238   ;; the last node in this block. This is NIL when we are in the
239   ;; process of building a block (and in the dummy component head and
240   ;; tail blocks.)
241   (last nil :type (or node null))
242   ;; the forward and backward links in the depth-first ordering of the
243   ;; blocks. These slots are NIL at beginning/end.
244   (next nil :type (or null cblock))
245   (prev nil :type (or null cblock))
246   ;; This block's attributes: see above.
247   (flags (block-attributes reoptimize flush-p type-check type-asserted
248                            test-modified)
249          :type attributes)
250   ;; in constraint propagation: list of LAMBDA-VARs killed in this block
251   ;; in copy propagation: list of killed TNs
252   (kill nil)
253   ;; other sets used in constraint propagation and/or copy propagation
254   (gen nil)
255   (in nil)
256   (out nil)
257   ;; the component this block is in, or NIL temporarily during IR1
258   ;; conversion and in deleted blocks
259   (component (progn
260                (aver-live-component *current-component*)
261                *current-component*)
262              :type (or component null))
263   ;; a flag used by various graph-walking code to determine whether
264   ;; this block has been processed already or what. We make this
265   ;; initially NIL so that FIND-INITIAL-DFO doesn't have to scan the
266   ;; entire initial component just to clear the flags.
267   (flag nil)
268   ;; some kind of info used by the back end
269   (info nil)
270   ;; constraints that hold in this block and its successors by merit
271   ;; of being tested by its IF predecessors.
272   (test-constraint nil :type (or sset null)))
273 (def!method print-object ((cblock cblock) stream)
274   (print-unreadable-object (cblock stream :type t :identity t)
275     (format stream "~W :START c~W"
276             (block-number cblock)
277             (cont-num (block-start cblock)))))
278
279 ;;; The BLOCK-ANNOTATION class is inherited (via :INCLUDE) by
280 ;;; different BLOCK-INFO annotation structures so that code
281 ;;; (specifically control analysis) can be shared.
282 (defstruct (block-annotation (:constructor nil)
283                              (:copier nil))
284   ;; The IR1 block that this block is in the INFO for.
285   (block (missing-arg) :type cblock)
286   ;; the next and previous block in emission order (not DFO). This
287   ;; determines which block we drop though to, and is also used to
288   ;; chain together overflow blocks that result from splitting of IR2
289   ;; blocks in lifetime analysis.
290   (next nil :type (or block-annotation null))
291   (prev nil :type (or block-annotation null)))
292
293 ;;; A COMPONENT structure provides a handle on a connected piece of
294 ;;; the flow graph. Most of the passes in the compiler operate on
295 ;;; COMPONENTs rather than on the entire flow graph.
296 ;;;
297 ;;; According to the CMU CL internals/front.tex, the reason for
298 ;;; separating compilation into COMPONENTs is
299 ;;;   to increase the efficiency of large block compilations. In
300 ;;;   addition to improving locality of reference and reducing the
301 ;;;   size of flow analysis problems, this allows back-end data
302 ;;;   structures to be reclaimed after the compilation of each
303 ;;;   component.
304 (defstruct (component (:copier nil)
305                       (:constructor
306                        make-component (head tail &aux (last-block tail))))
307   ;; unique ID for debugging
308   #!+sb-show (id (new-object-id) :read-only t)
309   ;; the kind of component
310   ;;
311   ;; (The terminology here is left over from before
312   ;; sbcl-0.pre7.34.flaky5.2, when there was no such thing as
313   ;; FUNCTIONAL-HAS-EXTERNAL-REFERENCES-P, so that Python was
314   ;; incapable of building standalone :EXTERNAL functions, but instead
315   ;; had to implement things like #'CL:COMPILE as FUNCALL of a little
316   ;; toplevel stub whose sole purpose was to return an :EXTERNAL
317   ;; function.)
318   ;;
319   ;; The possibilities are:
320   ;;   NIL
321   ;;     an ordinary component, containing non-top-level code
322   ;;   :TOPLEVEL
323   ;;     a component containing only load-time code
324   ;;   :COMPLEX-TOPLEVEL
325   ;;     In the old system, before FUNCTIONAL-HAS-EXTERNAL-REFERENCES-P
326   ;;     was defined, this was necessarily a component containing both
327   ;;     top level and run-time code. Now this state is also used for
328   ;;     a component with HAS-EXTERNAL-REFERENCES-P functionals in it.
329   ;;   :INITIAL
330   ;;     the result of initial IR1 conversion, on which component
331   ;;     analysis has not been done
332   ;;   :DELETED
333   ;;     debris left over from component analysis
334   ;;
335   ;; See also COMPONENT-TOPLEVELISH-P.
336   (kind nil :type (member nil :toplevel :complex-toplevel :initial :deleted))
337   ;; the blocks that are the dummy head and tail of the DFO
338   ;;
339   ;; Entry/exit points have these blocks as their
340   ;; predecessors/successors. The start and return from each
341   ;; non-deleted function is linked to the component head and
342   ;; tail. Until physical environment analysis links NLX entry stubs
343   ;; to the component head, every successor of the head is a function
344   ;; start (i.e. begins with a BIND node.)
345   (head (missing-arg) :type cblock)
346   (tail (missing-arg) :type cblock)
347   ;; New blocks are inserted before this.
348   (last-block (missing-arg) :type cblock)
349   ;; This becomes a list of the CLAMBDA structures for all functions
350   ;; in this component. OPTIONAL-DISPATCHes are represented only by
351   ;; their XEP and other associated lambdas. This doesn't contain any
352   ;; deleted or LET lambdas.
353   ;;
354   ;; Note that logical associations between CLAMBDAs and COMPONENTs
355   ;; seem to exist for a while before this is initialized. See e.g.
356   ;; the NEW-FUNCTIONALS slot. In particular, I got burned by writing
357   ;; some code to use this value to decide which components need
358   ;; LOCALL-ANALYZE-COMPONENT, when it turns out that
359   ;; LOCALL-ANALYZE-COMPONENT had a role in initializing this value
360   ;; (and DFO stuff does too, maybe). Also, even after it's
361   ;; initialized, it might change as CLAMBDAs are deleted or merged.
362   ;; -- WHN 2001-09-30
363   (lambdas () :type list)
364   ;; a list of FUNCTIONALs for functions that are newly converted, and
365   ;; haven't been local-call analyzed yet. Initially functions are not
366   ;; in the LAMBDAS list. Local call analysis moves them there
367   ;; (possibly as LETs, or implicitly as XEPs if an OPTIONAL-DISPATCH.)
368   ;; Between runs of local call analysis there may be some debris of
369   ;; converted or even deleted functions in this list.
370   (new-functionals () :type list)
371   ;; If this is true, then there is stuff in this component that could
372   ;; benefit from further IR1 optimization.
373   (reoptimize t :type boolean)
374   ;; If this is true, then the control flow in this component was
375   ;; messed up by IR1 optimizations, so the DFO should be recomputed.
376   (reanalyze nil :type boolean)
377   ;; some sort of name for the code in this component
378   (name "<unknown>" :type simple-string)
379   ;; When I am a child, this is :NO-IR2-YET.
380   ;; In my adulthood, IR2 stores notes to itself here.
381   ;; After I have left the great wheel and am staring into the GC, this
382   ;;   is set to :DEAD to indicate that it's a gruesome error to operate
383   ;;   on me (e.g. by using me as *CURRENT-COMPONENT*, or by pushing
384   ;;   LAMBDAs onto my NEW-FUNCTIONALS, as in sbcl-0.pre7.115).
385   (info :no-ir2-yet :type (or ir2-component (member :no-ir2-yet :dead)))
386   ;; the SOURCE-INFO structure describing where this component was
387   ;; compiled from
388   (source-info *source-info* :type source-info)
389   ;; count of the number of inline expansions we have done while
390   ;; compiling this component, to detect infinite or exponential
391   ;; blowups
392   (inline-expansions 0 :type index)
393   ;; a map from combination nodes to things describing how an
394   ;; optimization of the node failed. The description is an alist
395   ;; (TRANSFORM . ARGS), where TRANSFORM is the structure describing
396   ;; the transform that failed, and ARGS is either a list of format
397   ;; arguments for the note, or the FUN-TYPE that would have
398   ;; enabled the transformation but failed to match.
399   (failed-optimizations (make-hash-table :test 'eq) :type hash-table)
400   ;; This is similar to NEW-FUNCTIONALS, but is used when a function
401   ;; has already been analyzed, but new references have been added by
402   ;; inline expansion. Unlike NEW-FUNCTIONALS, this is not disjoint
403   ;; from COMPONENT-LAMBDAS.
404   (reanalyze-functionals nil :type list))
405 (defprinter (component :identity t)
406   name
407   #!+sb-show id
408   (reanalyze :test reanalyze))
409
410 ;;; Check that COMPONENT is suitable for roles which involve adding
411 ;;; new code. (gotta love imperative programming with lotso in-place
412 ;;; side effects...)
413 (defun aver-live-component (component)
414   ;; FIXME: As of sbcl-0.pre7.115, we're asserting that
415   ;; COMPILE-COMPONENT hasn't happened yet. Might it be even better
416   ;; (certainly stricter, possibly also correct...) to assert that
417   ;; IR1-FINALIZE hasn't happened yet?
418   (aver (not (eql (component-info component) :dead))))
419
420 ;;; Before sbcl-0.7.0, there were :TOPLEVEL things which were magical
421 ;;; in multiple ways. That's since been refactored into the orthogonal
422 ;;; properties "optimized for locall with no arguments" and "externally
423 ;;; visible/referenced (so don't delete it)". The code <0.7.0 did a lot
424 ;;; of tests a la (EQ KIND :TOP_LEVEL) in the "don't delete it?" sense;
425 ;;; this function is a sort of literal translation of those tests into
426 ;;; the new world.
427 ;;;
428 ;;; FIXME: After things settle down, bare :TOPLEVEL might go away, at
429 ;;; which time it might be possible to replace the COMPONENT-KIND
430 ;;; :TOPLEVEL mess with a flag COMPONENT-HAS-EXTERNAL-REFERENCES-P
431 ;;; along the lines of FUNCTIONAL-HAS-EXTERNAL-REFERENCES-P.
432 (defun lambda-toplevelish-p (clambda)
433   (or (eql (lambda-kind clambda) :toplevel)
434       (lambda-has-external-references-p clambda)))
435 (defun component-toplevelish-p (component)
436   (member (component-kind component)
437           '(:toplevel :complex-toplevel)))
438
439 ;;; A CLEANUP structure represents some dynamic binding action. Blocks
440 ;;; are annotated with the current CLEANUP so that dynamic bindings
441 ;;; can be removed when control is transferred out of the binding
442 ;;; environment. We arrange for changes in dynamic bindings to happen
443 ;;; at block boundaries, so that cleanup code may easily be inserted.
444 ;;; The "mess-up" action is explicitly represented by a funny function
445 ;;; call or ENTRY node.
446 ;;;
447 ;;; We guarantee that CLEANUPs only need to be done at block boundaries
448 ;;; by requiring that the exit continuations initially head their
449 ;;; blocks, and then by not merging blocks when there is a cleanup
450 ;;; change.
451 (defstruct (cleanup (:copier nil))
452   ;; the kind of thing that has to be cleaned up
453   (kind (missing-arg)
454         :type (member :special-bind :catch :unwind-protect :block :tagbody))
455   ;; the node that messes things up. This is the last node in the
456   ;; non-messed-up environment. Null only temporarily. This could be
457   ;; deleted due to unreachability.
458   (mess-up nil :type (or node null))
459   ;; a list of all the NLX-INFO structures whose NLX-INFO-CLEANUP is
460   ;; this cleanup. This is filled in by physical environment analysis.
461   (nlx-info nil :type list))
462 (defprinter (cleanup :identity t)
463   kind
464   mess-up
465   (nlx-info :test nlx-info))
466
467 ;;; A PHYSENV represents the result of physical environment analysis.
468 ;;;
469 ;;; As far as I can tell from reverse engineering, this IR1 structure
470 ;;; represents the physical environment (which is probably not the
471 ;;; standard Lispy term for this concept, but I dunno what is the
472 ;;; standard term): those things in the lexical environment which a
473 ;;; LAMBDA actually interacts with. Thus in
474 ;;;   (DEFUN FROB-THINGS (THINGS)
475 ;;;     (DOLIST (THING THINGS)
476 ;;;       (BLOCK FROBBING-ONE-THING
477 ;;;         (MAPCAR (LAMBDA (PATTERN)
478 ;;;                   (WHEN (FITS-P THING PATTERN)
479 ;;;                     (RETURN-FROM FROB-THINGS (LIST :FIT THING PATTERN))))
480 ;;;                 *PATTERNS*))))
481 ;;; the variables THINGS, THING, and PATTERN and the block names
482 ;;; FROB-THINGS and FROBBING-ONE-THING are all in the inner LAMBDA's
483 ;;; lexical environment, but of those only THING, PATTERN, and
484 ;;; FROB-THINGS are in its physical environment. In IR1, we largely
485 ;;; just collect the names of these things; in IR2 an IR2-PHYSENV
486 ;;; structure is attached to INFO and used to keep track of
487 ;;; associations between these names and less-abstract things (like
488 ;;; TNs, or eventually stack slots and registers). -- WHN 2001-09-29
489 (defstruct (physenv (:copier nil))
490   ;; the function that allocates this physical environment
491   (lambda (missing-arg) :type clambda :read-only t)
492   #| ; seems not to be used as of sbcl-0.pre7.51
493   ;; a list of all the lambdas that allocate variables in this
494   ;; physical environment
495   (lambdas nil :type list)
496   |#
497   ;; This ultimately converges to a list of all the LAMBDA-VARs and
498   ;; NLX-INFOs needed from enclosing environments by code in this
499   ;; physical environment. In the meantime, it may be
500   ;;   * NIL at object creation time
501   ;;   * a superset of the correct result, generated somewhat later
502   ;;   * smaller and smaller sets converging to the correct result as
503   ;;     we notice and delete unused elements in the superset
504   (closure nil :type list)
505   ;; a list of NLX-INFO structures describing all the non-local exits
506   ;; into this physical environment
507   (nlx-info nil :type list)
508   ;; some kind of info used by the back end
509   (info nil))
510 (defprinter (physenv :identity t)
511   lambda
512   (closure :test closure)
513   (nlx-info :test nlx-info))
514
515 ;;; An TAIL-SET structure is used to accumulate information about
516 ;;; tail-recursive local calls. The "tail set" is effectively the
517 ;;; transitive closure of the "is called tail-recursively by"
518 ;;; relation.
519 ;;;
520 ;;; All functions in the same tail set share the same TAIL-SET
521 ;;; structure. Initially each function has its own TAIL-SET, but when
522 ;;; IR1-OPTIMIZE-RETURN notices a tail local call, it joins the tail
523 ;;; sets of the called function and the calling function.
524 ;;;
525 ;;; The tail set is somewhat approximate, because it is too early to
526 ;;; be sure which calls will be tail-recursive. Any call that *might*
527 ;;; end up tail-recursive causes TAIL-SET merging.
528 (defstruct (tail-set)
529   ;; a list of all the LAMBDAs in this tail set
530   (funs nil :type list)
531   ;; our current best guess of the type returned by these functions.
532   ;; This is the union across all the functions of the return node's
533   ;; RESULT-TYPE, excluding local calls.
534   (type *wild-type* :type ctype)
535   ;; some info used by the back end
536   (info nil))
537 (defprinter (tail-set :identity t)
538   funs
539   type
540   (info :test info))
541
542 ;;; An NLX-INFO structure is used to collect various information about
543 ;;; non-local exits. This is effectively an annotation on the
544 ;;; CONTINUATION, although it is accessed by searching in the
545 ;;; PHYSENV-NLX-INFO.
546 (def!struct (nlx-info (:make-load-form-fun ignore-it))
547   ;; the cleanup associated with this exit. In a catch or
548   ;; unwind-protect, this is the :CATCH or :UNWIND-PROTECT cleanup,
549   ;; and not the cleanup for the escape block. The CLEANUP-KIND of
550   ;; this thus provides a good indication of what kind of exit is
551   ;; being done.
552   (cleanup (missing-arg) :type cleanup)
553   ;; the continuation exited to (the CONT of the EXIT nodes). If this
554   ;; exit is from an escape function (CATCH or UNWIND-PROTECT), then
555   ;; physical environment analysis deletes the escape function and
556   ;; instead has the %NLX-ENTRY use this continuation.
557   ;;
558   ;; This slot is primarily an indication of where this exit delivers
559   ;; its values to (if any), but it is also used as a sort of name to
560   ;; allow us to find the NLX-INFO that corresponds to a given exit.
561   ;; For this purpose, the ENTRY must also be used to disambiguate,
562   ;; since exits to different places may deliver their result to the
563   ;; same continuation.
564   (continuation (missing-arg) :type continuation)
565   ;; the entry stub inserted by physical environment analysis. This is
566   ;; a block containing a call to the %NLX-ENTRY funny function that
567   ;; has the original exit destination as its successor. Null only
568   ;; temporarily.
569   (target nil :type (or cblock null))
570   ;; some kind of info used by the back end
571   info)
572 (defprinter (nlx-info :identity t)
573   continuation
574   target
575   info)
576 \f
577 ;;;; LEAF structures
578
579 ;;; Variables, constants and functions are all represented by LEAF
580 ;;; structures. A reference to a LEAF is indicated by a REF node. This
581 ;;; allows us to easily substitute one for the other without actually
582 ;;; hacking the flow graph.
583 (def!struct (leaf (:make-load-form-fun ignore-it)
584                   (:constructor nil))
585   ;; unique ID for debugging
586   #!+sb-show (id (new-object-id) :read-only t)
587   ;; (For public access to this slot, use LEAF-SOURCE-NAME.)
588   ;;
589   ;; the name of LEAF as it appears in the source, e.g. 'FOO or '(SETF
590   ;; FOO) or 'N or '*Z*, or the special .ANONYMOUS. value if there's
591   ;; no name for this thing in the source (as can happen for
592   ;; FUNCTIONALs, e.g. for anonymous LAMBDAs or for functions for
593   ;; top-level forms; and can also happen for anonymous constants) or
594   ;; perhaps also if the match between the name and the thing is
595   ;; skewed enough (e.g. for macro functions or method functions) that
596   ;; we don't want to have that name affect compilation
597   ;;
598   ;; (We use .ANONYMOUS. here more or less the way we'd ordinarily use
599   ;; NIL, but we're afraid to use NIL because it's a symbol which could
600   ;; be the name of a leaf, if only the constant named NIL.)
601   ;;
602   ;; The value of this slot in can affect ordinary runtime behavior,
603   ;; e.g. of special variables and known functions, not just debugging.
604   ;;
605   ;; See also the LEAF-DEBUG-NAME function and the
606   ;; FUNCTIONAL-%DEBUG-NAME slot.
607   (%source-name (missing-arg)
608                 :type (or symbol (and cons (satisfies legal-fun-name-p)))
609                 :read-only t)
610   ;; the type which values of this leaf must have
611   (type *universal-type* :type ctype)
612   ;; where the TYPE information came from:
613   ;;  :DECLARED, from a declaration.
614   ;;  :ASSUMED, from uses of the object.
615   ;;  :DEFINED, from examination of the definition.
616   ;; FIXME: This should be a named type. (LEAF-WHERE-FROM? Or
617   ;; perhaps just WHERE-FROM, since it's not just used in LEAF,
618   ;; but also in various DEFINE-INFO-TYPEs in globaldb.lisp,
619   ;; and very likely elsewhere too.)
620   (where-from :assumed :type (member :declared :assumed :defined))
621   ;; list of the REF nodes for this leaf
622   (refs () :type list)
623   ;; true if there was ever a REF or SET node for this leaf. This may
624   ;; be true when REFS and SETS are null, since code can be deleted.
625   (ever-used nil :type boolean)
626   ;; some kind of info used by the back end
627   (info nil))
628
629 ;;; LEAF name operations
630 ;;;
631 ;;; KLUDGE: wants CLOS..
632 (defun leaf-has-source-name-p (leaf)
633   (not (eq (leaf-%source-name leaf)
634            '.anonymous.)))
635 (defun leaf-source-name (leaf)
636   (aver (leaf-has-source-name-p leaf))
637   (leaf-%source-name leaf))
638 (defun leaf-debug-name (leaf)
639   (if (functional-p leaf)
640       ;; FUNCTIONALs have additional %DEBUG-NAME behavior.
641       (functional-debug-name leaf)
642       ;; Other objects just use their source name.
643       ;;
644       ;; (As of sbcl-0.pre7.85, there are a few non-FUNCTIONAL
645       ;; anonymous objects, (anonymous constants..) and those would
646       ;; fail here if we ever tried to get debug names from them, but
647       ;; it looks as though it's never interesting to get debug names
648       ;; from them, so it's moot. -- WHN)
649       (leaf-source-name leaf)))
650
651 ;;; The CONSTANT structure is used to represent known constant values.
652 ;;; If NAME is not null, then it is the name of the named constant
653 ;;; which this leaf corresponds to, otherwise this is an anonymous
654 ;;; constant.
655 (def!struct (constant (:include leaf))
656   ;; the value of the constant
657   (value nil :type t))
658 (defprinter (constant :identity t)
659   (%source-name :test %source-name)
660   value)
661
662 ;;; The BASIC-VAR structure represents information common to all
663 ;;; variables which don't correspond to known local functions.
664 (def!struct (basic-var (:include leaf)
665                        (:constructor nil))
666   ;; Lists of the set nodes for this variable.
667   (sets () :type list))
668
669 ;;; The GLOBAL-VAR structure represents a value hung off of the symbol
670 ;;; NAME.
671 (def!struct (global-var (:include basic-var))
672   ;; kind of variable described
673   (kind (missing-arg)
674         :type (member :special :global-function :global)))
675 (defprinter (global-var :identity t)
676   %source-name
677   #!+sb-show id
678   (type :test (not (eq type *universal-type*)))
679   (where-from :test (not (eq where-from :assumed)))
680   kind)
681
682 ;;; A DEFINED-FUN represents a function that is defined in the same
683 ;;; compilation block, or that has an inline expansion, or that has a
684 ;;; non-NIL INLINEP value. Whenever we change the INLINEP state (i.e.
685 ;;; an inline proclamation) we copy the structure so that former
686 ;;; INLINEP values are preserved.
687 (def!struct (defined-fun (:include global-var
688                                    (where-from :defined)
689                                    (kind :global-function)))
690   ;; The values of INLINEP and INLINE-EXPANSION initialized from the
691   ;; global environment.
692   (inlinep nil :type inlinep)
693   (inline-expansion nil :type (or cons null))
694   ;; the block-local definition of this function (either because it
695   ;; was semi-inline, or because it was defined in this block). If
696   ;; this function is not an entry point, then this may be deleted or
697   ;; LET-converted. Null if we haven't converted the expansion yet.
698   (functional nil :type (or functional null)))
699 (defprinter (defined-fun :identity t)
700   %source-name
701   #!+sb-show id
702   inlinep
703   (functional :test functional))
704 \f
705 ;;;; function stuff
706
707 ;;; We default the WHERE-FROM and TYPE slots to :DEFINED and FUNCTION.
708 ;;; We don't normally manipulate function types for defined functions,
709 ;;; but if someone wants to know, an approximation is there.
710 (def!struct (functional (:include leaf
711                                   (%source-name '.anonymous.)
712                                   (where-from :defined)
713                                   (type (specifier-type 'function))))
714   ;; (For public access to this slot, use LEAF-DEBUG-NAME.)
715   ;;
716   ;; the name of FUNCTIONAL for debugging purposes, or NIL if we
717   ;; should just let the SOURCE-NAME fall through
718   ;; 
719   ;; Unlike the SOURCE-NAME slot, this slot's value should never
720   ;; affect ordinary code behavior, only debugging/diagnostic behavior.
721   ;;
722   ;; Ha.  Ah, the starry-eyed idealism of the writer of the above
723   ;; paragraph.  FUNCTION-LAMBDA-EXPRESSION's behaviour, as of
724   ;; sbcl-0.7.11.x, differs if the name of the a function is a string
725   ;; or not, as if it is a valid function name then it can look for an
726   ;; inline expansion.
727   ;;
728   ;; The value of this slot can be anything, except that it shouldn't
729   ;; be a legal function name, since otherwise debugging gets
730   ;; confusing. (If a legal function name is a good name for the
731   ;; function, it should be in %SOURCE-NAME, and then we shouldn't
732   ;; need a %DEBUG-NAME.) In SBCL as of 0.pre7.87, it's always a
733   ;; string unless it's NIL, since that's how CMU CL represented debug
734   ;; names. However, eventually I (WHN) think it we should start using
735   ;; list values instead, since they have much nicer print properties
736   ;; (abbreviation, skipping package prefixes when unneeded, and
737   ;; renaming package prefixes when we do things like renaming SB!EXT
738   ;; to SB-EXT).
739   ;;
740   ;; E.g. for the function which implements (DEFUN FOO ...), we could
741   ;; have
742   ;;   %SOURCE-NAME=FOO
743   ;;   %DEBUG-NAME=NIL
744   ;; for the function which implements the top level form
745   ;; (IN-PACKAGE :FOO) we could have
746   ;;   %SOURCE-NAME=NIL
747   ;;   %DEBUG-NAME="top level form (IN-PACKAGE :FOO)"
748   ;; for the function which implements FOO in
749   ;;   (DEFUN BAR (...) (FLET ((FOO (...) ...)) ...))
750   ;; we could have
751   ;;   %SOURCE-NAME=FOO
752   ;;   %DEBUG-NAME="FLET FOO in BAR"
753   ;; and for the function which implements FOO in
754   ;;   (DEFMACRO FOO (...) ...)
755   ;; we could have
756   ;;   %SOURCE-NAME=FOO (or maybe .ANONYMOUS.?)
757   ;;   %DEBUG-NAME="DEFMACRO FOO"
758   (%debug-name nil
759                :type (or null (not (satisfies legal-fun-name-p)))
760                :read-only t)
761   ;; some information about how this function is used. These values
762   ;; are meaningful:
763   ;;
764   ;;    NIL
765   ;;    an ordinary function, callable using local call
766   ;;
767   ;;    :LET
768   ;;    a lambda that is used in only one local call, and has in
769   ;;    effect been substituted directly inline. The return node is
770   ;;    deleted, and the result is computed with the actual result
771   ;;    continuation for the call.
772   ;;
773   ;;    :MV-LET
774   ;;    Similar to :LET (as per FUNCTIONAL-LETLIKE-P), but the call
775   ;;    is an MV-CALL.
776   ;;
777   ;;    :ASSIGNMENT
778   ;;    similar to a LET (as per FUNCTIONAL-SOMEWHAT-LETLIKE-P), but
779   ;;    can have other than one call as long as there is at most
780   ;;    one non-tail call.
781   ;;
782   ;;    :OPTIONAL
783   ;;    a lambda that is an entry point for an OPTIONAL-DISPATCH.
784   ;;    Similar to NIL, but requires greater caution, since local call
785   ;;    analysis may create new references to this function. Also, the
786   ;;    function cannot be deleted even if it has *no* references. The
787   ;;    OPTIONAL-DISPATCH is in the LAMDBA-OPTIONAL-DISPATCH.
788   ;;
789   ;;    :EXTERNAL
790   ;;    an external entry point lambda. The function it is an entry
791   ;;    for is in the ENTRY-FUN slot.
792   ;;
793   ;;    :TOPLEVEL
794   ;;    a top level lambda, holding a compiled top level form.
795   ;;    Compiled very much like NIL, but provides an indication of
796   ;;    top level context. A :TOPLEVEL lambda should have *no*
797   ;;    references. Its ENTRY-FUN is a self-pointer.
798   ;;
799   ;;    :TOPLEVEL-XEP
800   ;;    After a component is compiled, we clobber any top level code
801   ;;    references to its non-closure XEPs with dummy FUNCTIONAL
802   ;;    structures having this kind. This prevents the retained
803   ;;    top level code from holding onto the IR for the code it
804   ;;    references.
805   ;;
806   ;;    :ESCAPE
807   ;;    :CLEANUP
808   ;;    special functions used internally by CATCH and UNWIND-PROTECT.
809   ;;    These are pretty much like a normal function (NIL), but are
810   ;;    treated specially by local call analysis and stuff. Neither
811   ;;    kind should ever be given an XEP even though they appear as
812   ;;    args to funny functions. An :ESCAPE function is never actually
813   ;;    called, and thus doesn't need to have code generated for it.
814   ;;
815   ;;    :DELETED
816   ;;    This function has been found to be uncallable, and has been
817   ;;    marked for deletion.
818   (kind nil :type (member nil :optional :deleted :external :toplevel
819                           :escape :cleanup :let :mv-let :assignment
820                           :toplevel-xep))
821   ;; Is this a function that some external entity (e.g. the fasl dumper)
822   ;; refers to, so that even when it appears to have no references, it
823   ;; shouldn't be deleted? In the old days (before
824   ;; sbcl-0.pre7.37.flaky5.2) this was sort of implicitly true when
825   ;; KIND was :TOPLEVEL. Now it must be set explicitly, both for
826   ;; :TOPLEVEL functions and for any other kind of functions that we
827   ;; want to dump or return from #'CL:COMPILE or whatever.
828   (has-external-references-p nil)
829   ;; In a normal function, this is the external entry point (XEP)
830   ;; lambda for this function, if any. Each function that is used
831   ;; other than in a local call has an XEP, and all of the
832   ;; non-local-call references are replaced with references to the
833   ;; XEP.
834   ;;
835   ;; In an XEP lambda (indicated by the :EXTERNAL kind), this is the
836   ;; function that the XEP is an entry-point for. The body contains
837   ;; local calls to all the actual entry points in the function. In a
838   ;; :TOPLEVEL lambda (which is its own XEP) this is a self-pointer.
839   ;;
840   ;; With all other kinds, this is null.
841   (entry-fun nil :type (or functional null))
842   ;; the value of any inline/notinline declaration for a local
843   ;; function (or NIL in any case if no inline expansion is available)
844   (inlinep nil :type inlinep)
845   ;; If we have a lambda that can be used as in inline expansion for
846   ;; this function, then this is it. If there is no source-level
847   ;; lambda corresponding to this function then this is null (but then
848   ;; INLINEP will always be NIL as well.)
849   (inline-expansion nil :type list)
850   ;; the lexical environment that the INLINE-EXPANSION should be converted in
851   (lexenv *lexenv* :type lexenv)
852   ;; the original function or macro lambda list, or :UNSPECIFIED if
853   ;; this is a compiler created function
854   (arg-documentation nil :type (or list (member :unspecified)))
855   ;; various rare miscellaneous info that drives code generation & stuff
856   (plist () :type list))
857 (defprinter (functional :identity t)
858   %source-name
859   %debug-name
860   #!+sb-show id)
861
862 ;;; Is FUNCTIONAL LET-converted? (where we're indifferent to whether
863 ;;; it returns one value or multiple values)
864 (defun functional-letlike-p (functional)
865   (member (functional-kind functional)
866           '(:let :mv-let)))
867
868 ;;; Is FUNCTIONAL sorta LET-converted? (where even an :ASSIGNMENT counts)
869 ;;;
870 ;;; FIXME: I (WHN) don't understand this one well enough to give a good
871 ;;; definition or even a good function name, it's just a literal copy
872 ;;; of a CMU CL idiom. Does anyone have a better name or explanation?
873 (defun functional-somewhat-letlike-p (functional)
874   (or (functional-letlike-p functional)
875       (eql (functional-kind functional) :assignment)))
876
877 ;;; FUNCTIONAL name operations
878 (defun functional-debug-name (functional)
879   ;; FUNCTIONAL-%DEBUG-NAME takes precedence over FUNCTIONAL-SOURCE-NAME
880   ;; here because we want different debug names for the functions in
881   ;; DEFUN FOO and FLET FOO even though they have the same source name.
882   (or (functional-%debug-name functional)
883       ;; Note that this will cause an error if the function is
884       ;; anonymous. In SBCL (as opposed to CMU CL) we make all
885       ;; FUNCTIONALs have debug names. The CMU CL code didn't bother
886       ;; in many FUNCTIONALs, especially those which were likely to be
887       ;; optimized away before the user saw them. However, getting
888       ;; that right requires a global understanding of the code,
889       ;; which seems bad, so we just require names for everything.
890       (leaf-source-name functional)))
891
892 ;;; The CLAMBDA only deals with required lexical arguments. Special,
893 ;;; optional, keyword and rest arguments are handled by transforming
894 ;;; into simpler stuff.
895 (def!struct (clambda (:include functional)
896                      (:conc-name lambda-)
897                      (:predicate lambda-p)
898                      (:constructor make-lambda)
899                      (:copier copy-lambda))
900   ;; list of LAMBDA-VAR descriptors for arguments
901   (vars nil :type list :read-only t)
902   ;; If this function was ever a :OPTIONAL function (an entry-point
903   ;; for an OPTIONAL-DISPATCH), then this is that OPTIONAL-DISPATCH.
904   ;; The optional dispatch will be :DELETED if this function is no
905   ;; longer :OPTIONAL.
906   (optional-dispatch nil :type (or optional-dispatch null))
907   ;; the BIND node for this LAMBDA. This node marks the beginning of
908   ;; the lambda, and serves to explicitly represent the lambda binding
909   ;; semantics within the flow graph representation. This is null in
910   ;; deleted functions, and also in LETs where we deleted the call and
911   ;; bind (because there are no variables left), but have not yet
912   ;; actually deleted the LAMBDA yet.
913   (bind nil :type (or bind null))
914   ;; the RETURN node for this LAMBDA, or NIL if it has been deleted.
915   ;; This marks the end of the lambda, receiving the result of the
916   ;; body. In a LET, the return node is deleted, and the body delivers
917   ;; the value to the actual continuation. The return may also be
918   ;; deleted if it is unreachable.
919   (return nil :type (or creturn null))
920   ;; If this CLAMBDA is a LET, then this slot holds the LAMBDA whose
921   ;; LETS list we are in, otherwise it is a self-pointer.
922   (home nil :type (or clambda null))
923   ;; all the lambdas that have been LET-substituted in this lambda.
924   ;; This is only non-null in lambdas that aren't LETs.
925   (lets nil :type list)
926   ;; all the ENTRY nodes in this function and its LETs, or null in a LET
927   (entries nil :type list)
928   ;; CLAMBDAs which are locally called by this lambda, and other
929   ;; objects (closed-over LAMBDA-VARs and XEPs) which this lambda
930   ;; depends on in such a way that DFO shouldn't put them in separate
931   ;; components.
932   (calls-or-closes nil :type list)
933   ;; the TAIL-SET that this LAMBDA is in. This is null during creation.
934   ;;
935   ;; In CMU CL, and old SBCL, this was also NILed out when LET
936   ;; conversion happened. That caused some problems, so as of
937   ;; sbcl-0.pre7.37.flaky5.2 when I was trying to get the compiler to
938   ;; emit :EXTERNAL functions directly, and so now the value
939   ;; is no longer NILed out in LET conversion, but instead copied
940   ;; (so that any further optimizations on the rest of the tail
941   ;; set won't modify the value) if necessary.
942   (tail-set nil :type (or tail-set null))
943   ;; the structure which represents the phsical environment that this
944   ;; function's variables are allocated in. This is filled in by
945   ;; physical environment analysis. In a LET, this is EQ to our home's
946   ;; physical environment.
947   (physenv nil :type (or physenv null))
948   ;; In a LET, this is the NODE-LEXENV of the combination node. We
949   ;; retain it so that if the LET is deleted (due to a lack of vars),
950   ;; we will still have caller's lexenv to figure out which cleanup is
951   ;; in effect.
952   (call-lexenv nil :type (or lexenv null)))
953 (defprinter (clambda :conc-name lambda- :identity t)
954   %source-name
955   %debug-name
956   #!+sb-show id
957   (type :test (not (eq type *universal-type*)))
958   (where-from :test (not (eq where-from :assumed)))
959   (vars :prin1 (mapcar #'leaf-source-name vars)))
960
961 ;;; The OPTIONAL-DISPATCH leaf is used to represent hairy lambdas. It
962 ;;; is a FUNCTIONAL, like LAMBDA. Each legal number of arguments has a
963 ;;; function which is called when that number of arguments is passed.
964 ;;; The function is called with all the arguments actually passed. If
965 ;;; additional arguments are legal, then the LEXPR style MORE-ENTRY
966 ;;; handles them. The value returned by the function is the value
967 ;;; which results from calling the OPTIONAL-DISPATCH.
968 ;;;
969 ;;; The theory is that each entry-point function calls the next entry
970 ;;; point tail-recursively, passing all the arguments passed in and
971 ;;; the default for the argument the entry point is for. The last
972 ;;; entry point calls the real body of the function. In the presence
973 ;;; of SUPPLIED-P args and other hair, things are more complicated. In
974 ;;; general, there is a distinct internal function that takes the
975 ;;; SUPPLIED-P args as parameters. The preceding entry point calls
976 ;;; this function with NIL filled in for the SUPPLIED-P args, while
977 ;;; the current entry point calls it with T in the SUPPLIED-P
978 ;;; positions.
979 ;;;
980 ;;; Note that it is easy to turn a call with a known number of
981 ;;; arguments into a direct call to the appropriate entry-point
982 ;;; function, so functions that are compiled together can avoid doing
983 ;;; the dispatch.
984 (def!struct (optional-dispatch (:include functional))
985   ;; the original parsed argument list, for anyone who cares
986   (arglist nil :type list)
987   ;; true if &ALLOW-OTHER-KEYS was supplied
988   (allowp nil :type boolean)
989   ;; true if &KEY was specified (which doesn't necessarily mean that
990   ;; there are any &KEY arguments..)
991   (keyp nil :type boolean)
992   ;; the number of required arguments. This is the smallest legal
993   ;; number of arguments.
994   (min-args 0 :type unsigned-byte)
995   ;; the total number of required and optional arguments. Args at
996   ;; positions >= to this are &REST, &KEY or illegal args.
997   (max-args 0 :type unsigned-byte)
998   ;; list of the LAMBDAs which are the entry points for non-rest,
999   ;; non-key calls. The entry for MIN-ARGS is first, MIN-ARGS+1
1000   ;; second, ... MAX-ARGS last. The last entry-point always calls the
1001   ;; main entry; in simple cases it may be the main entry.
1002   (entry-points nil :type list)
1003   ;; an entry point which takes MAX-ARGS fixed arguments followed by
1004   ;; an argument context pointer and an argument count. This entry
1005   ;; point deals with listifying rest args and parsing keywords. This
1006   ;; is null when extra arguments aren't legal.
1007   (more-entry nil :type (or clambda null))
1008   ;; the main entry-point into the function, which takes all arguments
1009   ;; including keywords as fixed arguments. The format of the
1010   ;; arguments must be determined by examining the arglist. This may
1011   ;; be used by callers that supply at least MAX-ARGS arguments and
1012   ;; know what they are doing.
1013   (main-entry nil :type (or clambda null)))
1014 (defprinter (optional-dispatch :identity t)
1015   %source-name
1016   %debug-name
1017   #!+sb-show id
1018   (type :test (not (eq type *universal-type*)))
1019   (where-from :test (not (eq where-from :assumed)))
1020   arglist
1021   allowp
1022   keyp
1023   min-args
1024   max-args
1025   (entry-points :test entry-points)
1026   (more-entry :test more-entry)
1027   main-entry)
1028
1029 ;;; The ARG-INFO structure allows us to tack various information onto
1030 ;;; LAMBDA-VARs during IR1 conversion. If we use one of these things,
1031 ;;; then the var will have to be massaged a bit before it is simple
1032 ;;; and lexical.
1033 (def!struct arg-info
1034   ;; true if this arg is to be specially bound
1035   (specialp nil :type boolean)
1036   ;; the kind of argument being described. Required args only have arg
1037   ;; info structures if they are special.
1038   (kind (missing-arg)
1039         :type (member :required :optional :keyword :rest
1040                       :more-context :more-count))
1041   ;; If true, this is the VAR for SUPPLIED-P variable of a keyword or
1042   ;; optional arg. This is true for keywords with non-constant
1043   ;; defaults even when there is no user-specified supplied-p var.
1044   (supplied-p nil :type (or lambda-var null))
1045   ;; the default for a keyword or optional, represented as the
1046   ;; original Lisp code. This is set to NIL in &KEY arguments that are
1047   ;; defaulted using the SUPPLIED-P arg.
1048   (default nil :type t)
1049   ;; the actual key for a &KEY argument. Note that in ANSI CL this is
1050   ;; not necessarily a keyword: (DEFUN FOO (&KEY ((BAR BAR))) ...).
1051   (key nil :type symbol))
1052 (defprinter (arg-info :identity t)
1053   (specialp :test specialp)
1054   kind
1055   (supplied-p :test supplied-p)
1056   (default :test default)
1057   (key :test key))
1058
1059 ;;; The LAMBDA-VAR structure represents a lexical lambda variable.
1060 ;;; This structure is also used during IR1 conversion to describe
1061 ;;; lambda arguments which may ultimately turn out not to be simple
1062 ;;; and lexical.
1063 ;;;
1064 ;;; LAMBDA-VARs with no REFs are considered to be deleted; physical
1065 ;;; environment analysis isn't done on these variables, so the back
1066 ;;; end must check for and ignore unreferenced variables. Note that a
1067 ;;; deleted LAMBDA-VAR may have sets; in this case the back end is
1068 ;;; still responsible for propagating the SET-VALUE to the set's CONT.
1069 (def!struct (lambda-var (:include basic-var))
1070   ;; true if this variable has been declared IGNORE
1071   (ignorep nil :type boolean)
1072   ;; the CLAMBDA that this var belongs to. This may be null when we are
1073   ;; building a lambda during IR1 conversion.
1074   (home nil :type (or null clambda))
1075   ;; This is set by physical environment analysis if it chooses an
1076   ;; indirect (value cell) representation for this variable because it
1077   ;; is both set and closed over.
1078   (indirect nil :type boolean)
1079   ;; The following two slots are only meaningful during IR1 conversion
1080   ;; of hairy lambda vars:
1081   ;;
1082   ;; The ARG-INFO structure which holds information obtained from
1083   ;; &keyword parsing.
1084   (arg-info nil :type (or arg-info null))
1085   ;; if true, the GLOBAL-VAR structure for the special variable which
1086   ;; is to be bound to the value of this argument
1087   (specvar nil :type (or global-var null))
1088   ;; Set of the CONSTRAINTs on this variable. Used by constraint
1089   ;; propagation. This is left null by the lambda pre-pass if it
1090   ;; determine that this is a set closure variable, and is thus not a
1091   ;; good subject for flow analysis.
1092   (constraints nil :type (or sset null)))
1093 (defprinter (lambda-var :identity t)
1094   %source-name
1095   #!+sb-show id
1096   (type :test (not (eq type *universal-type*)))
1097   (where-from :test (not (eq where-from :assumed)))
1098   (ignorep :test ignorep)
1099   (arg-info :test arg-info)
1100   (specvar :test specvar))
1101 \f
1102 ;;;; basic node types
1103
1104 ;;; A REF represents a reference to a LEAF. REF-REOPTIMIZE is
1105 ;;; initially (and forever) NIL, since REFs don't receive any values
1106 ;;; and don't have any IR1 optimizer.
1107 (defstruct (ref (:include node (reoptimize nil))
1108                 (:constructor make-ref
1109                               (leaf
1110                                &aux (leaf-type (leaf-type leaf))
1111                                     (derived-type
1112                                      (make-single-value-type leaf-type))))
1113                 (:copier nil))
1114   ;; The leaf referenced.
1115   (leaf nil :type leaf))
1116 (defprinter (ref :identity t)
1117   #!+sb-show id
1118   leaf)
1119
1120 ;;; Naturally, the IF node always appears at the end of a block.
1121 ;;; NODE-CONT is a dummy continuation, and is there only to keep
1122 ;;; people happy.
1123 (defstruct (cif (:include node)
1124                 (:conc-name if-)
1125                 (:predicate if-p)
1126                 (:constructor make-if)
1127                 (:copier copy-if))
1128   ;; CONTINUATION for the predicate
1129   (test (missing-arg) :type continuation)
1130   ;; the blocks that we execute next in true and false case,
1131   ;; respectively (may be the same)
1132   (consequent (missing-arg) :type cblock)
1133   (alternative (missing-arg) :type cblock))
1134 (defprinter (cif :conc-name if- :identity t)
1135   (test :prin1 (continuation-use test))
1136   consequent
1137   alternative)
1138
1139 (defstruct (cset (:include node
1140                            (derived-type (make-single-value-type
1141                                           *universal-type*)))
1142                  (:conc-name set-)
1143                  (:predicate set-p)
1144                  (:constructor make-set)
1145                  (:copier copy-set))
1146   ;; descriptor for the variable set
1147   (var (missing-arg) :type basic-var)
1148   ;; continuation for the value form
1149   (value (missing-arg) :type continuation))
1150 (defprinter (cset :conc-name set- :identity t)
1151   var
1152   (value :prin1 (continuation-use value)))
1153
1154 ;;; The BASIC-COMBINATION structure is used to represent both normal
1155 ;;; and multiple value combinations. In a local function call, this
1156 ;;; node appears at the end of its block and the body of the called
1157 ;;; function appears as the successor. The NODE-CONT remains the
1158 ;;; continuation which receives the value of the call.
1159 (defstruct (basic-combination (:include node)
1160                               (:constructor nil)
1161                               (:copier nil))
1162   ;; continuation for the function
1163   (fun (missing-arg) :type continuation)
1164   ;; list of CONTINUATIONs for the args. In a local call, an argument
1165   ;; continuation may be replaced with NIL to indicate that the
1166   ;; corresponding variable is unreferenced, and thus no argument
1167   ;; value need be passed.
1168   (args nil :type list)
1169   ;; the kind of function call being made. :LOCAL means that this is a
1170   ;; local call to a function in the same component, and that argument
1171   ;; syntax checking has been done, etc. Calls to known global
1172   ;; functions are represented by storing the FUN-INFO for the
1173   ;; function in this slot. :FULL is a call to an (as yet) unknown
1174   ;; function. :ERROR is like :FULL, but means that we have discovered
1175   ;; that the call contains an error, and should not be reconsidered
1176   ;; for optimization.
1177   (kind :full :type (or (member :local :full :error) fun-info))
1178   ;; some kind of information attached to this node by the back end
1179   (info nil))
1180
1181 ;;; The COMBINATION node represents all normal function calls,
1182 ;;; including FUNCALL. This is distinct from BASIC-COMBINATION so that
1183 ;;; an MV-COMBINATION isn't COMBINATION-P.
1184 (defstruct (combination (:include basic-combination)
1185                         (:constructor make-combination (fun))
1186                         (:copier nil)))
1187 (defprinter (combination :identity t)
1188   #!+sb-show id
1189   (fun :prin1 (continuation-use fun))
1190   (args :prin1 (mapcar (lambda (x)
1191                          (if x
1192                              (continuation-use x)
1193                              "<deleted>"))
1194                        args)))
1195
1196 ;;; An MV-COMBINATION is to MULTIPLE-VALUE-CALL as a COMBINATION is to
1197 ;;; FUNCALL. This is used to implement all the multiple-value
1198 ;;; receiving forms.
1199 (defstruct (mv-combination (:include basic-combination)
1200                            (:constructor make-mv-combination (fun))
1201                            (:copier nil)))
1202 (defprinter (mv-combination)
1203   (fun :prin1 (continuation-use fun))
1204   (args :prin1 (mapcar #'continuation-use args)))
1205
1206 ;;; The BIND node marks the beginning of a lambda body and represents
1207 ;;; the creation and initialization of the variables.
1208 (defstruct (bind (:include node)
1209                  (:copier nil))
1210   ;; the lambda we are binding variables for. Null when we are
1211   ;; creating the LAMBDA during IR1 translation.
1212   (lambda nil :type (or clambda null)))
1213 (defprinter (bind)
1214   lambda)
1215
1216 ;;; The RETURN node marks the end of a lambda body. It collects the
1217 ;;; return values and represents the control transfer on return. This
1218 ;;; is also where we stick information used for TAIL-SET type
1219 ;;; inference.
1220 (defstruct (creturn (:include node)
1221                     (:conc-name return-)
1222                     (:predicate return-p)
1223                     (:constructor make-return)
1224                     (:copier copy-return))
1225   ;; the lambda we are returning from. Null temporarily during
1226   ;; ir1tran.
1227   (lambda nil :type (or clambda null))
1228   ;; the continuation which yields the value of the lambda
1229   (result (missing-arg) :type continuation)
1230   ;; the union of the node-derived-type of all uses of the result
1231   ;; other than by a local call, intersected with the result's
1232   ;; asserted-type. If there are no non-call uses, this is
1233   ;; *EMPTY-TYPE*
1234   (result-type *wild-type* :type ctype))
1235 (defprinter (creturn :conc-name return- :identity t)
1236   lambda
1237   result-type)
1238
1239 ;;; The CAST node represents type assertions. The check for
1240 ;;; TYPE-TO-CHECK is performed and then the VALUE is declared to be of
1241 ;;; type ASSERTED-TYPE.
1242 (defstruct (cast (:include node)
1243                  (:constructor %make-cast))
1244   (asserted-type (missing-arg) :type ctype)
1245   (type-to-check (missing-arg) :type ctype)
1246   ;; an indication of what we have proven about how this type
1247   ;; assertion is satisfied:
1248   ;;
1249   ;; NIL
1250   ;;    No type check is necessary (VALUE type is a subtype of the TYPE-TO-CHECK.)
1251   ;;
1252   ;; T
1253   ;;    A type check is needed.
1254   (%type-check t :type (member t nil))
1255   ;; the continuations which is checked
1256   (value (missing-arg) :type continuation))
1257 (defprinter (cast :identity t)
1258   %type-check
1259   value
1260   asserted-type
1261   type-to-check)
1262 \f
1263 ;;;; non-local exit support
1264 ;;;;
1265 ;;;; In IR1, we insert special nodes to mark potentially non-local
1266 ;;;; lexical exits.
1267
1268 ;;; The ENTRY node serves to mark the start of the dynamic extent of a
1269 ;;; lexical exit. It is the mess-up node for the corresponding :ENTRY
1270 ;;; cleanup.
1271 (defstruct (entry (:include node)
1272                   (:copier nil))
1273   ;; All of the EXIT nodes for potential non-local exits to this point.
1274   (exits nil :type list)
1275   ;; The cleanup for this entry. NULL only temporarily.
1276   (cleanup nil :type (or cleanup null)))
1277 (defprinter (entry :identity t)
1278   #!+sb-show id)
1279
1280 ;;; The EXIT node marks the place at which exit code would be emitted,
1281 ;;; if necessary. This is interposed between the uses of the exit
1282 ;;; continuation and the exit continuation's DEST. Instead of using
1283 ;;; the returned value being delivered directly to the exit
1284 ;;; continuation, it is delivered to our VALUE continuation. The
1285 ;;; original exit continuation is the exit node's CONT.
1286 (defstruct (exit (:include node)
1287                  (:copier nil))
1288   ;; the ENTRY node that this is an exit for. If null, this is a
1289   ;; degenerate exit. A degenerate exit is used to "fill" an empty
1290   ;; block (which isn't allowed in IR1.) In a degenerate exit, Value
1291   ;; is always also null.
1292   (entry nil :type (or entry null))
1293   ;; the continuation yielding the value we are to exit with. If NIL,
1294   ;; then no value is desired (as in GO).
1295   (value nil :type (or continuation null)))
1296 (defprinter (exit :identity t)
1297   #!+sb-show id
1298   (entry :test entry)
1299   (value :test value))
1300 \f
1301 ;;;; miscellaneous IR1 structures
1302
1303 (defstruct (undefined-warning
1304             #-no-ansi-print-object
1305             (:print-object (lambda (x s)
1306                              (print-unreadable-object (x s :type t)
1307                                (prin1 (undefined-warning-name x) s))))
1308             (:copier nil))
1309   ;; the name of the unknown thing
1310   (name nil :type (or symbol list))
1311   ;; the kind of reference to NAME
1312   (kind (missing-arg) :type (member :function :type :variable))
1313   ;; the number of times this thing was used
1314   (count 0 :type unsigned-byte)
1315   ;; a list of COMPILER-ERROR-CONTEXT structures describing places
1316   ;; where this thing was used. Note that we only record the first
1317   ;; *UNDEFINED-WARNING-LIMIT* calls.
1318   (warnings () :type list))
1319 \f
1320 ;;; a helper for the POLICY macro, defined late here so that the
1321 ;;; various type tests can be inlined
1322 (declaim (ftype (function ((or list lexenv node functional)) list)
1323                 %coerce-to-policy))
1324 (defun %coerce-to-policy (thing)
1325   (let ((result (etypecase thing
1326                   (list thing)
1327                   (lexenv (lexenv-policy thing))
1328                   (node (lexenv-policy (node-lexenv thing)))
1329                   (functional (lexenv-policy (functional-lexenv thing))))))
1330     ;; Test the first element of the list as a rudimentary sanity
1331     ;; that it really does look like a valid policy.
1332     (aver (or (null result) (policy-quality-name-p (caar result))))
1333     ;; Voila.
1334     result))
1335 \f
1336 ;;;; Freeze some structure types to speed type testing.
1337
1338 #!-sb-fluid
1339 (declaim (freeze-type node leaf lexenv continuation cblock component cleanup
1340                       physenv tail-set nlx-info))