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