1c240565ba7164ec66f946fb4aff1b14824adc09
[sbcl.git] / src / compiler / dfo.lisp
1 ;;;; This file contains the code that finds the initial components and
2 ;;;; DFO, and recomputes the DFO if it is invalidated.
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 ;;; Find the DFO for a component, deleting any unreached blocks and
16 ;;; merging any other components we reach. We repeatedly iterate over
17 ;;; the entry points, since new ones may show up during the walk.
18 (declaim (ftype (function (component) (values)) find-dfo))
19 (defun find-dfo (component)
20   (clear-flags component)
21   (setf (component-reanalyze component) nil)
22   (let ((head (component-head component)))
23     (do ()
24         ((dolist (ep (block-succ head) t)
25            (unless (block-flag ep)
26              (find-dfo-aux ep head component)
27              (return nil))))))
28
29   (let ((num 0))
30     (declare (fixnum num))
31     (do-blocks-backwards (block component :both)
32       (if (block-flag block)
33           (setf (block-number block) (incf num))
34           (setf (block-delete-p block) t)))
35     (do-blocks (block component)
36       (unless (block-flag block)
37         (delete-block block))))
38   (values))
39
40 ;;; Move all the code and entry points from OLD to NEW. The code in
41 ;;; OLD is inserted at the head of NEW. This is also called during LET
42 ;;; conversion when we are about in insert the body of a LET in a
43 ;;; different component. [A local call can be to a different component
44 ;;; before FIND-INITIAL-DFO runs.]
45 (declaim (ftype (function (component component) (values)) join-components))
46 (defun join-components (new old)
47   (aver (eq (component-kind new) (component-kind old)))
48   (let ((old-head (component-head old))
49         (old-tail (component-tail old))
50         (head (component-head new))
51         (tail (component-tail new)))
52
53     (do-blocks (block old)
54       (setf (block-flag block) nil)
55       (setf (block-component block) new))
56
57     (let ((old-next (block-next old-head))
58           (old-last (block-prev old-tail))
59           (next (block-next head)))
60       (unless (eq old-next old-tail)
61         (setf (block-next head) old-next)
62         (setf (block-prev old-next) head)
63         
64         (setf (block-prev next) old-last)
65         (setf (block-next old-last) next))
66
67       (setf (block-next old-head) old-tail)
68       (setf (block-prev old-tail) old-head))
69
70     (setf (component-lambdas new)
71           (nconc (component-lambdas old) (component-lambdas new)))
72     (setf (component-lambdas old) nil)
73     (setf (component-new-funs new) (nconc (component-new-funs old)
74                                           (component-new-funs new))
75           (component-new-funs old) nil)
76
77     (dolist (xp (block-pred old-tail))
78       (unlink-blocks xp old-tail)
79       (link-blocks xp tail))
80     (dolist (ep (block-succ old-head))
81       (unlink-blocks old-head ep)
82       (link-blocks head ep)))
83   (values))
84
85 ;;; Do a depth-first walk from BLOCK, inserting ourself in the DFO
86 ;;; after HEAD. If we somehow find ourselves in another component,
87 ;;; then we join that component to our component.
88 (declaim (ftype (function (cblock cblock component) (values)) find-dfo-aux))
89 (defun find-dfo-aux (block head component)
90   (unless (eq (block-component block) component)
91     (join-components component (block-component block)))
92         
93   (unless (block-flag block)
94     (setf (block-flag block) t)
95     (dolist (succ (block-succ block))
96       (find-dfo-aux succ head component))
97
98     (remove-from-dfo block)
99     (add-to-dfo block head))
100   (values))
101
102 ;;; This function is called on each block by FIND-INITIAL-DFO-AUX
103 ;;; before it walks the successors. It looks at the home CLAMBDA's
104 ;;; BIND block to see whether that block is in some other component:
105 ;;; -- If the block is in the initial component, then do
106 ;;;    DFO-WALK-CALL-GRAPH on the home function to move it
107 ;;;    into COMPONENT.
108 ;;; -- If the block is in some other component, join COMPONENT into
109 ;;;    it and return that component.
110 ;;; -- If the home function is deleted, do nothing. BLOCK must
111 ;;;    eventually be discovered to be unreachable as well. This can
112 ;;;    happen when we have a NLX into a function with no references.
113 ;;;    The escape function still has refs (in the deleted function).
114 ;;;
115 ;;; This ensures that all the blocks in a given environment will be in
116 ;;; the same component, even when they might not seem reachable from
117 ;;; the environment entry. Consider the case of code that is only
118 ;;; reachable from a non-local exit.
119 (defun walk-home-call-graph (block component)
120   (declare (type cblock block) (type component component))
121   (let ((home-lambda (block-home-lambda block)))
122     (if (eq (functional-kind home-lambda) :deleted)
123         component
124         (let ((home-component (lambda-component home-lambda)))
125           (cond ((eq (component-kind home-component) :initial)
126                  (dfo-scavenge-call-graph home-lambda component))
127                 ((eq home-component component)
128                  component)
129                 (t
130                  (join-components home-component component)
131                  home-component))))))
132
133 ;;; This is somewhat similar to FIND-DFO-AUX, except that it merges
134 ;;; the current component with any strange component, rather than the
135 ;;; other way around. This is more efficient in the common case where
136 ;;; the current component doesn't have much stuff in it.
137 ;;;
138 ;;; We return the current component as a result, allowing the caller
139 ;;; to detect when the old current component has been merged with
140 ;;; another.
141 ;;;
142 ;;; We walk blocks in initial components as though they were already
143 ;;; in the current component, moving them to the current component in
144 ;;; the process. The blocks are inserted at the head of the current
145 ;;; component.
146 (defun find-initial-dfo-aux (block component)
147   (declare (type cblock block) (type component component))
148   (let ((this (block-component block)))
149     (cond
150      ((not (or (eq this component)
151                (eq (component-kind this) :initial)))
152       (join-components this component)
153       this)
154      ((block-flag block) component)
155      (t
156       (setf (block-flag block) t)
157       (let ((current (walk-home-call-graph block component)))
158         (dolist (succ (block-succ block))
159           (setq current (find-initial-dfo-aux succ current)))
160         
161         (remove-from-dfo block)
162         (add-to-dfo block (component-head current))
163         current)))))
164
165 ;;; Return a list of all the home lambdas that reference FUN (may
166 ;;; contain duplications).
167 ;;;
168 ;;; References to functions which local call analysis could not (or
169 ;;; were chosen not) to local call convert will appear as references
170 ;;; to XEP lambdas. We can ignore references to XEPs that appear in
171 ;;; :TOPLEVEL components, since environment analysis goes to special
172 ;;; effort to allow closing over of values from a separate top level
173 ;;; component. (And now that HAS-EXTERNAL-REFERENCES-P-ness
174 ;;; generalizes :TOPLEVEL-ness, we ignore those too.) All other
175 ;;; references must cause components to be joined.
176 ;;;
177 ;;; References in deleted functions are also ignored, since this code
178 ;;; will be deleted eventually.
179 (defun find-reference-funs (fun)
180   (collect ((res))
181     (dolist (ref (leaf-refs fun))
182       (let* ((home (node-home-lambda ref))
183              (home-kind (functional-kind home))
184              (home-externally-visible-p
185               (or (eq home-kind :toplevel)
186                   (functional-has-external-references-p home))))
187         (unless (or (and home-externally-visible-p
188                          (eq (functional-kind fun) :external))
189                     (eq home-kind :deleted))
190           (res home))))
191     (res)))
192
193 ;;; Move the code for FUN and all functions called by it into
194 ;;; COMPONENT. If FUN is already in COMPONENT, then we just return
195 ;;; that component.
196 ;;;
197 ;;; If the function is in an initial component, then we move its head
198 ;;; and tail to COMPONENT and add it to COMPONENT's lambdas. It is
199 ;;; harmless to move the tail (even though the return might be
200 ;;; unreachable) because if the return is unreachable it (and its
201 ;;; successor link) will be deleted in the post-deletion pass.
202 ;;;
203 ;;; We then do a FIND-DFO-AUX starting at the head of FUN. If this
204 ;;; flow-graph walk encounters another component (which can only
205 ;;; happen due to a non-local exit), then we move code into that
206 ;;; component instead. We then recurse on all functions called from
207 ;;; FUN, moving code into whichever component the preceding call
208 ;;; returned.
209 ;;;
210 ;;; If FUN is in the initial component, but the BLOCK-FLAG is set in
211 ;;; the bind block, then we just return COMPONENT, since we must have
212 ;;; already reached this function in the current walk (or the
213 ;;; component would have been changed).
214 ;;;
215 ;;; If the function is an XEP, then we also walk all functions that
216 ;;; contain references to the XEP. This is done so that environment
217 ;;; analysis doesn't need to cross component boundaries. This also
218 ;;; ensures that conversion of a full call to a local call won't
219 ;;; result in a need to join components, since the components will
220 ;;; already be one.
221 (defun dfo-scavenge-call-graph (fun component)
222   (declare (type clambda fun) (type component component))
223   (let* ((bind-block (node-block (lambda-bind fun)))
224          (old-lambda-component (block-component bind-block))
225          (return (lambda-return fun)))
226     (cond
227      ((eq old-lambda-component component)
228       component)
229      ((not (eq (component-kind old-lambda-component) :initial))
230       (join-components old-lambda-component component)
231       old-lambda-component)
232      ((block-flag bind-block)
233       component)
234      (t
235       (push fun (component-lambdas component))
236       (setf (component-lambdas old-lambda-component)
237             (delete fun (component-lambdas old-lambda-component)))
238       (link-blocks (component-head component) bind-block)
239       (unlink-blocks (component-head old-lambda-component) bind-block)
240       (when return
241         (let ((return-block (node-block return)))
242           (link-blocks return-block (component-tail component))
243           (unlink-blocks return-block (component-tail old-lambda-component))))
244
245       (let ((calls (if (eq (functional-kind fun) :external)
246                        (append (find-reference-funs fun)
247                                (lambda-calls fun))
248                        (lambda-calls fun))))
249         (do ((res (find-initial-dfo-aux bind-block component)
250                   (dfo-scavenge-call-graph (first remaining-calls) res))
251              (remaining-calls calls (rest remaining-calls)))
252             ((null remaining-calls)
253              res)
254           (declare (type component res))))))))
255
256 ;;; Return true if FUN is either an XEP or has EXITS to some of its
257 ;;; ENTRIES.
258 (defun has-xep-or-nlx (fun)
259   (declare (type clambda fun))
260   (or (eq (functional-kind fun) :external)
261       (let ((entries (lambda-entries fun)))
262         (and entries
263              (find-if #'entry-exits entries)))))
264
265 ;;; Compute the result of FIND-INITIAL-DFO given the list of all
266 ;;; resulting components. Components with a :TOPLEVEL lambda, but no
267 ;;; normal XEPs or potential non-local exits are marked as :TOPLEVEL.
268 ;;; If there is a :TOPLEVEL lambda, and also a normal XEP, then we
269 ;;; treat the component as normal, but also return such components in
270 ;;; a list as the third value. Components with no entry of any sort
271 ;;; are deleted.
272 (defun separate-toplevelish-components (components)
273   (declare (list components))
274   (collect ((real)
275             (top)
276             (real-top))
277     (dolist (component components)
278       (unless (eq (block-next (component-head component))
279                   (component-tail component))
280         (let* ((funs (component-lambdas component))
281                (has-top (find :toplevel funs :key #'functional-kind))
282                (has-external-references
283                 (some #'functional-has-external-references-p funs)))
284           (cond (;; The FUNCTIONAL-HAS-EXTERNAL-REFERENCES-P concept
285                  ;; is newer than the rest of this function, and
286                  ;; doesn't really seem to fit into its mindset. Here
287                  ;; we mark components which contain such FUNCTIONs
288                  ;; them as :COMPLEX-TOPLEVEL, since they do get
289                  ;; executed at run time, and since it's not valid to
290                  ;; delete them just because they don't have any
291                  ;; references from pure :TOPLEVEL components. -- WHN
292                  has-external-references
293                  (setf (component-kind component) :complex-toplevel)
294                  (real component)
295                  (real-top component))
296                 ((or (some #'has-xep-or-nlx funs)
297                      (and has-top (rest funs)))
298                  (setf (component-name component)
299                        (find-component-name component))
300                  (real component)
301                  (when has-top
302                    (setf (component-kind component) :complex-toplevel)
303                    (real-top component)))
304                 (has-top
305                  (setf (component-kind component) :toplevel)
306                  (setf (component-name component) "top level form")
307                  (top component))
308                 (t
309                  (delete-component component))))))
310
311     (values (real) (top) (real-top))))
312
313 ;; COMPONENTs want strings for names, LEAF-DEBUG-NAMEs mightn't be
314 ;; strings..
315 (defun component-name-from-functional-debug-name (functional)
316   (declare (type functional functional))
317   (let ((leaf-debug-name (leaf-debug-name functional)))
318     (the simple-string
319       (if (stringp leaf-debug-name)
320           leaf-debug-name
321           (debug-namify "function ~S" leaf-debug-name)))))
322
323 ;;; Given a list of top level lambdas, return
324 ;;;   (VALUES NONTOP-COMPONENTS TOP-COMPONENTS HAIRY-TOP-COMPONENTS).
325 ;;; Each of the three values returned is a list of COMPONENTs:
326 ;;;   NONTOP-COMPONENTS = non-top-level-ish COMPONENTs;
327 ;;;   TOP-COMPONENTS = top-level-ish COMPONENTs;
328 ;;;   HAIRY-TOP-COMPONENTS = a subset of NONTOP-COMPONENTS, those
329 ;;;    elements which include a top-level-ish lambda.
330 ;;;
331 ;;; We assign the DFO for each component, and delete any unreachable
332 ;;; blocks. We assume that the FLAGS have already been cleared.
333 (defun find-initial-dfo (toplevel-lambdas)
334   (declare (list toplevel-lambdas))
335   (collect ((components))
336     ;; We iterate over the lambdas in each initial component, trying
337     ;; to put each function in its own component, but joining it to
338     ;; an existing component if we find that there are references
339     ;; between them. Any code that is left in an initial component
340     ;; must be unreachable, so we can delete it. Stray links to the
341     ;; initial component tail (due NIL function terminated blocks)
342     ;; are moved to the appropriate newc component tail.
343     (dolist (toplevel-lambda toplevel-lambdas)
344       (let* ((block (lambda-block toplevel-lambda))
345              (old-component (block-component block))
346              (old-component-lambdas (component-lambdas old-component))
347              (new-component nil))
348         (aver (member toplevel-lambda old-component-lambdas))
349         (dolist (component-lambda old-component-lambdas)
350           (aver (member (functional-kind component-lambda)
351                         '(:optional :external :toplevel nil :escape
352                                     :cleanup)))
353           (unless new-component
354             (setf new-component (make-empty-component))
355             (setf (component-name new-component)
356                   ;; This isn't necessarily an ideal name for the
357                   ;; component, since it might end up with multiple
358                   ;; lambdas in it, not just this one, but it does
359                   ;; seem a better name than just "<unknown>".
360                   (component-name-from-functional-debug-name
361                    component-lambda)))
362           (let ((res (dfo-scavenge-call-graph component-lambda new-component)))
363             (when (eq res new-component)
364               (aver (not (position new-component (components))))
365               (components new-component)
366               (setq new-component nil))))
367         (when (eq (component-kind old-component) :initial)
368           (aver (null (component-lambdas old-component)))
369           (let ((tail (component-tail old-component)))
370             (dolist (pred (block-pred tail))
371               (let ((pred-component (block-component pred)))
372                 (unless (eq pred-component old-component)
373                   (unlink-blocks pred tail)
374                   (link-blocks pred (component-tail pred-component))))))
375           (delete-component old-component))))
376
377     ;; When we are done, we assign DFNs.
378     (dolist (component (components))
379       (let ((num 0))
380         (declare (fixnum num))
381         (do-blocks-backwards (block component :both)
382           (setf (block-number block) (incf num)))))
383
384     ;; Pull out top-level-ish code.
385     (separate-toplevelish-components (components))))
386 \f
387 ;;; Insert the code in LAMBDA at the end of RESULT-LAMBDA.
388 (defun merge-1-toplevel-lambda (result-lambda lambda)
389   (declare (type clambda result-lambda lambda))
390
391   ;; Delete the lambda, and combine the LETs and entries.
392   (setf (functional-kind lambda) :deleted)
393   (dolist (let (lambda-lets lambda))
394     (setf (lambda-home let) result-lambda)
395     (setf (lambda-physenv let) (lambda-physenv result-lambda))
396     (push let (lambda-lets result-lambda)))
397   (setf (lambda-entries result-lambda)
398         (nconc (lambda-entries result-lambda)
399                (lambda-entries lambda)))
400
401   (let* ((bind (lambda-bind lambda))
402          (bind-block (node-block bind))
403          (component (block-component bind-block))
404          (result-component (lambda-component result-lambda))
405          (result-return-block (node-block (lambda-return result-lambda))))
406
407     ;; Move blocks into the new COMPONENT, and move any nodes directly
408     ;; in the old LAMBDA into the new one (with LETs implicitly moved
409     ;; by changing their home.)
410     (do-blocks (block component)
411       (do-nodes (node cont block)
412         (let ((lexenv (node-lexenv node)))
413           (when (eq (lexenv-lambda lexenv) lambda)
414             (setf (lexenv-lambda lexenv) result-lambda))))
415       (setf (block-component block) result-component))
416
417     ;; Splice the blocks into the new DFO, and unlink them from the
418     ;; old component head and tail. Non-return blocks that jump to the
419     ;; tail (NIL-returning calls) are switched to go to the new tail.
420     (let* ((head (component-head component))
421            (first (block-next head))
422            (tail (component-tail component))
423            (last (block-prev tail))
424            (prev (block-prev result-return-block)))
425       (setf (block-next prev) first)
426       (setf (block-prev first) prev)
427       (setf (block-next last) result-return-block)
428       (setf (block-prev result-return-block) last)
429       (dolist (succ (block-succ head))
430         (unlink-blocks head succ))
431       (dolist (pred (block-pred tail))
432         (unlink-blocks pred tail)
433         (let ((last (block-last pred)))
434           (unless (return-p last)
435             (aver (basic-combination-p last))
436             (link-blocks pred (component-tail result-component))))))
437
438     (let ((lambdas (component-lambdas component)))
439       (aver (and (null (rest lambdas))
440                  (eq (first lambdas) lambda))))
441
442     ;; Switch the end of the code from the return block to the start of
443     ;; the next chunk.
444     (dolist (pred (block-pred result-return-block))
445       (unlink-blocks pred result-return-block)
446       (link-blocks pred bind-block))
447     (unlink-node bind)
448
449     ;; If there is a return, then delete it (making the preceding node
450     ;; the last node) and link the block to the result return. There
451     ;; is always a preceding REF NIL node in top level lambdas.
452     (let ((return (lambda-return lambda)))
453       (when return
454         (let ((return-block (node-block return))
455               (result (return-result return)))
456           (setf (block-last return-block) (continuation-use result))
457           (flush-dest result)
458           (delete-continuation result)
459           (link-blocks return-block result-return-block))))))
460
461 ;;; Given a non-empty list of top level LAMBDAs, smash them into a
462 ;;; top level lambda and component, returning these as values. We use
463 ;;; the first lambda and its component, putting the other code in that
464 ;;; component and deleting the other lambdas.
465 (defun merge-toplevel-lambdas (lambdas)
466   (declare (cons lambdas))
467   (let* ((result-lambda (first lambdas))
468          (result-return (lambda-return result-lambda)))
469     (cond
470      (result-return
471
472       ;; Make sure the result's return node starts a block so that we
473       ;; can splice code in before it.
474       (let ((prev (node-prev
475                    (continuation-use
476                     (return-result result-return)))))
477         (when (continuation-use prev)
478           (node-ends-block (continuation-use prev)))
479         (do-uses (use prev)
480           (let ((new (make-continuation)))
481             (delete-continuation-use use)
482             (add-continuation-use use new))))
483
484       (dolist (lambda (rest lambdas))
485         (merge-1-toplevel-lambda result-lambda lambda)))
486      (t
487       (dolist (lambda (rest lambdas))
488         (setf (functional-entry-fun lambda) nil)
489         (delete-component (lambda-component lambda)))))
490
491     (values (lambda-component result-lambda) result-lambda)))