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