primarily intending to integrate Colin Walter's O(N) map code and
[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 (file-comment
25   "$Header$")
26
27 ;;; This function propagates information from the variables in the function
28 ;;; Fun to the actual arguments in Call. This is also called by the VALUES IR1
29 ;;; optimizer when it sleazily converts MV-BINDs to LETs.
30 ;;;
31 ;;; We flush all arguments to Call that correspond to unreferenced variables
32 ;;; in Fun. We leave NILs in the Combination-Args so that the remaining args
33 ;;; still match up with their vars.
34 ;;;
35 ;;; We also apply the declared variable type assertion to the argument
36 ;;; continuations.
37 (defun propagate-to-args (call fun)
38   (declare (type combination call) (type clambda fun))
39   (do ((args (basic-combination-args call) (cdr args))
40        (vars (lambda-vars fun) (cdr vars)))
41       ((null args))
42     (let ((arg (car args))
43           (var (car vars)))
44       (cond ((leaf-refs var)
45              (assert-continuation-type arg (leaf-type var)))
46             (t
47              (flush-dest arg)
48              (setf (car args) nil)))))
49
50   (values))
51
52 ;;; This function handles merging the tail sets if Call is potentially
53 ;;; tail-recursive, and is a call to a function with a different TAIL-SET than
54 ;;; Call's Fun. This must be called whenever we alter IR1 so as to place a
55 ;;; local call in what might be a TR context. Note that any call which returns
56 ;;; its value to a RETURN is considered potentially TR, since any implicit
57 ;;; MV-PROG1 might be optimized away.
58 ;;;
59 ;;; We destructively modify the set for the calling function to represent both,
60 ;;; and then change all the functions in callee's set to reference the first.
61 ;;; If we do merge, we reoptimize the RETURN-RESULT continuation to cause
62 ;;; IR1-OPTIMIZE-RETURN to recompute the tail set type.
63 (defun merge-tail-sets (call &optional (new-fun (combination-lambda call)))
64   (declare (type basic-combination call) (type clambda new-fun))
65   (let ((return (continuation-dest (node-cont call))))
66     (when (return-p return)
67       (let ((call-set (lambda-tail-set (node-home-lambda call)))
68             (fun-set (lambda-tail-set new-fun)))
69         (unless (eq call-set fun-set)
70           (let ((funs (tail-set-functions fun-set)))
71             (dolist (fun funs)
72               (setf (lambda-tail-set fun) call-set))
73             (setf (tail-set-functions call-set)
74                   (nconc (tail-set-functions call-set) funs)))
75           (reoptimize-continuation (return-result return))
76           t)))))
77
78 ;;; Convert a combination into a local call. We PROPAGATE-TO-ARGS, set
79 ;;; the combination kind to :LOCAL, add FUN to the CALLS of the
80 ;;; function that the call is in, call MERGE-TAIL-SETS, then replace
81 ;;; the function in the REF node with the new function.
82 ;;;
83 ;;; We change the REF last, since changing the reference can trigger
84 ;;; LET conversion of the new function, but will only do so if the
85 ;;; call is local. Note that the replacement may trigger LET
86 ;;; conversion or other changes in IR1. We must call MERGE-TAIL-SETS
87 ;;; with NEW-FUN before the substitution, since after the substitution
88 ;;; (and LET conversion), the call may no longer be recognizable as
89 ;;; tail-recursive.
90 (defun convert-call (ref call fun)
91   (declare (type ref ref) (type combination call) (type clambda fun))
92   (propagate-to-args call fun)
93   (setf (basic-combination-kind call) :local)
94   (pushnew fun (lambda-calls (node-home-lambda call)))
95   (merge-tail-sets call fun)
96   (change-ref-leaf ref fun)
97   (values))
98 \f
99 ;;;; external entry point creation
100
101 ;;; Return a Lambda form that can be used as the definition of the XEP for Fun.
102 ;;;
103 ;;; If Fun is a lambda, then we check the number of arguments (conditional
104 ;;; on policy) and call Fun with all the arguments.
105 ;;;
106 ;;; If Fun is an Optional-Dispatch, then we dispatch off of the number of
107 ;;; supplied arguments by doing do an = test for each entry-point, calling the
108 ;;; entry with the appropriate prefix of the passed arguments.
109 ;;;
110 ;;; If there is a more arg, then there are a couple of optimizations that we
111 ;;; make (more for space than anything else):
112 ;;; -- If Min-Args is 0, then we make the more entry a T clause, since no
113 ;;;    argument count error is possible.
114 ;;; -- We can omit the = clause for the last entry-point, allowing the case of
115 ;;;    0 more args to fall through to the more entry.
116 ;;;
117 ;;; We don't bother to policy conditionalize wrong arg errors in optional
118 ;;; dispatches, since the additional overhead is negligible compared to the
119 ;;; other hair going down.
120 ;;;
121 ;;; Note that if policy indicates it, argument type declarations in Fun will
122 ;;; be verified. Since nothing is known about the type of the XEP arg vars,
123 ;;; type checks will be emitted when the XEP's arg vars are passed to the
124 ;;; actual function.
125 (defun make-xep-lambda (fun)
126   (declare (type functional fun))
127   (etypecase fun
128     (clambda
129      (let ((nargs (length (lambda-vars fun)))
130            (n-supplied (gensym))
131            (temps (make-gensym-list (length (lambda-vars fun)))))
132        `(lambda (,n-supplied ,@temps)
133           (declare (type index ,n-supplied))
134           ,(if (policy nil (zerop safety))
135                `(declare (ignore ,n-supplied))
136                `(%verify-argument-count ,n-supplied ,nargs))
137           (%funcall ,fun ,@temps))))
138     (optional-dispatch
139      (let* ((min (optional-dispatch-min-args fun))
140             (max (optional-dispatch-max-args fun))
141             (more (optional-dispatch-more-entry fun))
142             (n-supplied (gensym))
143             (temps (make-gensym-list max)))
144        (collect ((entries))
145          (do ((eps (optional-dispatch-entry-points fun) (rest eps))
146               (n min (1+ n)))
147              ((null eps))
148            (entries `((= ,n-supplied ,n)
149                       (%funcall ,(first eps) ,@(subseq temps 0 n)))))
150          `(lambda (,n-supplied ,@temps)
151             ;; FIXME: Make sure that INDEX type distinguishes between target
152             ;; and host. (Probably just make the SB!XC:DEFTYPE different from
153             ;; CL:DEFTYPE.)
154             (declare (type index ,n-supplied))
155             (cond
156              ,@(if more (butlast (entries)) (entries))
157              ,@(when more
158                  `((,(if (zerop min) 't `(>= ,n-supplied ,max))
159                     ,(let ((n-context (gensym))
160                            (n-count (gensym)))
161                        `(multiple-value-bind (,n-context ,n-count)
162                             (%more-arg-context ,n-supplied ,max)
163                           (%funcall ,more ,@temps ,n-context ,n-count))))))
164              (t
165               (%argument-count-error ,n-supplied)))))))))
166
167 ;;; Make an external entry point (XEP) for Fun and return it. We
168 ;;; convert the result of Make-XEP-Lambda in the correct environment,
169 ;;; then associate this lambda with Fun as its XEP. After the
170 ;;; conversion, we iterate over the function's associated lambdas,
171 ;;; redoing local call analysis so that the XEP calls will get
172 ;;; converted. We also bind *LEXENV* to change the compilation policy
173 ;;; over to the interface policy.
174 ;;;
175 ;;; We set Reanalyze and Reoptimize in the component, just in case we
176 ;;; discover an XEP after the initial local call analyze pass.
177 (defun make-external-entry-point (fun)
178   (declare (type functional fun))
179   (assert (not (functional-entry-function fun)))
180   (with-ir1-environment (lambda-bind (main-entry fun))
181     (let* ((*lexenv* (make-lexenv :cookie (make-interface-cookie *lexenv*)))
182            (res (ir1-convert-lambda (make-xep-lambda fun))))
183       (setf (functional-kind res) :external)
184       (setf (leaf-ever-used res) t)
185       (setf (functional-entry-function res) fun)
186       (setf (functional-entry-function fun) res)
187       (setf (component-reanalyze *current-component*) t)
188       (setf (component-reoptimize *current-component*) t)
189       (etypecase fun
190         (clambda (local-call-analyze-1 fun))
191         (optional-dispatch
192          (dolist (ep (optional-dispatch-entry-points fun))
193            (local-call-analyze-1 ep))
194          (when (optional-dispatch-more-entry fun)
195            (local-call-analyze-1 (optional-dispatch-more-entry fun)))))
196       res)))
197
198 ;;; Notice a Ref that is not in a local-call context. If the Ref is
199 ;;; already to an XEP, then do nothing, otherwise change it to the
200 ;;; XEP, making an XEP if necessary.
201 ;;;
202 ;;; If Ref is to a special :Cleanup or :Escape function, then we treat
203 ;;; it as though it was not an XEP reference (i.e. leave it alone.)
204 (defun reference-entry-point (ref)
205   (declare (type ref ref))
206   (let ((fun (ref-leaf ref)))
207     (unless (or (external-entry-point-p fun)
208                 (member (functional-kind fun) '(:escape :cleanup)))
209       (change-ref-leaf ref (or (functional-entry-function fun)
210                                (make-external-entry-point fun))))))
211 \f
212 ;;; Attempt to convert all references to Fun to local calls. The
213 ;;; reference must be the function for a call, and the function
214 ;;; continuation must be used only once, since otherwise we cannot be
215 ;;; sure what function is to be called. The call continuation would be
216 ;;; multiply used if there is hairy stuff such as conditionals in the
217 ;;; expression that computes the function.
218 ;;;
219 ;;; If we cannot convert a reference, then we mark the referenced
220 ;;; function as an entry-point, creating a new XEP if necessary. We
221 ;;; don't try to convert calls that are in error (:ERROR kind.)
222 ;;;
223 ;;; This is broken off from Local-Call-Analyze so that people can
224 ;;; force analysis of newly introduced calls. Note that we don't do
225 ;;; LET conversion here.
226 (defun local-call-analyze-1 (fun)
227   (declare (type functional fun))
228   (let ((refs (leaf-refs fun))
229         (first-time t))
230     (dolist (ref refs)
231       (let* ((cont (node-cont ref))
232              (dest (continuation-dest cont)))
233         (cond ((and (basic-combination-p dest)
234                     (eq (basic-combination-fun dest) cont)
235                     (eq (continuation-use cont) ref))
236
237                (convert-call-if-possible ref dest)
238
239                (unless (eq (basic-combination-kind dest) :local)
240                  (reference-entry-point ref)))
241               (t
242                (reference-entry-point ref))))
243       (setq first-time nil)))
244
245   (values))
246
247 ;;; We examine all New-Functions in component, attempting to convert
248 ;;; calls into local calls when it is legal. We also attempt to
249 ;;; convert each lambda to a LET. LET conversion is also triggered by
250 ;;; deletion of a function reference, but functions that start out
251 ;;; eligible for conversion must be noticed sometime.
252 ;;;
253 ;;; Note that there is a lot of action going on behind the scenes
254 ;;; here, triggered by reference deletion. In particular, the
255 ;;; COMPONENT-LAMBDAS are being hacked to remove newly deleted and let
256 ;;; converted lambdas, so it is important that the lambda is added to
257 ;;; the COMPONENT-LAMBDAS when it is. Also, the
258 ;;; COMPONENT-NEW-FUNCTIONS may contain all sorts of drivel, since it
259 ;;; is not updated when we delete functions, etc. Only
260 ;;; COMPONENT-LAMBDAS is updated.
261 ;;;
262 ;;; COMPONENT-REANALYZE-FUNCTIONS is treated similarly to
263 ;;; NEW-FUNCTIONS, but we don't add lambdas to the LAMBDAS.
264 (defun local-call-analyze (component)
265   (declare (type component component))
266   (loop
267     (let* ((new (pop (component-new-functions component)))
268            (fun (or new (pop (component-reanalyze-functions component)))))
269       (unless fun (return))
270       (let ((kind (functional-kind fun)))
271         (cond ((member kind '(:deleted :let :mv-let :assignment)))
272               ((and (null (leaf-refs fun)) (eq kind nil)
273                     (not (functional-entry-function fun)))
274                (delete-functional fun))
275               (t
276                (when (and new (lambda-p fun))
277                  (push fun (component-lambdas component)))
278                (local-call-analyze-1 fun)
279                (when (lambda-p fun)
280                  (maybe-let-convert fun)))))))
281
282   (values))
283
284 ;;; If policy is auspicious, Call is not in an XEP, and we don't seem
285 ;;; to be in an infinite recursive loop, then change the reference to
286 ;;; reference a fresh copy. We return whichever function we decide to
287 ;;; reference.
288 (defun maybe-expand-local-inline (fun ref call)
289   (if (and (policy call (>= speed space) (>= speed cspeed))
290            (not (eq (functional-kind (node-home-lambda call)) :external))
291            (not *converting-for-interpreter*)
292            (inline-expansion-ok call))
293       (with-ir1-environment call
294         (let* ((*lexenv* (functional-lexenv fun))
295                (won nil)
296                (res (catch 'local-call-lossage
297                       (prog1
298                           (ir1-convert-lambda (functional-inline-expansion fun))
299                         (setq won t)))))
300           (cond (won
301                  (change-ref-leaf ref res)
302                  res)
303                 (t
304                  (let ((*compiler-error-context* call))
305                    (compiler-note "couldn't inline expand because expansion ~
306                                    calls this let-converted local function:~
307                                    ~%  ~S"
308                                   (leaf-name res)))
309                  fun))))
310       fun))
311
312 ;;; Dispatch to the appropriate function to attempt to convert a call. Ref
313 ;;; most be a reference to a FUNCTIONAL. This is called in IR1 optimize as
314 ;;; well as in local call analysis. If the call is is already :Local, we do
315 ;;; nothing. If the call is already scheduled for deletion, also do nothing
316 ;;; (in addition to saving time, this also avoids some problems with optimizing
317 ;;; collections of functions that are partially deleted.)
318 ;;;
319 ;;; This is called both before and after FIND-INITIAL-DFO runs. When called
320 ;;; on a :INITIAL component, we don't care whether the caller and callee are in
321 ;;; the same component. Afterward, we must stick with whatever component
322 ;;; division we have chosen.
323 ;;;
324 ;;; Before attempting to convert a call, we see whether the function is
325 ;;; supposed to be inline expanded. Call conversion proceeds as before
326 ;;; after any expansion.
327 ;;;
328 ;;; We bind *Compiler-Error-Context* to the node for the call so that
329 ;;; warnings will get the right context.
330 (defun convert-call-if-possible (ref call)
331   (declare (type ref ref) (type basic-combination call))
332   (let* ((block (node-block call))
333          (component (block-component block))
334          (original-fun (ref-leaf ref)))
335     (assert (functional-p original-fun))
336     (unless (or (member (basic-combination-kind call) '(:local :error))
337                 (block-delete-p block)
338                 (eq (functional-kind (block-home-lambda block)) :deleted)
339                 (member (functional-kind original-fun)
340                         '(:top-level-xep :deleted))
341                 (not (or (eq (component-kind component) :initial)
342                          (eq (block-component
343                               (node-block
344                                (lambda-bind (main-entry original-fun))))
345                              component))))
346       (let ((fun (if (external-entry-point-p original-fun)
347                      (functional-entry-function original-fun)
348                      original-fun))
349             (*compiler-error-context* call))
350
351         (when (and (eq (functional-inlinep fun) :inline)
352                    (rest (leaf-refs original-fun)))
353           (setq fun (maybe-expand-local-inline fun ref call)))
354
355         (assert (member (functional-kind fun)
356                         '(nil :escape :cleanup :optional)))
357         (cond ((mv-combination-p call)
358                (convert-mv-call ref call fun))
359               ((lambda-p fun)
360                (convert-lambda-call ref call fun))
361               (t
362                (convert-hairy-call ref call fun))))))
363
364   (values))
365
366 ;;; Attempt to convert a multiple-value call. The only interesting
367 ;;; case is a call to a function that Looks-Like-An-MV-Bind, has
368 ;;; exactly one reference and no XEP, and is called with one values
369 ;;; continuation.
370 ;;;
371 ;;; We change the call to be to the last optional entry point and
372 ;;; change the call to be local. Due to our preconditions, the call
373 ;;; should eventually be converted to a let, but we can't do that now,
374 ;;; since there may be stray references to the e-p lambda due to
375 ;;; optional defaulting code.
376 ;;;
377 ;;; We also use variable types for the called function to construct an
378 ;;; assertion for the values continuation.
379 ;;;
380 ;;; See CONVERT-CALL for additional notes on MERGE-TAIL-SETS, etc.
381 (defun convert-mv-call (ref call fun)
382   (declare (type ref ref) (type mv-combination call) (type functional fun))
383   (when (and (looks-like-an-mv-bind fun)
384              (not (functional-entry-function fun))
385              (= (length (leaf-refs fun)) 1)
386              (= (length (basic-combination-args call)) 1))
387     (let ((ep (car (last (optional-dispatch-entry-points fun)))))
388       (setf (basic-combination-kind call) :local)
389       (pushnew ep (lambda-calls (node-home-lambda call)))
390       (merge-tail-sets call ep)
391       (change-ref-leaf ref ep)
392
393       (assert-continuation-type
394        (first (basic-combination-args call))
395        (make-values-type :optional (mapcar #'leaf-type (lambda-vars ep))
396                          :rest *universal-type*))))
397   (values))
398
399 ;;; Attempt to convert a call to a lambda. If the number of args is
400 ;;; wrong, we give a warning and mark the call as :ERROR to remove it
401 ;;; from future consideration. If the argcount is O.K. then we just
402 ;;; convert it.
403 (defun convert-lambda-call (ref call fun)
404   (declare (type ref ref) (type combination call) (type clambda fun))
405   (let ((nargs (length (lambda-vars fun)))
406         (call-args (length (combination-args call))))
407     (cond ((= call-args nargs)
408            (convert-call ref call fun))
409           (t
410            ;; FIXME: ANSI requires in "3.2.5 Exceptional Situations in the
411            ;; Compiler" that calling a function with "the wrong number of
412            ;; arguments" be only a STYLE-ERROR. I think, though, that this
413            ;; should only apply when the number of arguments is inferred
414            ;; from a previous definition. If the number of arguments
415            ;; is DECLAIMed, surely calling with the wrong number is a
416            ;; real WARNING. As long as SBCL continues to use CMU CL's
417            ;; non-ANSI DEFUN-is-a-DECLAIM policy, we're in violation here,
418            ;; but as long as we continue to use that policy, that's the
419            ;; not our biggest problem.:-| When we fix that policy, this
420            ;; should come back into compliance. (So fix that policy!)
421            (compiler-warning
422             "function called with ~R argument~:P, but wants exactly ~R"
423             call-args nargs)
424            (setf (basic-combination-kind call) :error)))))
425 \f
426 ;;;; optional, more and keyword calls
427
428 ;;; Similar to Convert-Lambda-Call, but deals with Optional-Dispatches. If
429 ;;; only fixed args are supplied, then convert a call to the correct entry
430 ;;; point. If keyword args are supplied, then dispatch to a subfunction. We
431 ;;; don't convert calls to functions that have a more (or rest) arg.
432 (defun convert-hairy-call (ref call fun)
433   (declare (type ref ref) (type combination call)
434            (type optional-dispatch fun))
435   (let ((min-args (optional-dispatch-min-args fun))
436         (max-args (optional-dispatch-max-args fun))
437         (call-args (length (combination-args call))))
438     (cond ((< call-args min-args)
439            ;; FIXME: ANSI requires in "3.2.5 Exceptional Situations in the
440            ;; Compiler" that calling a function with "the wrong number of
441            ;; arguments" be only a STYLE-ERROR. I think, though, that this
442            ;; should only apply when the number of arguments is inferred
443            ;; from a previous definition. If the number of arguments
444            ;; is DECLAIMed, surely calling with the wrong number is a
445            ;; real WARNING. As long as SBCL continues to use CMU CL's
446            ;; non-ANSI DEFUN-is-a-DECLAIM policy, we're in violation here,
447            ;; but as long as we continue to use that policy, that's the
448            ;; not our biggest problem.:-| When we fix that policy, this
449            ;; should come back into compliance. (So fix that policy!)
450            (compiler-warning
451             "function called with ~R argument~:P, but wants at least ~R"
452             call-args min-args)
453            (setf (basic-combination-kind call) :error))
454           ((<= call-args max-args)
455            (convert-call ref call
456                          (elt (optional-dispatch-entry-points fun)
457                               (- call-args min-args))))
458           ((optional-dispatch-more-entry fun)
459            (convert-more-call ref call fun))
460           (t
461            ;; FIXME: ANSI requires in "3.2.5 Exceptional Situations in the
462            ;; Compiler" that calling a function with "the wrong number of
463            ;; arguments" be only a STYLE-ERROR. I think, though, that this
464            ;; should only apply when the number of arguments is inferred
465            ;; from a previous definition. If the number of arguments
466            ;; is DECLAIMed, surely calling with the wrong number is a
467            ;; real WARNING. As long as SBCL continues to use CMU CL's
468            ;; non-ANSI DEFUN-is-a-DECLAIM policy, we're in violation here,
469            ;; but as long as we continue to use that policy, that's the
470            ;; not our biggest problem.:-| When we fix that policy, this
471            ;; should come back into compliance. (So fix that policy!)
472            (compiler-warning
473             "function called with ~R argument~:P, but wants at most ~R"
474             call-args max-args)
475            (setf (basic-combination-kind call) :error))))
476   (values))
477
478 ;;; This function is used to convert a call to an entry point when complex
479 ;;; transformations need to be done on the original arguments. Entry is the
480 ;;; entry point function that we are calling. Vars is a list of variable names
481 ;;; which are bound to the original call arguments. Ignores is the subset of
482 ;;; Vars which are ignored. Args is the list of arguments to the entry point
483 ;;; function.
484 ;;;
485 ;;; In order to avoid gruesome graph grovelling, we introduce a new function
486 ;;; that rearranges the arguments and calls the entry point. We analyze the
487 ;;; new function and the entry point immediately so that everything gets
488 ;;; converted during the single pass.
489 (defun convert-hairy-fun-entry (ref call entry vars ignores args)
490   (declare (list vars ignores args) (type ref ref) (type combination call)
491            (type clambda entry))
492   (let ((new-fun
493          (with-ir1-environment call
494            (ir1-convert-lambda
495             `(lambda ,vars
496                (declare (ignorable . ,ignores))
497                (%funcall ,entry . ,args))))))
498     (convert-call ref call new-fun)
499     (dolist (ref (leaf-refs entry))
500       (convert-call-if-possible ref (continuation-dest (node-cont ref))))))
501
502 ;;; Use Convert-Hairy-Fun-Entry to convert a more-arg call to a known
503 ;;; function into a local call to the Main-Entry.
504 ;;;
505 ;;; First we verify that all keywords are constant and legal. If there
506 ;;; aren't, then we warn the user and don't attempt to convert the call.
507 ;;;
508 ;;; We massage the supplied keyword arguments into the order expected by the
509 ;;; main entry. This is done by binding all the arguments to the keyword call
510 ;;; to variables in the introduced lambda, then passing these values variables
511 ;;; in the correct order when calling the main entry. Unused arguments
512 ;;; (such as the keywords themselves) are discarded simply by not passing them
513 ;;; along.
514 ;;;
515 ;;; If there is a rest arg, then we bundle up the args and pass them to LIST.
516 (defun convert-more-call (ref call fun)
517   (declare (type ref ref) (type combination call) (type optional-dispatch fun))
518   (let* ((max (optional-dispatch-max-args fun))
519          (arglist (optional-dispatch-arglist fun))
520          (args (combination-args call))
521          (more (nthcdr max args))
522          (flame (policy call (or (> speed brevity) (> space brevity))))
523          (loser nil)
524          (temps (make-gensym-list max))
525          (more-temps (make-gensym-list (length more))))
526     (collect ((ignores)
527               (supplied)
528               (key-vars))
529
530       (dolist (var arglist)
531         (let ((info (lambda-var-arg-info var)))
532           (when info
533             (ecase (arg-info-kind info)
534               (:keyword
535                (key-vars var))
536               ((:rest :optional))
537               ((:more-context :more-count)
538                (compiler-warning "can't local-call functions with &MORE args")
539                (setf (basic-combination-kind call) :error)
540                (return-from convert-more-call))))))
541
542       (when (optional-dispatch-keyp fun)
543         (when (oddp (length more))
544           (compiler-warning "function called with odd number of ~
545                              arguments in keyword portion")
546
547           (setf (basic-combination-kind call) :error)
548           (return-from convert-more-call))
549
550         (do ((key more (cddr key))
551              (temp more-temps (cddr temp)))
552             ((null key))
553           (let ((cont (first key)))
554             (unless (constant-continuation-p cont)
555               (when flame
556                 (compiler-note "non-constant keyword in keyword call"))
557               (setf (basic-combination-kind call) :error)
558               (return-from convert-more-call))
559
560             (let ((name (continuation-value cont))
561                   (dummy (first temp))
562                   (val (second temp)))
563               (dolist (var (key-vars)
564                            (progn
565                              (ignores dummy val)
566                              (setq loser name)))
567                 (let ((info (lambda-var-arg-info var)))
568                   (when (eq (arg-info-keyword info) name)
569                     (ignores dummy)
570                     (supplied (cons var val))
571                     (return)))))))
572
573         (when (and loser (not (optional-dispatch-allowp fun)))
574           (compiler-warning "function called with unknown argument keyword ~S"
575                             loser)
576           (setf (basic-combination-kind call) :error)
577           (return-from convert-more-call)))
578
579       (collect ((call-args))
580         (do ((var arglist (cdr var))
581              (temp temps (cdr temp)))
582             (())
583           (let ((info (lambda-var-arg-info (car var))))
584             (if info
585                 (ecase (arg-info-kind info)
586                   (:optional
587                    (call-args (car temp))
588                    (when (arg-info-supplied-p info)
589                      (call-args t)))
590                   (:rest
591                    (call-args `(list ,@more-temps))
592                    (return))
593                   (:keyword
594                    (return)))
595                 (call-args (car temp)))))
596
597         (dolist (var (key-vars))
598           (let ((info (lambda-var-arg-info var))
599                 (temp (cdr (assoc var (supplied)))))
600             (if temp
601                 (call-args temp)
602                 (call-args (arg-info-default info)))
603             (when (arg-info-supplied-p info)
604               (call-args (not (null temp))))))
605
606         (convert-hairy-fun-entry ref call (optional-dispatch-main-entry fun)
607                                  (append temps more-temps)
608                                  (ignores) (call-args)))))
609
610   (values))
611 \f
612 ;;;; LET conversion
613 ;;;;
614 ;;;; Converting to a LET has differing significance to various parts of the
615 ;;;; compiler:
616 ;;;; -- The body of a LET is spliced in immediately after the corresponding
617 ;;;;    combination node, making the control transfer explicit and allowing
618 ;;;;    LETs to be mashed together into a single block. The value of the LET is
619 ;;;;    delivered directly to the original continuation for the call,
620 ;;;;    eliminating the need to propagate information from the dummy result
621 ;;;;    continuation.
622 ;;;; -- As far as IR1 optimization is concerned, it is interesting in that
623 ;;;;    there is only one expression that the variable can be bound to, and
624 ;;;;    this is easily substitited for.
625 ;;;; -- LETs are interesting to environment analysis and to the back end
626 ;;;;    because in most ways a LET can be considered to be "the same function"
627 ;;;;    as its home function.
628 ;;;; -- LET conversion has dynamic scope implications, since control transfers
629 ;;;;    within the same environment are local. In a local control transfer,
630 ;;;;    cleanup code must be emitted to remove dynamic bindings that are no
631 ;;;;    longer in effect.
632
633 ;;; Set up the control transfer to the called lambda. We split the call
634 ;;; block immediately after the call, and link the head of FUN to the call
635 ;;; block. The successor block after splitting (where we return to) is
636 ;;; returned.
637 ;;;
638 ;;; If the lambda is is a different component than the call, then we call
639 ;;; JOIN-COMPONENTS. This only happens in block compilation before
640 ;;; FIND-INITIAL-DFO.
641 (defun insert-let-body (fun call)
642   (declare (type clambda fun) (type basic-combination call))
643   (let* ((call-block (node-block call))
644          (bind-block (node-block (lambda-bind fun)))
645          (component (block-component call-block)))
646     (let ((fun-component (block-component bind-block)))
647       (unless (eq fun-component component)
648         (assert (eq (component-kind component) :initial))
649         (join-components component fun-component)))
650
651     (let ((*current-component* component))
652       (node-ends-block call))
653     ;; FIXME: Use PROPER-LIST-OF-LENGTH-P here, and look for other
654     ;; uses of '=.*length' which could also be converted to use
655     ;; PROPER-LIST-OF-LENGTH-P.
656     (assert (= (length (block-succ call-block)) 1))
657     (let ((next-block (first (block-succ call-block))))
658       (unlink-blocks call-block next-block)
659       (link-blocks call-block bind-block)
660       next-block)))
661
662 ;;; Handle the environment semantics of LET conversion. We add the lambda
663 ;;; and its LETs to lets for the Call's home function. We merge the calls for
664 ;;; Fun with the calls for the home function, removing Fun in the process. We
665 ;;; also merge the Entries.
666 ;;;
667 ;;; We also unlink the function head from the component head and set
668 ;;; Component-Reanalyze to true to indicate that the DFO should be recomputed.
669 (defun merge-lets (fun call)
670   (declare (type clambda fun) (type basic-combination call))
671   (let ((component (block-component (node-block call))))
672     (unlink-blocks (component-head component) (node-block (lambda-bind fun)))
673     (setf (component-lambdas component)
674           (delete fun (component-lambdas component)))
675     (setf (component-reanalyze component) t))
676   (setf (lambda-call-lexenv fun) (node-lexenv call))
677   (let ((tails (lambda-tail-set fun)))
678     (setf (tail-set-functions tails)
679           (delete fun (tail-set-functions tails))))
680   (setf (lambda-tail-set fun) nil)
681   (let* ((home (node-home-lambda call))
682          (home-env (lambda-environment home)))
683     (push fun (lambda-lets home))
684     (setf (lambda-home fun) home)
685     (setf (lambda-environment fun) home-env)
686
687     (let ((lets (lambda-lets fun)))
688       (dolist (let lets)
689         (setf (lambda-home let) home)
690         (setf (lambda-environment let) home-env))
691
692       (setf (lambda-lets home) (nconc lets (lambda-lets home)))
693       (setf (lambda-lets fun) ()))
694
695     (setf (lambda-calls home)
696           (nunion (lambda-calls fun)
697                   (delete fun (lambda-calls home))))
698     (setf (lambda-calls fun) ())
699
700     (setf (lambda-entries home)
701           (nconc (lambda-entries fun) (lambda-entries home)))
702     (setf (lambda-entries fun) ()))
703   (values))
704
705 ;;; Handle the value semantics of let conversion. Delete Fun's return node,
706 ;;; and change the control flow to transfer to Next-Block instead. Move all
707 ;;; the uses of the result continuation to Call's Cont.
708 ;;;
709 ;;; If the actual continuation is only used by the let call, then we
710 ;;; intersect the type assertion on the dummy continuation with the assertion
711 ;;; for the actual continuation; in all other cases assertions on the dummy
712 ;;; continuation are lost.
713 ;;;
714 ;;; We also intersect the derived type of the call with the derived type of
715 ;;; all the dummy continuation's uses. This serves mainly to propagate
716 ;;; TRULY-THE through lets.
717 (defun move-return-uses (fun call next-block)
718   (declare (type clambda fun) (type basic-combination call)
719            (type cblock next-block))
720   (let* ((return (lambda-return fun))
721          (return-block (node-block return)))
722     (unlink-blocks return-block
723                    (component-tail (block-component return-block)))
724     (link-blocks return-block next-block)
725     (unlink-node return)
726     (delete-return return)
727     (let ((result (return-result return))
728           (cont (node-cont call))
729           (call-type (node-derived-type call)))
730       (when (eq (continuation-use cont) call)
731         (assert-continuation-type cont (continuation-asserted-type result)))
732       (unless (eq call-type *wild-type*)
733         (do-uses (use result)
734           (derive-node-type use call-type)))
735       (substitute-continuation-uses cont result)))
736   (values))
737
738 ;;; Change all Cont for all the calls to Fun to be the start continuation
739 ;;; for the bind node. This allows the blocks to be joined if the caller count
740 ;;; ever goes to one.
741 (defun move-let-call-cont (fun)
742   (declare (type clambda fun))
743   (let ((new-cont (node-prev (lambda-bind fun))))
744     (dolist (ref (leaf-refs fun))
745       (let ((dest (continuation-dest (node-cont ref))))
746         (delete-continuation-use dest)
747         (add-continuation-use dest new-cont))))
748   (values))
749
750 ;;; We are converting Fun to be a let when the call is in a non-tail
751 ;;; position. Any previously tail calls in Fun are no longer tail calls, and
752 ;;; must be restored to normal calls which transfer to Next-Block (Fun's
753 ;;; return point.)  We can't do this by DO-USES on the RETURN-RESULT, because
754 ;;; the return might have been deleted (if all calls were TR.)
755 ;;;
756 ;;; The called function might be an assignment in the case where we are
757 ;;; currently converting that function. In steady-state, assignments never
758 ;;; appear in the lambda-calls.
759 (defun unconvert-tail-calls (fun call next-block)
760   (dolist (called (lambda-calls fun))
761     (dolist (ref (leaf-refs called))
762       (let ((this-call (continuation-dest (node-cont ref))))
763         (when (and (node-tail-p this-call)
764                    (eq (node-home-lambda this-call) fun))
765           (setf (node-tail-p this-call) nil)
766           (ecase (functional-kind called)
767             ((nil :cleanup :optional)
768              (let ((block (node-block this-call))
769                    (cont (node-cont call)))
770                (ensure-block-start cont)
771                (unlink-blocks block (first (block-succ block)))
772                (link-blocks block next-block)
773                (delete-continuation-use this-call)
774                (add-continuation-use this-call cont)))
775             (:deleted)
776             (:assignment
777              (assert (eq called fun))))))))
778   (values))
779
780 ;;; Deal with returning from a let or assignment that we are converting.
781 ;;; FUN is the function we are calling, CALL is a call to FUN, and NEXT-BLOCK
782 ;;; is the return point for a non-tail call, or NULL if call is a tail call.
783 ;;;
784 ;;; If the call is not a tail call, then we must do UNCONVERT-TAIL-CALLS, since
785 ;;; a tail call is a call which returns its value out of the enclosing non-let
786 ;;; function. When call is non-TR, we must convert it back to an ordinary
787 ;;; local call, since the value must be delivered to the receiver of CALL's
788 ;;; value.
789 ;;;
790 ;;; We do different things depending on whether the caller and callee have
791 ;;; returns left:
792 ;;; -- If the callee has no return we just do MOVE-LET-CALL-CONT. Either the
793 ;;;    function doesn't return, or all returns are via tail-recursive local
794 ;;;    calls.
795 ;;; -- If CALL is a non-tail call, or if both have returns, then we
796 ;;;    delete the callee's return, move its uses to the call's result
797 ;;;    continuation, and transfer control to the appropriate return point.
798 ;;; -- If the callee has a return, but the caller doesn't, then we move the
799 ;;;    return to the caller.
800 (defun move-return-stuff (fun call next-block)
801   (declare (type clambda fun) (type basic-combination call)
802            (type (or cblock null) next-block))
803   (when next-block
804     (unconvert-tail-calls fun call next-block))
805   (let* ((return (lambda-return fun))
806          (call-fun (node-home-lambda call))
807          (call-return (lambda-return call-fun)))
808     (cond ((not return))
809           ((or next-block call-return)
810            (unless (block-delete-p (node-block return))
811              (move-return-uses fun call
812                                (or next-block (node-block call-return)))))
813           (t
814            (assert (node-tail-p call))
815            (setf (lambda-return call-fun) return)
816            (setf (return-lambda return) call-fun))))
817   (move-let-call-cont fun)
818   (values))
819
820 ;;; Actually do LET conversion. We call subfunctions to do most of the
821 ;;; work. We change the CALL's cont to be the continuation heading the bind
822 ;;; block, and also do REOPTIMIZE-CONTINUATION on the args and Cont so that
823 ;;; let-specific IR1 optimizations get a chance. We blow away any entry for
824 ;;; the function in *FREE-FUNCTIONS* so that nobody will create new reference
825 ;;; to it.
826 (defun let-convert (fun call)
827   (declare (type clambda fun) (type basic-combination call))
828   (let ((next-block (if (node-tail-p call)
829                         nil
830                         (insert-let-body fun call))))
831     (move-return-stuff fun call next-block)
832     (merge-lets fun call)))
833
834 ;;; Reoptimize all of Call's args and its result.
835 (defun reoptimize-call (call)
836   (declare (type basic-combination call))
837   (dolist (arg (basic-combination-args call))
838     (when arg
839       (reoptimize-continuation arg)))
840   (reoptimize-continuation (node-cont call))
841   (values))
842
843 ;;; We also don't convert calls to named functions which appear in the initial
844 ;;; component, delaying this until optimization. This minimizes the likelyhood
845 ;;; that we well let-convert a function which may have references added due to
846 ;;; later local inline expansion
847 (defun ok-initial-convert-p (fun)
848   (not (and (leaf-name fun)
849             (eq (component-kind
850                  (block-component
851                   (node-block (lambda-bind fun))))
852                 :initial))))
853
854 ;;; This function is called when there is some reason to believe that
855 ;;; the lambda Fun might be converted into a let. This is done after local
856 ;;; call analysis, and also when a reference is deleted. We only convert to a
857 ;;; let when the function is a normal local function, has no XEP, and is
858 ;;; referenced in exactly one local call. Conversion is also inhibited if the
859 ;;; only reference is in a block about to be deleted. We return true if we
860 ;;; converted.
861 ;;;
862 ;;; These rules may seem unnecessarily restrictive, since there are some
863 ;;; cases where we could do the return with a jump that don't satisfy these
864 ;;; requirements. The reason for doing things this way is that it makes the
865 ;;; concept of a let much more useful at the level of IR1 semantics. The
866 ;;; :ASSIGNMENT function kind provides another way to optimize calls to
867 ;;; single-return/multiple call functions.
868 ;;;
869 ;;; We don't attempt to convert calls to functions that have an XEP, since
870 ;;; we might be embarrassed later when we want to convert a newly discovered
871 ;;; local call. Also, see OK-INITIAL-CONVERT-P.
872 (defun maybe-let-convert (fun)
873   (declare (type clambda fun))
874   (let ((refs (leaf-refs fun)))
875     (when (and refs
876                (null (rest refs))
877                (member (functional-kind fun) '(nil :assignment))
878                (not (functional-entry-function fun)))
879       (let* ((ref-cont (node-cont (first refs)))
880              (dest (continuation-dest ref-cont)))
881         (when (and (basic-combination-p dest)
882                    (eq (basic-combination-fun dest) ref-cont)
883                    (eq (basic-combination-kind dest) :local)
884                    (not (block-delete-p (node-block dest)))
885                    (cond ((ok-initial-convert-p fun) t)
886                          (t
887                           (reoptimize-continuation ref-cont)
888                           nil)))
889           (unless (eq (functional-kind fun) :assignment)
890             (let-convert fun dest))
891           (reoptimize-call dest)
892           (setf (functional-kind fun)
893                 (if (mv-combination-p dest) :mv-let :let))))
894       t)))
895 \f
896 ;;;; tail local calls and assignments
897
898 ;;; Return T if there are no cleanups between Block1 and Block2, or if they
899 ;;; definitely won't generate any cleanup code. Currently we recognize lexical
900 ;;; entry points that are only used locally (if at all).
901 (defun only-harmless-cleanups (block1 block2)
902   (declare (type cblock block1 block2))
903   (or (eq block1 block2)
904       (let ((cleanup2 (block-start-cleanup block2)))
905         (do ((cleanup (block-end-cleanup block1)
906                       (node-enclosing-cleanup (cleanup-mess-up cleanup))))
907             ((eq cleanup cleanup2) t)
908           (case (cleanup-kind cleanup)
909             ((:block :tagbody)
910              (unless (null (entry-exits (cleanup-mess-up cleanup)))
911                (return nil)))
912             (t (return nil)))))))
913
914 ;;; If a potentially TR local call really is TR, then convert it to jump
915 ;;; directly to the called function. We also call MAYBE-CONVERT-TO-ASSIGNMENT.
916 ;;; The first value is true if we tail-convert. The second is the value of
917 ;;; M-C-T-A. We can switch the succesor (potentially deleting the RETURN node)
918 ;;; unless:
919 ;;; -- The call has already been converted.
920 ;;; -- The call isn't TR (some implicit MV PROG1.)
921 ;;; -- The call is in an XEP (thus we might decide to make it non-tail so that
922 ;;;    we can use known return inside the component.)
923 ;;; -- There is a change in the cleanup between the call in the return, so we
924 ;;;    might need to introduce cleanup code.
925 (defun maybe-convert-tail-local-call (call)
926   (declare (type combination call))
927   (let ((return (continuation-dest (node-cont call))))
928     (assert (return-p return))
929     (when (and (not (node-tail-p call))
930                (immediately-used-p (return-result return) call)
931                (not (eq (functional-kind (node-home-lambda call))
932                         :external))
933                (only-harmless-cleanups (node-block call)
934                                        (node-block return)))
935       (node-ends-block call)
936       (let ((block (node-block call))
937             (fun (combination-lambda call)))
938         (setf (node-tail-p call) t)
939         (unlink-blocks block (first (block-succ block)))
940         (link-blocks block (node-block (lambda-bind fun)))
941         (values t (maybe-convert-to-assignment fun))))))
942
943 ;;; Called when we believe it might make sense to convert Fun to an
944 ;;; assignment. All this function really does is determine when a function
945 ;;; with more than one call can still be combined with the calling function's
946 ;;; environment. We can convert when:
947 ;;; -- The function is a normal, non-entry function, and
948 ;;; -- Except for one call, all calls must be tail recursive calls in the
949 ;;;    called function (i.e. are self-recursive tail calls)
950 ;;; -- OK-INITIAL-CONVERT-P is true.
951 ;;;
952 ;;; There may be one outside call, and it need not be tail-recursive. Since
953 ;;; all tail local calls have already been converted to direct transfers, the
954 ;;; only control semantics needed are to splice in the body at the non-tail
955 ;;; call. If there is no non-tail call, then we need only merge the
956 ;;; environments. Both cases are handled by LET-CONVERT.
957 ;;;
958 ;;; ### It would actually be possible to allow any number of outside calls as
959 ;;; long as they all return to the same place (i.e. have the same conceptual
960 ;;; continuation.)  A special case of this would be when all of the outside
961 ;;; calls are tail recursive.
962 (defun maybe-convert-to-assignment (fun)
963   (declare (type clambda fun))
964   (when (and (not (functional-kind fun))
965              (not (functional-entry-function fun)))
966     (let ((non-tail nil)
967           (call-fun nil))
968       (when (and (dolist (ref (leaf-refs fun) t)
969                    (let ((dest (continuation-dest (node-cont ref))))
970                      (when (block-delete-p (node-block dest)) (return nil))
971                      (let ((home (node-home-lambda ref)))
972                        (unless (eq home fun)
973                          (when call-fun (return nil))
974                          (setq call-fun home))
975                        (unless (node-tail-p dest)
976                          (when (or non-tail (eq home fun)) (return nil))
977                          (setq non-tail dest)))))
978                  (ok-initial-convert-p fun))
979         (setf (functional-kind fun) :assignment)
980         (let-convert fun (or non-tail
981                              (continuation-dest
982                               (node-cont (first (leaf-refs fun))))))
983         (when non-tail (reoptimize-call non-tail))
984         t))))