ae4ad080dba81e34272ceb09d17fe891dd6178ad
[sbcl.git] / src / compiler / locall.lisp
1 ;;;; This file implements local call analysis. A local call is a
2 ;;;; function call between functions being compiled at the same time.
3 ;;;; If we can tell at compile time that such a call is legal, then we
4 ;;;; change the combination to call the correct lambda, mark it as
5 ;;;; local, and add this link to our call graph. Once a call is local,
6 ;;;; it is then eligible for let conversion, which places the body of
7 ;;;; the function inline.
8 ;;;;
9 ;;;; We cannot always do a local call even when we do have the
10 ;;;; function being called. Calls that cannot be shown to have legal
11 ;;;; arg counts are not converted.
12
13 ;;;; This software is part of the SBCL system. See the README file for
14 ;;;; more information.
15 ;;;;
16 ;;;; This software is derived from the CMU CL system, which was
17 ;;;; written at Carnegie Mellon University and released into the
18 ;;;; public domain. The software is in the public domain and is
19 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
20 ;;;; files for more information.
21
22 (in-package "SB!C")
23
24 ;;; This function propagates information from the variables in the
25 ;;; function FUN to the actual arguments in CALL. This is also called
26 ;;; by the VALUES IR1 optimizer when it sleazily converts MV-BINDs to
27 ;;; LETs.
28 ;;;
29 ;;; We flush all arguments to CALL that correspond to unreferenced
30 ;;; variables in FUN. We leave NILs in the COMBINATION-ARGS so that
31 ;;; the remaining args still match up with their vars.
32 ;;;
33 ;;; We also apply the declared variable type assertion to the argument
34 ;;; continuations.
35 (defun propagate-to-args (call fun)
36   (declare (type combination call) (type clambda fun))
37   (do ((args (basic-combination-args call) (cdr args))
38        (vars (lambda-vars fun) (cdr vars)))
39       ((null args))
40     (let ((arg (car args))
41           (var (car vars)))
42       (cond ((leaf-refs var)
43              (assert-continuation-type arg (leaf-type var)
44                                        (lexenv-policy (node-lexenv call))))
45             (t
46              (flush-dest arg)
47              (setf (car args) nil)))))
48
49   (values))
50
51 ;;; This function handles merging the tail sets if CALL is potentially
52 ;;; tail-recursive, and is a call to a function with a different
53 ;;; TAIL-SET than CALL's FUN. This must be called whenever we alter
54 ;;; IR1 so as to place a local call in what might be a tail-recursive
55 ;;; context. Note that any call which returns its value to a RETURN is
56 ;;; considered potentially tail-recursive, since any implicit MV-PROG1
57 ;;; might be optimized away.
58 ;;;
59 ;;; We destructively modify the set for the calling function to
60 ;;; represent both, and then change all the functions in callee's set
61 ;;; to reference the first. If we do merge, we reoptimize the
62 ;;; RETURN-RESULT continuation to cause IR1-OPTIMIZE-RETURN to
63 ;;; recompute the tail set type.
64 (defun merge-tail-sets (call &optional (new-fun (combination-lambda call)))
65   (declare (type basic-combination call) (type clambda new-fun))
66   (let ((return (continuation-dest (node-cont call))))
67     (when (return-p return)
68       (let ((call-set (lambda-tail-set (node-home-lambda call)))
69             (fun-set (lambda-tail-set new-fun)))
70         (unless (eq call-set fun-set)
71           (let ((funs (tail-set-funs fun-set)))
72             (dolist (fun funs)
73               (setf (lambda-tail-set fun) call-set))
74             (setf (tail-set-funs call-set)
75                   (nconc (tail-set-funs call-set) funs)))
76           (reoptimize-continuation (return-result return))
77           t)))))
78
79 ;;; Convert a combination into a local call. We PROPAGATE-TO-ARGS, set
80 ;;; the combination kind to :LOCAL, add FUN to the CALLS of the
81 ;;; function that the call is in, call MERGE-TAIL-SETS, then replace
82 ;;; the function in the REF node with the new function.
83 ;;;
84 ;;; We change the REF last, since changing the reference can trigger
85 ;;; LET conversion of the new function, but will only do so if the
86 ;;; call is local. Note that the replacement may trigger LET
87 ;;; conversion or other changes in IR1. We must call MERGE-TAIL-SETS
88 ;;; with NEW-FUN before the substitution, since after the substitution
89 ;;; (and LET conversion), the call may no longer be recognizable as
90 ;;; tail-recursive.
91 (defun convert-call (ref call fun)
92   (declare (type ref ref) (type combination call) (type clambda fun))
93   (propagate-to-args call fun)
94   (setf (basic-combination-kind call) :local)
95   (pushnew fun (lambda-calls-or-closes (node-home-lambda call)))
96   (merge-tail-sets call fun)
97   (change-ref-leaf ref fun)
98   (values))
99 \f
100 ;;;; external entry point creation
101
102 ;;; Return a LAMBDA form that can be used as the definition of the XEP
103 ;;; for FUN.
104 ;;;
105 ;;; If FUN is a LAMBDA, then we check the number of arguments
106 ;;; (conditional on policy) and call FUN with all the arguments.
107 ;;;
108 ;;; If FUN is an OPTIONAL-DISPATCH, then we dispatch off of the number
109 ;;; of supplied arguments by doing do an = test for each entry-point,
110 ;;; calling the entry with the appropriate prefix of the passed
111 ;;; arguments.
112 ;;;
113 ;;; If there is a &MORE arg, then there are a couple of optimizations
114 ;;; that we make (more for space than anything else):
115 ;;; -- If MIN-ARGS is 0, then we make the more entry a T clause, since 
116 ;;;    no argument count error is possible.
117 ;;; -- We can omit the = clause for the last entry-point, allowing the 
118 ;;;    case of 0 more args to fall through to the more entry.
119 ;;;
120 ;;; We don't bother to policy conditionalize wrong arg errors in
121 ;;; optional dispatches, since the additional overhead is negligible
122 ;;; compared to the cost of everything else going on.
123 ;;;
124 ;;; Note that if policy indicates it, argument type declarations in
125 ;;; FUN will be verified. Since nothing is known about the type of the
126 ;;; XEP arg vars, type checks will be emitted when the XEP's arg vars
127 ;;; are passed to the actual function.
128 (defun make-xep-lambda-expression (fun)
129   (declare (type functional fun))
130   (etypecase fun
131     (clambda
132      (let ((nargs (length (lambda-vars fun)))
133            (n-supplied (gensym))
134            (temps (make-gensym-list (length (lambda-vars fun)))))
135        `(lambda (,n-supplied ,@temps)
136           (declare (type index ,n-supplied))
137           ,(if (policy *lexenv* (zerop verify-arg-count))
138                `(declare (ignore ,n-supplied))
139                `(%verify-arg-count ,n-supplied ,nargs))
140           (locally
141             (declare (optimize (merge-tail-calls 3)))
142             (%funcall ,fun ,@temps)))))
143     (optional-dispatch
144      (let* ((min (optional-dispatch-min-args fun))
145             (max (optional-dispatch-max-args fun))
146             (more (optional-dispatch-more-entry fun))
147             (n-supplied (gensym))
148             (temps (make-gensym-list max)))
149        (collect ((entries))
150          (do ((eps (optional-dispatch-entry-points fun) (rest eps))
151               (n min (1+ n)))
152              ((null eps))
153            (entries `((= ,n-supplied ,n)
154                       (%funcall ,(first eps) ,@(subseq temps 0 n)))))
155          `(lambda (,n-supplied ,@temps)
156             ;; FIXME: Make sure that INDEX type distinguishes between
157             ;; target and host. (Probably just make the SB!XC:DEFTYPE
158             ;; different from CL:DEFTYPE.)
159             (declare (type index ,n-supplied))
160             (cond
161              ,@(if more (butlast (entries)) (entries))
162              ,@(when more
163                  `((,(if (zerop min) t `(>= ,n-supplied ,max))
164                     ,(let ((n-context (gensym))
165                            (n-count (gensym)))
166                        `(multiple-value-bind (,n-context ,n-count)
167                             (%more-arg-context ,n-supplied ,max)
168                           (locally
169                             (declare (optimize (merge-tail-calls 3)))
170                             (%funcall ,more ,@temps ,n-context ,n-count)))))))
171              (t
172               (%arg-count-error ,n-supplied)))))))))
173
174 ;;; Make an external entry point (XEP) for FUN and return it. We
175 ;;; convert the result of MAKE-XEP-LAMBDA in the correct environment,
176 ;;; then associate this lambda with FUN as its XEP. After the
177 ;;; conversion, we iterate over the function's associated lambdas,
178 ;;; redoing local call analysis so that the XEP calls will get
179 ;;; converted. 
180 ;;;
181 ;;; We set REANALYZE and REOPTIMIZE in the component, just in case we
182 ;;; discover an XEP after the initial local call analyze pass.
183 (defun make-xep (fun)
184   (declare (type functional fun))
185   (aver (null (functional-entry-fun fun)))
186   (with-ir1-environment-from-node (lambda-bind (main-entry fun))
187     (let ((res (ir1-convert-lambda (make-xep-lambda-expression fun)
188                                    :debug-name (debug-namify
189                                                 "XEP for ~A"
190                                                 (leaf-debug-name fun)))))
191       (setf (functional-kind res) :external
192             (leaf-ever-used res) t
193             (functional-entry-fun res) fun
194             (functional-entry-fun fun) res
195             (component-reanalyze *current-component*) t
196             (component-reoptimize *current-component*) t)
197       (etypecase fun
198         (clambda
199          (locall-analyze-fun-1 fun))
200         (optional-dispatch
201          (dolist (ep (optional-dispatch-entry-points fun))
202            (locall-analyze-fun-1 ep))
203          (when (optional-dispatch-more-entry fun)
204            (locall-analyze-fun-1 (optional-dispatch-more-entry fun)))))
205       res)))
206
207 ;;; Notice a REF that is not in a local-call context. If the REF is
208 ;;; already to an XEP, then do nothing, otherwise change it to the
209 ;;; XEP, making an XEP if necessary.
210 ;;;
211 ;;; If REF is to a special :CLEANUP or :ESCAPE function, then we treat
212 ;;; it as though it was not an XEP reference (i.e. leave it alone).
213 (defun reference-entry-point (ref)
214   (declare (type ref ref))
215   (let ((fun (ref-leaf ref)))
216     (unless (or (xep-p fun)
217                 (member (functional-kind fun) '(:escape :cleanup)))
218       (change-ref-leaf ref (or (functional-entry-fun fun)
219                                (make-xep fun))))))
220 \f
221 ;;; Attempt to convert all references to FUN to local calls. The
222 ;;; reference must be the function for a call, and the function
223 ;;; continuation must be used only once, since otherwise we cannot be
224 ;;; sure what function is to be called. The call continuation would be
225 ;;; multiply used if there is hairy stuff such as conditionals in the
226 ;;; expression that computes the function.
227 ;;;
228 ;;; If we cannot convert a reference, then we mark the referenced
229 ;;; function as an entry-point, creating a new XEP if necessary. We
230 ;;; don't try to convert calls that are in error (:ERROR kind.)
231 ;;;
232 ;;; This is broken off from LOCALL-ANALYZE-COMPONENT so that people
233 ;;; can force analysis of newly introduced calls. Note that we don't
234 ;;; do LET conversion here.
235 (defun locall-analyze-fun-1 (fun)
236   (declare (type functional fun))
237   (let ((refs (leaf-refs fun))
238         (first-time t))
239     (dolist (ref refs)
240       (let* ((cont (node-cont ref))
241              (dest (continuation-dest cont)))
242         (cond ((and (basic-combination-p dest)
243                     (eq (basic-combination-fun dest) cont)
244                     (eq (continuation-use cont) ref))
245
246                (convert-call-if-possible ref dest)
247
248                (unless (eq (basic-combination-kind dest) :local)
249                  (reference-entry-point ref)))
250               (t
251                (reference-entry-point ref))))
252       (setq first-time nil)))
253
254   (values))
255
256 ;;; We examine all NEW-FUNCTIONALS in COMPONENT, attempting to convert
257 ;;; calls into local calls when it is legal. We also attempt to
258 ;;; convert each LAMBDA to a LET. LET conversion is also triggered by
259 ;;; deletion of a function reference, but functions that start out
260 ;;; eligible for conversion must be noticed sometime.
261 ;;;
262 ;;; Note that there is a lot of action going on behind the scenes
263 ;;; here, triggered by reference deletion. In particular, the
264 ;;; COMPONENT-LAMBDAS are being hacked to remove newly deleted and LET
265 ;;; converted LAMBDAs, so it is important that the LAMBDA is added to
266 ;;; the COMPONENT-LAMBDAS when it is. Also, the
267 ;;; COMPONENT-NEW-FUNCTIONALS may contain all sorts of drivel, since
268 ;;; it is not updated when we delete functions, etc. Only
269 ;;; COMPONENT-LAMBDAS is updated.
270 ;;;
271 ;;; COMPONENT-REANALYZE-FUNCTIONALS is treated similarly to
272 ;;; COMPONENT-NEW-FUNCTIONALS, but we don't add lambdas to the
273 ;;; LAMBDAS.
274 (defun locall-analyze-component (component)
275   (declare (type component component))
276   (aver-live-component component)
277   (loop
278     (let* ((new-functional (pop (component-new-functionals component)))
279            (functional (or new-functional
280                            (pop (component-reanalyze-functionals component)))))
281       (unless functional
282         (return))
283       (let ((kind (functional-kind functional)))
284         (cond ((or (functional-somewhat-letlike-p functional)
285                    (eql kind :deleted))
286                (values)) ; nothing to do
287               ((and (null (leaf-refs functional)) (eq kind nil)
288                     (not (functional-entry-fun functional)))
289                (delete-functional functional))
290               (t
291                ;; Fix/check FUNCTIONAL's relationship to COMPONENT-LAMDBAS.
292                (cond ((not (lambda-p functional))
293                       ;; Since FUNCTIONAL isn't a LAMBDA, this doesn't
294                       ;; apply: no-op.
295                       (values))
296                      (new-functional ; FUNCTIONAL came from
297                                      ; NEW-FUNCTIONALS, hence is new.
298                       ;; FUNCTIONAL becomes part of COMPONENT-LAMBDAS now.
299                       (aver (not (member functional
300                                          (component-lambdas component))))
301                       (push functional (component-lambdas component)))
302                      (t ; FUNCTIONAL is old.
303                       ;; FUNCTIONAL should be in COMPONENT-LAMBDAS already.
304                       (aver (member functional (component-lambdas
305                                                 component)))))
306                (locall-analyze-fun-1 functional)
307                (when (lambda-p functional)
308                  (maybe-let-convert functional)))))))
309   (values))
310
311 (defun locall-analyze-clambdas-until-done (clambdas)
312   (loop
313    (let ((did-something nil))
314      (dolist (clambda clambdas)
315        (let* ((component (lambda-component clambda))
316               (*all-components* (list component)))
317          ;; The original CMU CL code seemed to implicitly assume that
318          ;; COMPONENT is the only one here. Let's make that explicit.
319          (aver (= 1 (length (functional-components clambda))))
320          (aver (eql component (first (functional-components clambda))))
321          (when (component-new-functionals component)
322            (setf did-something t)
323            (locall-analyze-component component))))
324      (unless did-something
325        (return))))
326   (values))
327
328 ;;; If policy is auspicious and CALL is not in an XEP and we don't seem
329 ;;; to be in an infinite recursive loop, then change the reference to
330 ;;; reference a fresh copy. We return whichever function we decide to
331 ;;; reference.
332 (defun maybe-expand-local-inline (original-functional ref call)
333   (if (and (policy call
334                    (and (>= speed space)
335                         (>= speed compilation-speed)))
336            (not (eq (functional-kind (node-home-lambda call)) :external))
337            (inline-expansion-ok call))
338       (multiple-value-bind (losing-local-functional converted-lambda)
339           (catch 'locall-already-let-converted
340             (with-ir1-environment-from-node call
341               (let ((*lexenv* (functional-lexenv original-functional)))
342                 (values nil
343                         (ir1-convert-lambda
344                          (functional-inline-expansion original-functional)
345                          :debug-name (debug-namify
346                                       "local inline ~A"
347                                       (leaf-debug-name
348                                        original-functional)))))))
349         (cond (losing-local-functional
350                (let ((*compiler-error-context* call))
351                  (compiler-note "couldn't inline expand because expansion ~
352                                  calls this LET-converted local function:~
353                                  ~%  ~S"
354                                 (leaf-debug-name losing-local-functional)))
355                original-functional)
356               (t
357                (change-ref-leaf ref converted-lambda)
358                converted-lambda)))
359       original-functional))
360
361 ;;; Dispatch to the appropriate function to attempt to convert a call.
362 ;;; REF must be a reference to a FUNCTIONAL. This is called in IR1
363 ;;; optimization as well as in local call analysis. If the call is is
364 ;;; already :LOCAL, we do nothing. If the call is already scheduled
365 ;;; for deletion, also do nothing (in addition to saving time, this
366 ;;; also avoids some problems with optimizing collections of functions
367 ;;; that are partially deleted.)
368 ;;;
369 ;;; This is called both before and after FIND-INITIAL-DFO runs. When
370 ;;; called on a :INITIAL component, we don't care whether the caller
371 ;;; and callee are in the same component. Afterward, we must stick
372 ;;; with whatever component division we have chosen.
373 ;;;
374 ;;; Before attempting to convert a call, we see whether the function
375 ;;; is supposed to be inline expanded. Call conversion proceeds as
376 ;;; before after any expansion.
377 ;;;
378 ;;; We bind *COMPILER-ERROR-CONTEXT* to the node for the call so that
379 ;;; warnings will get the right context.
380 (defun convert-call-if-possible (ref call)
381   (declare (type ref ref) (type basic-combination call))
382   (let* ((block (node-block call))
383          (component (block-component block))
384          (original-fun (ref-leaf ref)))
385     (aver (functional-p original-fun))
386     (unless (or (member (basic-combination-kind call) '(:local :error))
387                 (block-delete-p block)
388                 (eq (functional-kind (block-home-lambda block)) :deleted)
389                 (member (functional-kind original-fun)
390                         '(:toplevel-xep :deleted))
391                 (not (or (eq (component-kind component) :initial)
392                          (eq (block-component
393                               (node-block
394                                (lambda-bind (main-entry original-fun))))
395                              component))))
396       (let ((fun (if (xep-p original-fun)
397                      (functional-entry-fun original-fun)
398                      original-fun))
399             (*compiler-error-context* call))
400
401         (when (and (eq (functional-inlinep fun) :inline)
402                    (rest (leaf-refs original-fun)))
403           (setq fun (maybe-expand-local-inline fun ref call)))
404
405         (aver (member (functional-kind fun)
406                       '(nil :escape :cleanup :optional)))
407         (cond ((mv-combination-p call)
408                (convert-mv-call ref call fun))
409               ((lambda-p fun)
410                (convert-lambda-call ref call fun))
411               (t
412                (convert-hairy-call ref call fun))))))
413
414   (values))
415
416 ;;; Attempt to convert a multiple-value call. The only interesting
417 ;;; case is a call to a function that LOOKS-LIKE-AN-MV-BIND, has
418 ;;; exactly one reference and no XEP, and is called with one values
419 ;;; continuation.
420 ;;;
421 ;;; We change the call to be to the last optional entry point and
422 ;;; change the call to be local. Due to our preconditions, the call
423 ;;; should eventually be converted to a let, but we can't do that now,
424 ;;; since there may be stray references to the e-p lambda due to
425 ;;; optional defaulting code.
426 ;;;
427 ;;; We also use variable types for the called function to construct an
428 ;;; assertion for the values continuation.
429 ;;;
430 ;;; See CONVERT-CALL for additional notes on MERGE-TAIL-SETS, etc.
431 (defun convert-mv-call (ref call fun)
432   (declare (type ref ref) (type mv-combination call) (type functional fun))
433   (when (and (looks-like-an-mv-bind fun)
434              (not (functional-entry-fun fun))
435              (= (length (leaf-refs fun)) 1)
436              (= (length (basic-combination-args call)) 1))
437     (let ((ep (car (last (optional-dispatch-entry-points fun)))))
438       (setf (basic-combination-kind call) :local)
439       (pushnew ep (lambda-calls-or-closes (node-home-lambda call)))
440       (merge-tail-sets call ep)
441       (change-ref-leaf ref ep)
442
443       (assert-continuation-type
444        (first (basic-combination-args call))
445        (make-values-type :optional (mapcar #'leaf-type (lambda-vars ep))
446                          :rest *universal-type*)
447        (lexenv-policy (node-lexenv call)))))
448   (values))
449
450 ;;; Attempt to convert a call to a lambda. If the number of args is
451 ;;; wrong, we give a warning and mark the call as :ERROR to remove it
452 ;;; from future consideration. If the argcount is O.K. then we just
453 ;;; convert it.
454 (defun convert-lambda-call (ref call fun)
455   (declare (type ref ref) (type combination call) (type clambda fun))
456   (let ((nargs (length (lambda-vars fun)))
457         (call-args (length (combination-args call))))
458     (cond ((= call-args nargs)
459            (convert-call ref call fun))
460           (t
461            ;; FIXME: ANSI requires in "3.2.5 Exceptional Situations in the
462            ;; Compiler" that calling a function with "the wrong number of
463            ;; arguments" be only a STYLE-ERROR. I think, though, that this
464            ;; should only apply when the number of arguments is inferred
465            ;; from a previous definition. If the number of arguments
466            ;; is DECLAIMed, surely calling with the wrong number is a
467            ;; real WARNING. As long as SBCL continues to use CMU CL's
468            ;; non-ANSI DEFUN-is-a-DECLAIM policy, we're in violation here,
469            ;; but as long as we continue to use that policy, that's the
470            ;; not our biggest problem.:-| When we fix that policy, this
471            ;; should come back into compliance. (So fix that policy!)
472            ;;   ..but..
473            ;; FIXME, continued: Except that section "3.2.2.3 Semantic
474            ;; Constraints" says that if it's within the same file, it's
475            ;; wrong. And we're in locall.lisp here, so it's probably
476            ;; (haven't checked this..) a call to something in the same
477            ;; file. So maybe it deserves a full warning anyway.
478            (compiler-warn
479             "function called with ~R argument~:P, but wants exactly ~R"
480             call-args nargs)
481            (setf (basic-combination-kind call) :error)))))
482 \f
483 ;;;; &OPTIONAL, &MORE and &KEYWORD calls
484
485 ;;; This is similar to CONVERT-LAMBDA-CALL, but deals with
486 ;;; OPTIONAL-DISPATCHes. If only fixed args are supplied, then convert
487 ;;; a call to the correct entry point. If &KEY args are supplied, then
488 ;;; dispatch to a subfunction. We don't convert calls to functions
489 ;;; that have a &MORE (or &REST) arg.
490 (defun convert-hairy-call (ref call fun)
491   (declare (type ref ref) (type combination call)
492            (type optional-dispatch fun))
493   (let ((min-args (optional-dispatch-min-args fun))
494         (max-args (optional-dispatch-max-args fun))
495         (call-args (length (combination-args call))))
496     (cond ((< call-args min-args)
497            ;; FIXME: See FIXME note at the previous
498            ;; wrong-number-of-arguments warnings in this file.
499            (compiler-warn
500             "function called with ~R argument~:P, but wants at least ~R"
501             call-args min-args)
502            (setf (basic-combination-kind call) :error))
503           ((<= call-args max-args)
504            (convert-call ref call
505                          (elt (optional-dispatch-entry-points fun)
506                               (- call-args min-args))))
507           ((optional-dispatch-more-entry fun)
508            (convert-more-call ref call fun))
509           (t
510            ;; FIXME: See FIXME note at the previous
511            ;; wrong-number-of-arguments warnings in this file.
512            (compiler-warn
513             "function called with ~R argument~:P, but wants at most ~R"
514             call-args max-args)
515            (setf (basic-combination-kind call) :error))))
516   (values))
517
518 ;;; This function is used to convert a call to an entry point when
519 ;;; complex transformations need to be done on the original arguments.
520 ;;; ENTRY is the entry point function that we are calling. VARS is a
521 ;;; list of variable names which are bound to the original call
522 ;;; arguments. IGNORES is the subset of VARS which are ignored. ARGS
523 ;;; is the list of arguments to the entry point function.
524 ;;;
525 ;;; In order to avoid gruesome graph grovelling, we introduce a new
526 ;;; function that rearranges the arguments and calls the entry point.
527 ;;; We analyze the new function and the entry point immediately so
528 ;;; that everything gets converted during the single pass.
529 (defun convert-hairy-fun-entry (ref call entry vars ignores args)
530   (declare (list vars ignores args) (type ref ref) (type combination call)
531            (type clambda entry))
532   (let ((new-fun
533          (with-ir1-environment-from-node call
534            (ir1-convert-lambda
535             `(lambda ,vars
536                (declare (ignorable ,@ignores))
537                (%funcall ,entry ,@args))
538             :debug-name (debug-namify "hairy function entry ~S"
539                                       (continuation-fun-name
540                                        (basic-combination-fun call)))))))
541     (convert-call ref call new-fun)
542     (dolist (ref (leaf-refs entry))
543       (convert-call-if-possible ref (continuation-dest (node-cont ref))))))
544
545 ;;; Use CONVERT-HAIRY-FUN-ENTRY to convert a &MORE-arg call to a known
546 ;;; function into a local call to the MAIN-ENTRY.
547 ;;;
548 ;;; First we verify that all keywords are constant and legal. If there
549 ;;; aren't, then we warn the user and don't attempt to convert the call.
550 ;;;
551 ;;; We massage the supplied &KEY arguments into the order expected
552 ;;; by the main entry. This is done by binding all the arguments to
553 ;;; the keyword call to variables in the introduced lambda, then
554 ;;; passing these values variables in the correct order when calling
555 ;;; the main entry. Unused arguments (such as the keywords themselves)
556 ;;; are discarded simply by not passing them along.
557 ;;;
558 ;;; If there is a &REST arg, then we bundle up the args and pass them
559 ;;; to LIST.
560 (defun convert-more-call (ref call fun)
561   (declare (type ref ref) (type combination call) (type optional-dispatch fun))
562   (let* ((max (optional-dispatch-max-args fun))
563          (arglist (optional-dispatch-arglist fun))
564          (args (combination-args call))
565          (more (nthcdr max args))
566          (flame (policy call (or (> speed inhibit-warnings)
567                                  (> space inhibit-warnings))))
568          (loser nil)
569          (allowp nil)
570          (allow-found nil)
571          (temps (make-gensym-list max))
572          (more-temps (make-gensym-list (length more))))
573     (collect ((ignores)
574               (supplied)
575               (key-vars))
576
577       (dolist (var arglist)
578         (let ((info (lambda-var-arg-info var)))
579           (when info
580             (ecase (arg-info-kind info)
581               (:keyword
582                (key-vars var))
583               ((:rest :optional))
584               ((:more-context :more-count)
585                (compiler-warn "can't local-call functions with &MORE args")
586                (setf (basic-combination-kind call) :error)
587                (return-from convert-more-call))))))
588
589       (when (optional-dispatch-keyp fun)
590         (when (oddp (length more))
591           (compiler-warn "function called with odd number of ~
592                           arguments in keyword portion")
593
594           (setf (basic-combination-kind call) :error)
595           (return-from convert-more-call))
596
597         (do ((key more (cddr key))
598              (temp more-temps (cddr temp)))
599             ((null key))
600           (let ((cont (first key)))
601             (unless (constant-continuation-p cont)
602               (when flame
603                 (compiler-note "non-constant keyword in keyword call"))
604               (setf (basic-combination-kind call) :error)
605               (return-from convert-more-call))
606
607             (let ((name (continuation-value cont))
608                   (dummy (first temp))
609                   (val (second temp)))
610               ;; FIXME: check whether KEY was supplied earlier
611               (when (and (eq name :allow-other-keys) (not allow-found))
612                 (let ((val (second key)))
613                   (cond ((constant-continuation-p val)
614                          (setq allow-found t
615                                allowp (continuation-value val)))
616                         (t (when flame
617                              (compiler-note "non-constant :ALLOW-OTHER-KEYS value"))
618                            (setf (basic-combination-kind call) :error)
619                            (return-from convert-more-call)))))
620               (dolist (var (key-vars)
621                            (progn
622                              (ignores dummy val)
623                              (unless (eq name :allow-other-keys)
624                                (setq loser name))))
625                 (let ((info (lambda-var-arg-info var)))
626                   (when (eq (arg-info-key info) name)
627                     (ignores dummy)
628                     (supplied (cons var val))
629                     (return)))))))
630
631         (when (and loser (not (optional-dispatch-allowp fun)) (not allowp))
632           (compiler-warn "function called with unknown argument keyword ~S"
633                          loser)
634           (setf (basic-combination-kind call) :error)
635           (return-from convert-more-call)))
636
637       (collect ((call-args))
638         (do ((var arglist (cdr var))
639              (temp temps (cdr temp)))
640             (())
641           (let ((info (lambda-var-arg-info (car var))))
642             (if info
643                 (ecase (arg-info-kind info)
644                   (:optional
645                    (call-args (car temp))
646                    (when (arg-info-supplied-p info)
647                      (call-args t)))
648                   (:rest
649                    (call-args `(list ,@more-temps))
650                    (return))
651                   (:keyword
652                    (return)))
653                 (call-args (car temp)))))
654
655         (dolist (var (key-vars))
656           (let ((info (lambda-var-arg-info var))
657                 (temp (cdr (assoc var (supplied)))))
658             (if temp
659                 (call-args temp)
660                 (call-args (arg-info-default info)))
661             (when (arg-info-supplied-p info)
662               (call-args (not (null temp))))))
663
664         (convert-hairy-fun-entry ref call (optional-dispatch-main-entry fun)
665                                  (append temps more-temps)
666                                  (ignores) (call-args)))))
667
668   (values))
669 \f
670 ;;;; LET conversion
671 ;;;;
672 ;;;; Converting to a LET has differing significance to various parts
673 ;;;; of the compiler:
674 ;;;; -- The body of a LET is spliced in immediately after the
675 ;;;;    corresponding combination node, making the control transfer
676 ;;;;    explicit and allowing LETs to be mashed together into a single
677 ;;;;    block. The value of the LET is delivered directly to the
678 ;;;;    original continuation for the call, eliminating the need to
679 ;;;;    propagate information from the dummy result continuation.
680 ;;;; -- As far as IR1 optimization is concerned, it is interesting in
681 ;;;;    that there is only one expression that the variable can be bound
682 ;;;;    to, and this is easily substituted for.
683 ;;;; -- LETs are interesting to environment analysis and to the back
684 ;;;;    end because in most ways a LET can be considered to be "the
685 ;;;;    same function" as its home function.
686 ;;;; -- LET conversion has dynamic scope implications, since control
687 ;;;;    transfers within the same environment are local. In a local
688 ;;;;    control transfer, cleanup code must be emitted to remove
689 ;;;;    dynamic bindings that are no longer in effect.
690
691 ;;; Set up the control transfer to the called CLAMBDA. We split the
692 ;;; call block immediately after the call, and link the head of
693 ;;; CLAMBDA to the call block. The successor block after splitting
694 ;;; (where we return to) is returned.
695 ;;;
696 ;;; If the lambda is is a different component than the call, then we
697 ;;; call JOIN-COMPONENTS. This only happens in block compilation
698 ;;; before FIND-INITIAL-DFO.
699 (defun insert-let-body (clambda call)
700   (declare (type clambda clambda) (type basic-combination call))
701   (let* ((call-block (node-block call))
702          (bind-block (node-block (lambda-bind clambda)))
703          (component (block-component call-block)))
704     (aver-live-component component)
705     (let ((clambda-component (block-component bind-block)))
706       (unless (eq clambda-component component)
707         (aver (eq (component-kind component) :initial))
708         (join-components component clambda-component)))
709     (let ((*current-component* component))
710       (node-ends-block call))
711     ;; FIXME: Use DESTRUCTURING-BIND here, and grep for other 
712     ;; uses of '=.*length' which could also be converted to use
713     ;; DESTRUCTURING-BIND or PROPER-LIST-OF-LENGTH-P.
714     (aver (= (length (block-succ call-block)) 1))
715     (let ((next-block (first (block-succ call-block))))
716       (unlink-blocks call-block next-block)
717       (link-blocks call-block bind-block)
718       next-block)))
719
720 ;;; Remove CLAMBDA from the tail set of anything it used to be in the
721 ;;; same set as; but leave CLAMBDA with a valid tail set value of
722 ;;; its own, for the benefit of code which might try to pull
723 ;;; something out of it (e.g. return type).
724 (defun depart-from-tail-set (clambda)
725   ;; Until sbcl-0.pre7.37.flaky5.2, we did
726   ;;   (LET ((TAILS (LAMBDA-TAIL-SET CLAMBDA)))
727   ;;     (SETF (TAIL-SET-FUNS TAILS)
728   ;;           (DELETE CLAMBDA (TAIL-SET-FUNS TAILS))))
729   ;;   (SETF (LAMBDA-TAIL-SET CLAMBDA) NIL)
730   ;; here. Apparently the idea behind the (SETF .. NIL) was that since
731   ;; TAIL-SET-FUNS no longer thinks we're in the tail set, it's
732   ;; inconsistent, and perhaps unsafe, for us to think we're in the
733   ;; tail set. Unfortunately..
734   ;;
735   ;; The (SETF .. NIL) caused problems in sbcl-0.pre7.37.flaky5.2 when
736   ;; I was trying to get Python to emit :EXTERNAL LAMBDAs directly
737   ;; (instead of only being able to emit funny little :TOPLEVEL stubs
738   ;; which you called in order to get the address of an external LAMBDA):
739   ;; the external function was defined in terms of internal function,
740   ;; which was LET-converted, and then things blew up downstream when
741   ;; FINALIZE-XEP-DEFINITION tried to find out its DEFINED-TYPE from
742   ;; the now-NILed-out TAIL-SET. So..
743   ;;
744   ;; To deal with this problem, we no longer NIL out 
745   ;; (LAMBDA-TAIL-SET CLAMBDA) here. Instead:
746   ;;   * If we're the only function in TAIL-SET-FUNS, it should
747   ;;     be safe to leave ourself linked to it, and it to you.
748   ;;   * If there are other functions in TAIL-SET-FUNS, then we're
749   ;;     afraid of future optimizations on those functions causing
750   ;;     the TAIL-SET object no longer to be valid to describe our
751   ;;     return value. Thus, we delete ourselves from that object;
752   ;;     but we save a newly-allocated tail-set, derived from the old
753   ;;     one, for ourselves, for the use of later code (e.g.
754   ;;     FINALIZE-XEP-DEFINITION) which might want to
755   ;;     know about our return type.
756   (let* ((old-tail-set (lambda-tail-set clambda))
757          (old-tail-set-funs (tail-set-funs old-tail-set)))
758     (unless (= 1 (length old-tail-set-funs))
759       (setf (tail-set-funs old-tail-set)
760             (delete clambda old-tail-set-funs))
761       (let ((new-tail-set (copy-tail-set old-tail-set)))
762         (setf (lambda-tail-set clambda) new-tail-set
763               (tail-set-funs new-tail-set) (list clambda)))))
764   ;; The documentation on TAIL-SET-INFO doesn't tell whether it could
765   ;; remain valid in this case, so we nuke it on the theory that
766   ;; missing information tends to be less dangerous than incorrect
767   ;; information.
768   (setf (tail-set-info (lambda-tail-set clambda)) nil))
769
770 ;;; Handle the PHYSENV semantics of LET conversion. We add CLAMBDA and
771 ;;; its LETs to LETs for the CALL's home function. We merge the calls
772 ;;; for CLAMBDA with the calls for the home function, removing CLAMBDA
773 ;;; in the process. We also merge the ENTRIES.
774 ;;;
775 ;;; We also unlink the function head from the component head and set
776 ;;; COMPONENT-REANALYZE to true to indicate that the DFO should be
777 ;;; recomputed.
778 (defun merge-lets (clambda call)
779
780   (declare (type clambda clambda) (type basic-combination call))
781
782   (let ((component (node-component call)))
783     (unlink-blocks (component-head component) (lambda-block clambda))
784     (setf (component-lambdas component)
785           (delete clambda (component-lambdas component)))
786     (setf (component-reanalyze component) t))
787   (setf (lambda-call-lexenv clambda) (node-lexenv call))
788
789   (depart-from-tail-set clambda)
790
791   (let* ((home (node-home-lambda call))
792          (home-physenv (lambda-physenv home)))
793
794     (aver (not (eq home clambda)))
795
796     ;; CLAMBDA belongs to HOME now.
797     (push clambda (lambda-lets home))
798     (setf (lambda-home clambda) home)
799     (setf (lambda-physenv clambda) home-physenv)
800
801     ;; All of CLAMBDA's LETs belong to HOME now.
802     (let ((lets (lambda-lets clambda)))
803       (dolist (let lets)
804         (setf (lambda-home let) home)
805         (setf (lambda-physenv let) home-physenv))
806       (setf (lambda-lets home) (nconc lets (lambda-lets home))))
807     ;; CLAMBDA no longer has an independent existence as an entity
808     ;; which has LETs.
809     (setf (lambda-lets clambda) nil)
810
811     ;; HOME no longer calls CLAMBDA, and owns all of CLAMBDA's old
812     ;; DFO dependencies.
813     (setf (lambda-calls-or-closes home)
814           (delete clambda
815                   (nunion (lambda-calls-or-closes clambda)
816                           (lambda-calls-or-closes home))))
817     ;; CLAMBDA no longer has an independent existence as an entity
818     ;; which calls things or has DFO dependencies.
819     (setf (lambda-calls-or-closes clambda) nil)
820
821     ;; All of CLAMBDA's ENTRIES belong to HOME now.
822     (setf (lambda-entries home)
823           (nconc (lambda-entries clambda)
824                  (lambda-entries home)))
825     ;; CLAMBDA no longer has an independent existence as an entity
826     ;; with ENTRIES.
827     (setf (lambda-entries clambda) nil))
828
829   (values))
830
831 ;;; Handle the value semantics of LET conversion. Delete FUN's return
832 ;;; node, and change the control flow to transfer to NEXT-BLOCK
833 ;;; instead. Move all the uses of the result continuation to CALL's
834 ;;; CONT.
835 ;;;
836 ;;; If the actual continuation is only used by the LET call, then we
837 ;;; intersect the type assertion on the dummy continuation with the
838 ;;; assertion for the actual continuation; in all other cases
839 ;;; assertions on the dummy continuation are lost.
840 ;;;
841 ;;; We also intersect the derived type of the CALL with the derived
842 ;;; type of all the dummy continuation's uses. This serves mainly to
843 ;;; propagate TRULY-THE through LETs.
844 (defun move-return-uses (fun call next-block)
845   (declare (type clambda fun) (type basic-combination call)
846            (type cblock next-block))
847   (let* ((return (lambda-return fun))
848          (return-block (node-block return)))
849     (unlink-blocks return-block
850                    (component-tail (block-component return-block)))
851     (link-blocks return-block next-block)
852     (unlink-node return)
853     (delete-return return)
854     (let ((result (return-result return))
855           (cont (node-cont call))
856           (call-type (node-derived-type call)))
857       (when (eq (continuation-use cont) call)
858         (set-continuation-type-assertion
859          cont
860          (continuation-asserted-type result)
861          (continuation-type-to-check result)))
862       (unless (eq call-type *wild-type*)
863         (do-uses (use result)
864           (derive-node-type use call-type)))
865       (substitute-continuation-uses cont result)))
866   (values))
867
868 ;;; Change all CONT for all the calls to FUN to be the start
869 ;;; continuation for the bind node. This allows the blocks to be
870 ;;; joined if the caller count ever goes to one.
871 (defun move-let-call-cont (fun)
872   (declare (type clambda fun))
873   (let ((new-cont (node-prev (lambda-bind fun))))
874     (dolist (ref (leaf-refs fun))
875       (let ((dest (continuation-dest (node-cont ref))))
876         (delete-continuation-use dest)
877         (add-continuation-use dest new-cont))))
878   (values))
879
880 ;;; We are converting FUN to be a LET when the call is in a non-tail
881 ;;; position. Any previously tail calls in FUN are no longer tail
882 ;;; calls, and must be restored to normal calls which transfer to
883 ;;; NEXT-BLOCK (FUN's return point.) We can't do this by DO-USES on
884 ;;; the RETURN-RESULT, because the return might have been deleted (if
885 ;;; all calls were TR.)
886 (defun unconvert-tail-calls (fun call next-block)
887   (dolist (called (lambda-calls-or-closes fun))
888     (when (lambda-p called)
889       (dolist (ref (leaf-refs called))
890         (let ((this-call (continuation-dest (node-cont ref))))
891           (when (and this-call
892                      (node-tail-p this-call)
893                      (eq (node-home-lambda this-call) fun))
894             (setf (node-tail-p this-call) nil)
895             (ecase (functional-kind called)
896               ((nil :cleanup :optional)
897                (let ((block (node-block this-call))
898                      (cont (node-cont call)))
899                  (ensure-block-start cont)
900                  (unlink-blocks block (first (block-succ block)))
901                  (link-blocks block next-block)
902                  (delete-continuation-use this-call)
903                  (add-continuation-use this-call cont)))
904               (:deleted)
905               ;; The called function might be an assignment in the
906               ;; case where we are currently converting that function.
907               ;; In steady-state, assignments never appear as a called
908               ;; function.
909               (:assignment
910                (aver (eq called fun)))))))))
911   (values))
912
913 ;;; Deal with returning from a LET or assignment that we are
914 ;;; converting. FUN is the function we are calling, CALL is a call to
915 ;;; FUN, and NEXT-BLOCK is the return point for a non-tail call, or
916 ;;; NULL if call is a tail call.
917 ;;;
918 ;;; If the call is not a tail call, then we must do
919 ;;; UNCONVERT-TAIL-CALLS, since a tail call is a call which returns
920 ;;; its value out of the enclosing non-let function. When call is
921 ;;; non-TR, we must convert it back to an ordinary local call, since
922 ;;; the value must be delivered to the receiver of CALL's value.
923 ;;;
924 ;;; We do different things depending on whether the caller and callee
925 ;;; have returns left:
926
927 ;;; -- If the callee has no return we just do MOVE-LET-CALL-CONT.
928 ;;;    Either the function doesn't return, or all returns are via
929 ;;;    tail-recursive local calls.
930 ;;; -- If CALL is a non-tail call, or if both have returns, then
931 ;;;    we delete the callee's return, move its uses to the call's
932 ;;;    result continuation, and transfer control to the appropriate
933 ;;;    return point.
934 ;;; -- If the callee has a return, but the caller doesn't, then we
935 ;;;    move the return to the caller.
936 (defun move-return-stuff (fun call next-block)
937   (declare (type clambda fun) (type basic-combination call)
938            (type (or cblock null) next-block))
939   (when next-block
940     (unconvert-tail-calls fun call next-block))
941   (let* ((return (lambda-return fun))
942          (call-fun (node-home-lambda call))
943          (call-return (lambda-return call-fun)))
944     (cond ((not return))
945           ((or next-block call-return)
946            (unless (block-delete-p (node-block return))
947              (when (and (node-tail-p call)
948                         call-return
949                         (not (eq (node-cont call)
950                                  (return-result call-return))))
951                ;; We do not care to give a meaningful continuation to
952                ;; a tail combination, but here we need it.
953                (delete-continuation-use call)
954                (add-continuation-use call (return-result call-return)))
955              (move-return-uses fun call
956                                (or next-block (node-block call-return)))))
957           (t
958            (aver (node-tail-p call))
959            (setf (lambda-return call-fun) return)
960            (setf (return-lambda return) call-fun)
961            (setf (lambda-return fun) nil))))
962   (move-let-call-cont fun)
963   (values))
964
965 ;;; Actually do LET conversion. We call subfunctions to do most of the
966 ;;; work. We change the CALL's CONT to be the continuation heading the
967 ;;; BIND block, and also do REOPTIMIZE-CONTINUATION on the args and
968 ;;; CONT so that LET-specific IR1 optimizations get a chance. We blow
969 ;;; away any entry for the function in *FREE-FUNS* so that nobody
970 ;;; will create new references to it.
971 (defun let-convert (fun call)
972   (declare (type clambda fun) (type basic-combination call))
973   (let ((next-block (if (node-tail-p call)
974                         nil
975                         (insert-let-body fun call))))
976     (move-return-stuff fun call next-block)
977     (merge-lets fun call)))
978
979 ;;; Reoptimize all of CALL's args and its result.
980 (defun reoptimize-call (call)
981   (declare (type basic-combination call))
982   (dolist (arg (basic-combination-args call))
983     (when arg
984       (reoptimize-continuation arg)))
985   (reoptimize-continuation (node-cont call))
986   (values))
987
988 ;;; Are there any declarations in force to say CLAMBDA shouldn't be
989 ;;; LET converted?
990 (defun declarations-suppress-let-conversion-p (clambda)
991   ;; From the user's point of view, LET-converting something that
992   ;; has a name is inlining it. (The user can't see what we're doing
993   ;; with anonymous things, and suppressing inlining
994   ;; for such things can easily give Python acute indigestion, so
995   ;; we don't.)
996   (when (leaf-has-source-name-p clambda)
997     ;; ANSI requires that explicit NOTINLINE be respected.
998     (or (eq (lambda-inlinep clambda) :notinline)
999         ;; If (= LET-CONVERTION 0) we can guess that inlining
1000         ;; generally won't be appreciated, but if the user
1001         ;; specifically requests inlining, that takes precedence over
1002         ;; our general guess.
1003         (and (policy clambda (= let-convertion 0))
1004              (not (eq (lambda-inlinep clambda) :inline))))))
1005
1006 ;;; We also don't convert calls to named functions which appear in the
1007 ;;; initial component, delaying this until optimization. This
1008 ;;; minimizes the likelihood that we will LET-convert a function which
1009 ;;; may have references added due to later local inline expansion.
1010 (defun ok-initial-convert-p (fun)
1011   (not (and (leaf-has-source-name-p fun)
1012             (or (declarations-suppress-let-conversion-p fun)
1013                 (eq (component-kind (lambda-component fun))
1014                     :initial)))))
1015
1016 ;;; This function is called when there is some reason to believe that
1017 ;;; CLAMBDA might be converted into a LET. This is done after local
1018 ;;; call analysis, and also when a reference is deleted. We return
1019 ;;; true if we converted.
1020 (defun maybe-let-convert (clambda)
1021   (declare (type clambda clambda))
1022   (unless (declarations-suppress-let-conversion-p clambda)
1023     ;; We only convert to a LET when the function is a normal local
1024     ;; function, has no XEP, and is referenced in exactly one local
1025     ;; call. Conversion is also inhibited if the only reference is in
1026     ;; a block about to be deleted.
1027     ;;
1028     ;; These rules limiting LET conversion may seem unnecessarily
1029     ;; restrictive, since there are some cases where we could do the
1030     ;; return with a jump that don't satisfy these requirements. The
1031     ;; reason for doing things this way is that it makes the concept
1032     ;; of a LET much more useful at the level of IR1 semantics. The
1033     ;; :ASSIGNMENT function kind provides another way to optimize
1034     ;; calls to single-return/multiple call functions.
1035     ;;
1036     ;; We don't attempt to convert calls to functions that have an
1037     ;; XEP, since we might be embarrassed later when we want to
1038     ;; convert a newly discovered local call. Also, see
1039     ;; OK-INITIAL-CONVERT-P.
1040     (let ((refs (leaf-refs clambda)))
1041       (when (and refs
1042                  (null (rest refs))
1043                  (member (functional-kind clambda) '(nil :assignment))
1044                  (not (functional-entry-fun clambda)))
1045         (let* ((ref (first refs))
1046                (ref-cont (node-cont ref))
1047                (dest (continuation-dest ref-cont)))
1048           (when (and dest
1049                      (basic-combination-p dest)
1050                      (eq (basic-combination-fun dest) ref-cont)
1051                      (eq (basic-combination-kind dest) :local)
1052                      (not (block-delete-p (node-block dest)))
1053                      (cond ((ok-initial-convert-p clambda) t)
1054                            (t
1055                             (reoptimize-continuation ref-cont)
1056                             nil)))
1057             (when (eq clambda (node-home-lambda dest))
1058               (delete-lambda clambda)
1059               (return-from maybe-let-convert nil))
1060             (unless (eq (functional-kind clambda) :assignment)
1061               (let-convert clambda dest))
1062             (reoptimize-call dest)
1063             (setf (functional-kind clambda)
1064                   (if (mv-combination-p dest) :mv-let :let))))
1065         t))))
1066 \f
1067 ;;;; tail local calls and assignments
1068
1069 ;;; Return T if there are no cleanups between BLOCK1 and BLOCK2, or if
1070 ;;; they definitely won't generate any cleanup code. Currently we
1071 ;;; recognize lexical entry points that are only used locally (if at
1072 ;;; all).
1073 (defun only-harmless-cleanups (block1 block2)
1074   (declare (type cblock block1 block2))
1075   (or (eq block1 block2)
1076       (let ((cleanup2 (block-start-cleanup block2)))
1077         (do ((cleanup (block-end-cleanup block1)
1078                       (node-enclosing-cleanup (cleanup-mess-up cleanup))))
1079             ((eq cleanup cleanup2) t)
1080           (case (cleanup-kind cleanup)
1081             ((:block :tagbody)
1082              (unless (null (entry-exits (cleanup-mess-up cleanup)))
1083                (return nil)))
1084             (t (return nil)))))))
1085
1086 ;;; If a potentially TR local call really is TR, then convert it to
1087 ;;; jump directly to the called function. We also call
1088 ;;; MAYBE-CONVERT-TO-ASSIGNMENT. The first value is true if we
1089 ;;; tail-convert. The second is the value of M-C-T-A. We can switch
1090 ;;; the succesor (potentially deleting the RETURN node) unless:
1091 ;;; -- The call has already been converted.
1092 ;;; -- The call isn't TR (some implicit MV PROG1.)
1093 ;;; -- The call is in an XEP (thus we might decide to make it non-tail 
1094 ;;;    so that we can use known return inside the component.)
1095 ;;; -- There is a change in the cleanup between the call in the return, 
1096 ;;;    so we might need to introduce cleanup code.
1097 (defun maybe-convert-tail-local-call (call)
1098   (declare (type combination call))
1099   (let ((return (continuation-dest (node-cont call))))
1100     (aver (return-p return))
1101     (when (and (not (node-tail-p call))
1102                (immediately-used-p (return-result return) call)
1103                (not (eq (functional-kind (node-home-lambda call))
1104                         :external))
1105                (only-harmless-cleanups (node-block call)
1106                                        (node-block return)))
1107       (node-ends-block call)
1108       (let ((block (node-block call))
1109             (fun (combination-lambda call)))
1110         (setf (node-tail-p call) t)
1111         (unlink-blocks block (first (block-succ block)))
1112         (link-blocks block (lambda-block fun))
1113         (values t (maybe-convert-to-assignment fun))))))
1114
1115 ;;; This is called when we believe it might make sense to convert
1116 ;;; CLAMBDA to an assignment. All this function really does is
1117 ;;; determine when a function with more than one call can still be
1118 ;;; combined with the calling function's environment. We can convert
1119 ;;; when:
1120 ;;; -- The function is a normal, non-entry function, and
1121 ;;; -- Except for one call, all calls must be tail recursive calls 
1122 ;;;    in the called function (i.e. are self-recursive tail calls)
1123 ;;; -- OK-INITIAL-CONVERT-P is true.
1124 ;;;
1125 ;;; There may be one outside call, and it need not be tail-recursive.
1126 ;;; Since all tail local calls have already been converted to direct
1127 ;;; transfers, the only control semantics needed are to splice in the
1128 ;;; body at the non-tail call. If there is no non-tail call, then we
1129 ;;; need only merge the environments. Both cases are handled by
1130 ;;; LET-CONVERT.
1131 ;;;
1132 ;;; ### It would actually be possible to allow any number of outside
1133 ;;; calls as long as they all return to the same place (i.e. have the
1134 ;;; same conceptual continuation.) A special case of this would be
1135 ;;; when all of the outside calls are tail recursive.
1136 (defun maybe-convert-to-assignment (clambda)
1137   (declare (type clambda clambda))
1138   (when (and (not (functional-kind clambda))
1139              (not (functional-entry-fun clambda)))
1140     (let ((outside-non-tail-call nil)
1141           (outside-call nil))
1142       (when (and (dolist (ref (leaf-refs clambda) t)
1143                    (let ((dest (continuation-dest (node-cont ref))))
1144                      (when (or (not dest)
1145                                (block-delete-p (node-block dest)))
1146                        (return nil))
1147                      (let ((home (node-home-lambda ref)))
1148                        (unless (eq home clambda)
1149                          (when outside-call
1150                            (return nil))
1151                          (setq outside-call dest))
1152                        (unless (node-tail-p dest)
1153                          (when (or outside-non-tail-call (eq home clambda))
1154                            (return nil))
1155                          (setq outside-non-tail-call dest)))))
1156                  (ok-initial-convert-p clambda))
1157         (cond (outside-call (setf (functional-kind clambda) :assignment)
1158                             (let-convert clambda outside-call)
1159                             (when outside-non-tail-call
1160                               (reoptimize-call outside-non-tail-call))
1161                             t)
1162               (t (delete-lambda clambda)
1163                  nil))))))