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