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