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