0.pre7.49:
[sbcl.git] / src / compiler / envanal.lisp
1 ;;;; This file implements the environment analysis phase for the
2 ;;;; compiler. This phase annotates IR1 with a hierarchy environment
3 ;;;; structures, determining the environment that each LAMBDA 
4 ;;;; allocates its variables and finding what values are closed over
5 ;;;; by each environment.
6
7 ;;;; This software is part of the SBCL system. See the README file for
8 ;;;; more information.
9 ;;;;
10 ;;;; This software is derived from the CMU CL system, which was
11 ;;;; written at Carnegie Mellon University and released into the
12 ;;;; public domain. The software is in the public domain and is
13 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
14 ;;;; files for more information.
15
16 (in-package "SB!C")
17
18 ;;; Do environment analysis on the code in COMPONENT. This involves
19 ;;; various things:
20 ;;;  1. Make an ENVIRONMENT structure for each non-LET LAMBDA, assigning 
21 ;;;     the LAMBDA-ENVIRONMENT for all LAMBDAs.
22 ;;;  2. Find all values that need to be closed over by each environment.
23 ;;;  3. Scan the blocks in the component closing over non-local-exit
24 ;;;     continuations.
25 ;;;  4. Delete all non-top-level functions with no references. This
26 ;;;     should only get functions with non-NULL kinds, since normal
27 ;;;     functions are deleted when their references go to zero. If
28 ;;;     *BYTE-COMPILING*, then don't delete optional entries with no
29 ;;;     references, since the byte interpreter wants to call entries
30 ;;;     that the XEP doesn't.
31 (defun environment-analyze (component)
32   (declare (type component component))
33   (aver (every (lambda (x)
34                  (eq (functional-kind x) :deleted))
35                (component-new-functions component)))
36   (setf (component-new-functions component) ())
37   (dolist (fun (component-lambdas component))
38     (reinit-lambda-environment fun))
39   (dolist (fun (component-lambdas component))
40     (compute-closure fun)
41     (dolist (let (lambda-lets fun))
42       (compute-closure let)))
43
44   (find-non-local-exits component)
45   (find-cleanup-points component)
46   (tail-annotate component)
47
48   (dolist (fun (component-lambdas component))
49     (when (null (leaf-refs fun))
50       (let ((kind (functional-kind fun)))
51         (unless (or (eq kind :top-level)
52                     (functional-has-external-references-p fun))
53           (aver (member kind '(:optional :cleanup :escape)))
54           (setf (functional-kind fun) nil)
55           (delete-functional fun)))))
56
57   (values))
58
59 ;;; This is to be called on a COMPONENT with top-level LAMBDAs before
60 ;;; the compilation of the associated non-top-level code to detect
61 ;;; closed over top-level variables. We just do COMPUTE-CLOSURE on all
62 ;;; the lambdas. This will pre-allocate environments for all the
63 ;;; functions with closed-over top-level variables. The post-pass will
64 ;;; use the existing structure, rather than allocating a new one. We
65 ;;; return true if we discover any possible closure vars.
66 (defun pre-environment-analyze-top-level (component)
67   (declare (type component component))
68   (let ((found-it nil))
69     (dolist (lambda (component-lambdas component))
70       (when (compute-closure lambda)
71         (setq found-it t))
72       (dolist (let (lambda-lets lambda))
73         (when (compute-closure let)
74           (setq found-it t))))
75     found-it))
76
77 ;;; This is like old CMU CL PRE-ENVIRONMENT-ANALYZE-TOP-LEVEL, except
78 ;;;   (1) It's been brought into the post-0.7.0 world where the property
79 ;;;       HAS-EXTERNAL-REFERENCES-P is orthogonal to the property of
80 ;;;       being specialized/optimized for locall at top level.
81 ;;;   (2) There's no return value, since we don't care whether we
82 ;;;       find any possible closure variables.
83 ;;;
84 ;;; I wish I could find an explanation of why
85 ;;; PRE-ENVIRONMENT-ANALYZE-TOP-LEVEL is important. The old CMU CL
86 ;;; comments said
87 ;;;     Called on component with top-level lambdas before the
88 ;;;     compilation of the associated non-top-level code to detect
89 ;;;     closed over top-level variables. We just do COMPUTE-CLOSURE on
90 ;;;     all the lambdas. This will pre-allocate environments for all
91 ;;;     the functions with closed-over top-level variables. The
92 ;;;     post-pass will use the existing structure, rather than
93 ;;;     allocating a new one. We return true if we discover any
94 ;;;     possible closure vars.
95 ;;; But that doesn't seem to explain why it's important. I do observe
96 ;;; that when it's not done, compiler assertions occasionally fail. My
97 ;;; tentative hypothesis is that other environment analysis expects to
98 ;;; bottom out on the outermost enclosing thing, and (insert
99 ;;; mysterious reason here) it's important to set up bottomed-out-here
100 ;;; environments before anything else. -- WHN 2001-09-30
101 (defun preallocate-environments-for-top-levelish-lambdas (component)
102   (dolist (clambda (component-lambdas component))
103     (when (lambda-top-levelish-p clambda)
104       (compute-closure clambda)))
105   (values))
106
107 ;;; If FUN has an environment, return it, otherwise assign an empty one.
108 (defun get-lambda-environment (fun)
109   (declare (type clambda fun))
110   (let* ((fun (lambda-home fun))
111          (env (lambda-environment fun)))
112     (or env
113         (let ((res (make-environment :function fun)))
114           (setf (lambda-environment fun) res)
115           (dolist (letlambda (lambda-lets fun))
116             ;; This assertion is to make explicit an
117             ;; apparently-otherwise-undocumented property of existing
118             ;; code: We never overwrite an old LAMBDA-ENVIRONMENT.
119             ;; -- WHN 2001-09-30
120             (aver (null (lambda-environment letlambda)))
121             ;; I *think* this is true regardless of LAMBDA-KIND.
122             ;; -- WHN 2001-09-30
123             (aver (eql (lambda-home letlambda) fun))
124             (setf (lambda-environment letlambda) res))
125           res))))
126
127 ;;; If FUN has no physical environment, assign one, otherwise clean up
128 ;;; the old physical environment, removing/flagging variables that
129 ;;; have no sets or refs. If a var has no references, we remove it
130 ;;; from the closure. If it has no sets, we clear the INDIRECT flag.
131 ;;; This is necessary because pre-analysis is done before
132 ;;; optimization.
133 (defun reinit-lambda-environment (fun)
134   (let ((old (lambda-environment (lambda-home fun))))
135     (cond (old
136            (setf (environment-closure old)
137                  (delete-if #'(lambda (x)
138                                 (and (lambda-var-p x)
139                                      (null (leaf-refs x))))
140                             (environment-closure old)))
141            (flet ((clear (fun)
142                     (dolist (var (lambda-vars fun))
143                       (unless (lambda-var-sets var)
144                         (setf (lambda-var-indirect var) nil)))))
145              (clear fun)
146              (dolist (let (lambda-lets fun))
147                (clear let))))
148           (t
149            (get-lambda-environment fun))))
150   (values))
151
152 ;;; Get NODE's environment, assigning one if necessary.
153 (defun get-node-environment (node)
154   (declare (type node node))
155   (get-lambda-environment (node-home-lambda node)))
156
157 ;;; Find any variables in FUN with references outside of the home
158 ;;; environment and close over them. If a closed over variable is set,
159 ;;; then we set the INDIRECT flag so that we will know the closed over
160 ;;; value is really a pointer to the value cell. We also warn about
161 ;;; unreferenced variables here, just because it's a convenient place
162 ;;; to do it. We return true if we close over anything.
163 (defun compute-closure (fun)
164   (declare (type clambda fun))
165   (let ((env (get-lambda-environment fun))
166         (did-something nil))
167     (note-unreferenced-vars fun)
168     (dolist (var (lambda-vars fun))
169       (dolist (ref (leaf-refs var))
170         (let ((ref-env (get-node-environment ref)))
171           (unless (eq ref-env env)
172             (when (lambda-var-sets var)
173               (setf (lambda-var-indirect var) t))
174             (setq did-something t)
175             (close-over var ref-env env))))
176       (dolist (set (basic-var-sets var))
177         (let ((set-env (get-node-environment set)))
178           (unless (eq set-env env)
179             (setq did-something t)
180             (setf (lambda-var-indirect var) t)
181             (close-over var set-env env)))))
182     did-something))
183
184 ;;; Make sure that THING is closed over in REF-ENV and in all
185 ;;; environments for the functions that reference REF-ENV's function
186 ;;; (not just calls.) HOME-ENV is THING's home environment. When we
187 ;;; reach the home environment, we stop propagating the closure.
188 (defun close-over (thing ref-env home-env)
189   (declare (type environment ref-env home-env))
190   (cond ((eq ref-env home-env))
191         ((member thing (environment-closure ref-env)))
192         (t
193          (push thing (environment-closure ref-env))
194          (dolist (call (leaf-refs (environment-function ref-env)))
195            (close-over thing (get-node-environment call) home-env))))
196   (values))
197 \f
198 ;;;; non-local exit
199
200 ;;; Insert the entry stub before the original exit target, and add a
201 ;;; new entry to the ENVIRONMENT-NLX-INFO. The %NLX-ENTRY call in the
202 ;;; stub is passed the NLX-INFO as an argument so that the back end
203 ;;; knows what entry is being done.
204 ;;;
205 ;;; The link from the EXIT block to the entry stub is changed to be a
206 ;;; link to the component head. Similarly, the EXIT block is linked to
207 ;;; the component tail. This leaves the entry stub reachable, but
208 ;;; makes the flow graph less confusing to flow analysis.
209 ;;;
210 ;;; If a CATCH or an UNWIND-protect, then we set the LEXENV for the
211 ;;; last node in the cleanup code to be the enclosing environment, to
212 ;;; represent the fact that the binding was undone as a side-effect of
213 ;;; the exit. This will cause a lexical exit to be broken up if we are
214 ;;; actually exiting the scope (i.e. a BLOCK), and will also do any
215 ;;; other cleanups that may have to be done on the way.
216 (defun insert-nlx-entry-stub (exit env)
217   (declare (type environment env) (type exit exit))
218   (let* ((exit-block (node-block exit))
219          (next-block (first (block-succ exit-block)))
220          (cleanup (entry-cleanup (exit-entry exit)))
221          (info (make-nlx-info :cleanup cleanup
222                               :continuation (node-cont exit)))
223          (entry (exit-entry exit))
224          (new-block (insert-cleanup-code exit-block next-block
225                                          entry
226                                          `(%nlx-entry ',info)
227                                          (entry-cleanup entry)))
228          (component (block-component new-block)))
229     (unlink-blocks exit-block new-block)
230     (link-blocks exit-block (component-tail component))
231     (link-blocks (component-head component) new-block)
232
233     (setf (nlx-info-target info) new-block)
234     (push info (environment-nlx-info env))
235     (push info (cleanup-nlx-info cleanup))
236     (when (member (cleanup-kind cleanup) '(:catch :unwind-protect))
237       (setf (node-lexenv (block-last new-block))
238             (node-lexenv entry))))
239
240   (values))
241
242 ;;; Do stuff necessary to represent a non-local exit from the node
243 ;;; EXIT into ENV. This is called for each non-local exit node, of
244 ;;; which there may be several per exit continuation. This is what we
245 ;;; do:
246 ;;; -- If there isn't any NLX-Info entry in the environment, make
247 ;;;    an entry stub, otherwise just move the exit block link to
248 ;;;    the component tail.
249 ;;; -- Close over the NLX-Info in the exit environment.
250 ;;; -- If the exit is from an :Escape function, then substitute a
251 ;;;    constant reference to NLX-Info structure for the escape
252 ;;;    function reference. This will cause the escape function to
253 ;;;    be deleted (although not removed from the DFO.)  The escape
254 ;;;    function is no longer needed, and we don't want to emit code
255 ;;;    for it. We then also change the %NLX-ENTRY call to use the
256 ;;;    NLX continuation so that there will be a use to represent
257 ;;;    the NLX use.
258 (defun note-non-local-exit (env exit)
259   (declare (type environment env) (type exit exit))
260   (let ((entry (exit-entry exit))
261         (cont (node-cont exit))
262         (exit-fun (node-home-lambda exit)))
263
264     (if (find-nlx-info entry cont)
265         (let ((block (node-block exit)))
266           (aver (= (length (block-succ block)) 1))
267           (unlink-blocks block (first (block-succ block)))
268           (link-blocks block (component-tail (block-component block))))
269         (insert-nlx-entry-stub exit env))
270
271     (let ((info (find-nlx-info entry cont)))
272       (aver info)
273       (close-over info (node-environment exit) env)
274       (when (eq (functional-kind exit-fun) :escape)
275         (mapc #'(lambda (x)
276                   (setf (node-derived-type x) *wild-type*))
277               (leaf-refs exit-fun))
278         (substitute-leaf (find-constant info) exit-fun)
279         (let ((node (block-last (nlx-info-target info))))
280           (delete-continuation-use node)
281           (add-continuation-use node (nlx-info-continuation info))))))
282
283   (values))
284
285 ;;; Iterate over the EXITs in COMPONENT, calling NOTE-NON-LOCAL-EXIT
286 ;;; when we find a block that ends in a non-local EXIT node. We also
287 ;;; ensure that all EXIT nodes are either non-local or degenerate by
288 ;;; calling IR1-OPTIMIZE-EXIT on local exits. This makes life simpler
289 ;;; for later phases.
290 (defun find-non-local-exits (component)
291   (declare (type component component))
292   (dolist (lambda (component-lambdas component))
293     (dolist (entry (lambda-entries lambda))
294       (dolist (exit (entry-exits entry))
295         (let ((target-env (node-environment entry)))
296           (if (eq (node-environment exit) target-env)
297               (maybe-delete-exit exit)
298               (note-non-local-exit target-env exit))))))
299
300   (values))
301 \f
302 ;;;; cleanup emission
303
304 ;;; Zoom up the cleanup nesting until we hit CLEANUP1, accumulating
305 ;;; cleanup code as we go. When we are done, convert the cleanup code
306 ;;; in an implicit MV-PROG1. We have to force local call analysis of
307 ;;; new references to UNWIND-PROTECT cleanup functions. If we don't
308 ;;; actually have to do anything, then we don't insert any cleanup
309 ;;; code.
310 ;;;
311 ;;; If we do insert cleanup code, we check that BLOCK1 doesn't end in
312 ;;; a "tail" local call.
313 ;;;
314 ;;; We don't need to adjust the ending cleanup of the cleanup block,
315 ;;; since the cleanup blocks are inserted at the start of the DFO, and
316 ;;; are thus never scanned.
317 (defun emit-cleanups (block1 block2)
318   (declare (type cblock block1 block2))
319   (collect ((code)
320             (reanalyze-funs))
321     (let ((cleanup2 (block-start-cleanup block2)))
322       (do ((cleanup (block-end-cleanup block1)
323                     (node-enclosing-cleanup (cleanup-mess-up cleanup))))
324           ((eq cleanup cleanup2))
325         (let* ((node (cleanup-mess-up cleanup))
326                (args (when (basic-combination-p node)
327                        (basic-combination-args node))))
328           (ecase (cleanup-kind cleanup)
329             (:special-bind
330              (code `(%special-unbind ',(continuation-value (first args)))))
331             (:catch
332              (code `(%catch-breakup)))
333             (:unwind-protect
334              (code `(%unwind-protect-breakup))
335              (let ((fun (ref-leaf (continuation-use (second args)))))
336                (reanalyze-funs fun)
337                (code `(%funcall ,fun))))
338             ((:block :tagbody)
339              (dolist (nlx (cleanup-nlx-info cleanup))
340                (code `(%lexical-exit-breakup ',nlx)))))))
341
342       (when (code)
343         (aver (not (node-tail-p (block-last block1))))
344         (insert-cleanup-code block1 block2
345                              (block-last block1)
346                              `(progn ,@(code)))
347         (dolist (fun (reanalyze-funs))
348           (local-call-analyze-1 fun)))))
349
350   (values))
351
352 ;;; Loop over the blocks in COMPONENT, calling EMIT-CLEANUPS when we
353 ;;; see a successor in the same environment with a different cleanup.
354 ;;; We ignore the cleanup transition if it is to a cleanup enclosed by
355 ;;; the current cleanup, since in that case we are just messing up the
356 ;;; environment, hence this is not the place to clean it.
357 (defun find-cleanup-points (component)
358   (declare (type component component))
359   (do-blocks (block1 component)
360     (let ((env1 (block-environment block1))
361           (cleanup1 (block-end-cleanup block1)))
362       (dolist (block2 (block-succ block1))
363         (when (block-start block2)
364           (let ((env2 (block-environment block2))
365                 (cleanup2 (block-start-cleanup block2)))
366             (unless (or (not (eq env2 env1))
367                         (eq cleanup1 cleanup2)
368                         (and cleanup2
369                              (eq (node-enclosing-cleanup
370                                   (cleanup-mess-up cleanup2))
371                                  cleanup1)))
372               (emit-cleanups block1 block2)))))))
373   (values))
374
375 ;;; Mark all tail-recursive uses of function result continuations with
376 ;;; the corresponding TAIL-SET. Nodes whose type is NIL (i.e. don't
377 ;;; return) such as calls to ERROR are never annotated as tail in
378 ;;; order to preserve debugging information.
379 (defun tail-annotate (component)
380   (declare (type component component))
381   (dolist (fun (component-lambdas component))
382     (let ((ret (lambda-return fun)))
383       (when ret
384         (let ((result (return-result ret)))
385           (do-uses (use result)
386             (when (and (immediately-used-p result use)
387                      (or (not (eq (node-derived-type use) *empty-type*))
388                          (not (basic-combination-p use))
389                          (eq (basic-combination-kind use) :local)))
390                 (setf (node-tail-p use) t)))))))
391   (values))