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