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