443fef5569458c4d406b29851c19a80bd401b51f
[sbcl.git] / src / compiler / ir1-translators.lisp
1 ;;;; the usual place for DEF-IR1-TRANSLATOR forms (and their
2 ;;;; close personal friends)
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!C")
14 \f
15 ;;;; special forms for control
16
17 (def-ir1-translator progn ((&rest forms) start next result)
18   #!+sb-doc
19   "PROGN form*
20
21 Evaluates each FORM in order, returning the values of the last form. With no
22 forms, returns NIL."
23   (ir1-convert-progn-body start next result forms))
24
25 (def-ir1-translator if ((test then &optional else) start next result)
26   #!+sb-doc
27   "IF predicate then [else]
28
29 If PREDICATE evaluates to false, evaluate THEN and return its values,
30 otherwise evaluate ELSE and return its values. ELSE defaults to NIL."
31   (let* ((pred-ctran (make-ctran))
32          (pred-lvar (make-lvar))
33          (then-ctran (make-ctran))
34          (then-block (ctran-starts-block then-ctran))
35          (else-ctran (make-ctran))
36          (else-block (ctran-starts-block else-ctran))
37          (node (make-if :test pred-lvar
38                         :consequent then-block
39                         :alternative else-block)))
40     ;; IR1-CONVERT-MAYBE-PREDICATE requires DEST to be CIF, so the
41     ;; order of the following two forms is important
42     (setf (lvar-dest pred-lvar) node)
43     (ir1-convert start pred-ctran pred-lvar test)
44     (link-node-to-previous-ctran node pred-ctran)
45
46     (let ((start-block (ctran-block pred-ctran)))
47       (setf (block-last start-block) node)
48       (ctran-starts-block next)
49
50       (link-blocks start-block then-block)
51       (link-blocks start-block else-block))
52
53     (ir1-convert then-ctran next result then)
54     (ir1-convert else-ctran next result else)))
55 \f
56 ;;;; BLOCK and TAGBODY
57
58 ;;;; We make an ENTRY node to mark the start and a :ENTRY cleanup to
59 ;;;; mark its extent. When doing GO or RETURN-FROM, we emit an EXIT
60 ;;;; node.
61
62 ;;; Make a :ENTRY cleanup and emit an ENTRY node, then convert the
63 ;;; body in the modified environment. We make NEXT start a block now,
64 ;;; since if it was done later, the block would be in the wrong
65 ;;; environment.
66 (def-ir1-translator block ((name &rest forms) start next result)
67   #!+sb-doc
68   "BLOCK name form*
69
70 Evaluate the FORMS as a PROGN. Within the lexical scope of the body,
71 RETURN-FROM can be used to exit the form."
72   (unless (symbolp name)
73     (compiler-error "The block name ~S is not a symbol." name))
74   (start-block start)
75   (ctran-starts-block next)
76   (let* ((dummy (make-ctran))
77          (entry (make-entry))
78          (cleanup (make-cleanup :kind :block
79                                 :mess-up entry)))
80     (push entry (lambda-entries (lexenv-lambda *lexenv*)))
81     (setf (entry-cleanup entry) cleanup)
82     (link-node-to-previous-ctran entry start)
83     (use-ctran entry dummy)
84
85     (let* ((env-entry (list entry next result))
86            (*lexenv* (make-lexenv :blocks (list (cons name env-entry))
87                                   :cleanup cleanup)))
88       (ir1-convert-progn-body dummy next result forms))))
89
90 (def-ir1-translator return-from ((name &optional value) start next result)
91   #!+sb-doc
92   "RETURN-FROM block-name value-form
93
94 Evaluate the VALUE-FORM, returning its values from the lexically enclosing
95 block BLOCK-NAME. This is constrained to be used only within the dynamic
96 extent of the block."
97   ;; old comment:
98   ;;   We make NEXT start a block just so that it will have a block
99   ;;   assigned. People assume that when they pass a ctran into
100   ;;   IR1-CONVERT as NEXT, it will have a block when it is done.
101   ;; KLUDGE: Note that this block is basically fictitious. In the code
102   ;;   (BLOCK B (RETURN-FROM B) (SETQ X 3))
103   ;; it's the block which answers the question "which block is
104   ;; the (SETQ X 3) in?" when the right answer is that (SETQ X 3) is
105   ;; dead code and so doesn't really have a block at all. The existence
106   ;; of this block, and that way that it doesn't explicitly say
107   ;; "I'm actually nowhere at all" makes some logic (e.g.
108   ;; BLOCK-HOME-LAMBDA-OR-NULL) more obscure, and it might be better
109   ;; to get rid of it, perhaps using a special placeholder value
110   ;; to indicate the orphanedness of the code.
111   (declare (ignore result))
112   (ctran-starts-block next)
113   (let* ((found (or (lexenv-find name blocks)
114                     (compiler-error "return for unknown block: ~S" name)))
115          (exit-ctran (second found))
116          (value-ctran (make-ctran))
117          (value-lvar (make-lvar))
118          (entry (first found))
119          (exit (make-exit :entry entry
120                           :value value-lvar)))
121     (when (ctran-deleted-p exit-ctran)
122       (throw 'locall-already-let-converted exit-ctran))
123     (push exit (entry-exits entry))
124     (setf (lvar-dest value-lvar) exit)
125     (ir1-convert start value-ctran value-lvar value)
126     (link-node-to-previous-ctran exit value-ctran)
127     (let ((home-lambda (ctran-home-lambda-or-null start)))
128       (when home-lambda
129         (push entry (lambda-calls-or-closes home-lambda))))
130     (use-continuation exit exit-ctran (third found))))
131
132 ;;; Return a list of the segments of a TAGBODY. Each segment looks
133 ;;; like (<tag> <form>* (go <next tag>)). That is, we break up the
134 ;;; tagbody into segments of non-tag statements, and explicitly
135 ;;; represent the drop-through with a GO. The first segment has a
136 ;;; dummy NIL tag, since it represents code before the first tag. The
137 ;;; last segment (which may also be the first segment) ends in NIL
138 ;;; rather than a GO.
139 (defun parse-tagbody (body)
140   (declare (list body))
141   (collect ((segments))
142     (let ((current (cons nil body)))
143       (loop
144         (let ((tag-pos (position-if (complement #'listp) current :start 1)))
145           (unless tag-pos
146             (segments `(,@current nil))
147             (return))
148           (let ((tag (elt current tag-pos)))
149             (when (assoc tag (segments))
150               (compiler-error
151                "The tag ~S appears more than once in the tagbody."
152                tag))
153             (unless (or (symbolp tag) (integerp tag))
154               (compiler-error "~S is not a legal tagbody statement." tag))
155             (segments `(,@(subseq current 0 tag-pos) (go ,tag))))
156           (setq current (nthcdr tag-pos current)))))
157     (segments)))
158
159 ;;; Set up the cleanup, emitting the entry node. Then make a block for
160 ;;; each tag, building up the tag list for LEXENV-TAGS as we go.
161 ;;; Finally, convert each segment with the precomputed Start and Cont
162 ;;; values.
163 (def-ir1-translator tagbody ((&rest statements) start next result)
164   #!+sb-doc
165   "TAGBODY {tag | statement}*
166
167 Define tags for use with GO. The STATEMENTS are evaluated in order ,skipping
168 TAGS, and NIL is returned. If a statement contains a GO to a defined TAG
169 within the lexical scope of the form, then control is transferred to the next
170 statement following that tag. A TAG must an integer or a symbol. A STATEMENT
171 must be a list. Other objects are illegal within the body."
172   (start-block start)
173   (ctran-starts-block next)
174   (let* ((dummy (make-ctran))
175          (entry (make-entry))
176          (segments (parse-tagbody statements))
177          (cleanup (make-cleanup :kind :tagbody
178                                 :mess-up entry)))
179     (push entry (lambda-entries (lexenv-lambda *lexenv*)))
180     (setf (entry-cleanup entry) cleanup)
181     (link-node-to-previous-ctran entry start)
182     (use-ctran entry dummy)
183
184     (collect ((tags)
185               (starts)
186               (ctrans))
187       (starts dummy)
188       (dolist (segment (rest segments))
189         (let* ((tag-ctran (make-ctran))
190                (tag (list (car segment) entry tag-ctran)))
191           (ctrans tag-ctran)
192           (starts tag-ctran)
193           (ctran-starts-block tag-ctran)
194           (tags tag)))
195       (ctrans next)
196
197       (let ((*lexenv* (make-lexenv :cleanup cleanup :tags (tags))))
198         (mapc (lambda (segment start end)
199                 (ir1-convert-progn-body start end
200                                         (when (eq end next) result)
201                                         (rest segment)))
202               segments (starts) (ctrans))))))
203
204 ;;; Emit an EXIT node without any value.
205 (def-ir1-translator go ((tag) start next result)
206   #!+sb-doc
207   "GO tag
208
209 Transfer control to the named TAG in the lexically enclosing TAGBODY. This is
210 constrained to be used only within the dynamic extent of the TAGBODY."
211   (ctran-starts-block next)
212   (let* ((found (or (lexenv-find tag tags :test #'eql)
213                     (compiler-error "attempt to GO to nonexistent tag: ~S"
214                                     tag)))
215          (entry (first found))
216          (exit (make-exit :entry entry)))
217     (push exit (entry-exits entry))
218     (link-node-to-previous-ctran exit start)
219     (let ((home-lambda (ctran-home-lambda-or-null start)))
220       (when home-lambda
221         (push entry (lambda-calls-or-closes home-lambda))))
222     (use-ctran exit (second found))))
223 \f
224 ;;;; translators for compiler-magic special forms
225
226 ;;; This handles EVAL-WHEN in non-top-level forms. (EVAL-WHENs in top
227 ;;; level forms are picked off and handled by PROCESS-TOPLEVEL-FORM,
228 ;;; so that they're never seen at this level.)
229 ;;;
230 ;;; ANSI "3.2.3.1 Processing of Top Level Forms" says that processing
231 ;;; of non-top-level EVAL-WHENs is very simple:
232 ;;;   EVAL-WHEN forms cause compile-time evaluation only at top level.
233 ;;;   Both :COMPILE-TOPLEVEL and :LOAD-TOPLEVEL situation specifications
234 ;;;   are ignored for non-top-level forms. For non-top-level forms, an
235 ;;;   eval-when specifying the :EXECUTE situation is treated as an
236 ;;;   implicit PROGN including the forms in the body of the EVAL-WHEN
237 ;;;   form; otherwise, the forms in the body are ignored.
238 (def-ir1-translator eval-when ((situations &rest forms) start next result)
239   #!+sb-doc
240   "EVAL-WHEN (situation*) form*
241
242 Evaluate the FORMS in the specified SITUATIONS (any of :COMPILE-TOPLEVEL,
243 :LOAD-TOPLEVEL, or :EXECUTE, or (deprecated) COMPILE, LOAD, or EVAL)."
244   (multiple-value-bind (ct lt e) (parse-eval-when-situations situations)
245     (declare (ignore ct lt))
246     (ir1-convert-progn-body start next result (and e forms)))
247   (values))
248
249 ;;; common logic for MACROLET and SYMBOL-MACROLET
250 ;;;
251 ;;; Call DEFINITIONIZE-FUN on each element of DEFINITIONS to find its
252 ;;; in-lexenv representation, stuff the results into *LEXENV*, and
253 ;;; call FUN (with no arguments).
254 (defun %funcall-in-foomacrolet-lexenv (definitionize-fun
255                                        definitionize-keyword
256                                        definitions
257                                        fun)
258   (declare (type function definitionize-fun fun))
259   (declare (type (member :vars :funs) definitionize-keyword))
260   (declare (type list definitions))
261   (unless (= (length definitions)
262              (length (remove-duplicates definitions :key #'first)))
263     (compiler-style-warn "duplicate definitions in ~S" definitions))
264   (let* ((processed-definitions (mapcar definitionize-fun definitions))
265          (*lexenv* (make-lexenv definitionize-keyword processed-definitions)))
266     ;; I wonder how much of an compiler performance penalty this
267     ;; non-constant keyword is.
268     (funcall fun definitionize-keyword processed-definitions)))
269
270 ;;; Tweak LEXENV to include the DEFINITIONS from a MACROLET, then
271 ;;; call FUN (with no arguments).
272 ;;;
273 ;;; This is split off from the IR1 convert method so that it can be
274 ;;; shared by the special-case top level MACROLET processing code, and
275 ;;; further split so that the special-case MACROLET processing code in
276 ;;; EVAL can likewise make use of it.
277 (defun macrolet-definitionize-fun (context lexenv)
278   (flet ((fail (control &rest args)
279            (ecase context
280              (:compile (apply #'compiler-error control args))
281              (:eval (error 'simple-program-error
282                            :format-control control
283                            :format-arguments args)))))
284     (lambda (definition)
285       (unless (list-of-length-at-least-p definition 2)
286         (fail "The list ~S is too short to be a legal local macro definition."
287               definition))
288       (destructuring-bind (name arglist &body body) definition
289         (unless (symbolp name)
290           (fail "The local macro name ~S is not a symbol." name))
291         (when (fboundp name)
292           (program-assert-symbol-home-package-unlocked
293            context name "binding ~A as a local macro"))
294         (unless (listp arglist)
295           (fail "The local macro argument list ~S is not a list."
296                 arglist))
297         (with-unique-names (whole environment)
298           (multiple-value-bind (body local-decls)
299               (parse-defmacro arglist whole body name 'macrolet
300                               :environment environment)
301             `(,name macro .
302                     ,(compile-in-lexenv
303                       nil
304                       `(lambda (,whole ,environment)
305                          ,@local-decls
306                          ,body)
307                       lexenv))))))))
308
309 (defun funcall-in-macrolet-lexenv (definitions fun context)
310   (%funcall-in-foomacrolet-lexenv
311    (macrolet-definitionize-fun context (make-restricted-lexenv *lexenv*))
312    :funs
313    definitions
314    fun))
315
316 (def-ir1-translator macrolet ((definitions &rest body) start next result)
317   #!+sb-doc
318   "MACROLET ({(name lambda-list form*)}*) body-form*
319
320 Evaluate the BODY-FORMS in an environment with the specified local macros
321 defined. Name is the local macro name, LAMBDA-LIST is a DEFMACRO style
322 destructuring lambda list, and the FORMS evaluate to the expansion."
323   (funcall-in-macrolet-lexenv
324    definitions
325    (lambda (&key funs)
326      (declare (ignore funs))
327      (ir1-translate-locally body start next result))
328    :compile))
329
330 (defun symbol-macrolet-definitionize-fun (context)
331   (flet ((fail (control &rest args)
332            (ecase context
333              (:compile (apply #'compiler-error control args))
334              (:eval (error 'simple-program-error
335                            :format-control control
336                            :format-arguments args)))))
337     (lambda (definition)
338       (unless (proper-list-of-length-p definition 2)
339         (fail "malformed symbol/expansion pair: ~S" definition))
340       (destructuring-bind (name expansion) definition
341         (unless (symbolp name)
342           (fail "The local symbol macro name ~S is not a symbol." name))
343         (when (or (boundp name) (eq (info :variable :kind name) :macro))
344           (program-assert-symbol-home-package-unlocked
345            context name "binding ~A as a local symbol-macro"))
346         (let ((kind (info :variable :kind name)))
347           (when (member kind '(:special :constant))
348             (fail "Attempt to bind a ~(~A~) variable with SYMBOL-MACROLET: ~S"
349                   kind name)))
350         ;; A magical cons that MACROEXPAND-1 understands.
351         `(,name . (macro . ,expansion))))))
352
353 (defun funcall-in-symbol-macrolet-lexenv (definitions fun context)
354   (%funcall-in-foomacrolet-lexenv
355    (symbol-macrolet-definitionize-fun context)
356    :vars
357    definitions
358    fun))
359
360 (def-ir1-translator symbol-macrolet
361     ((macrobindings &body body) start next result)
362   #!+sb-doc
363   "SYMBOL-MACROLET ({(name expansion)}*) decl* form*
364
365 Define the NAMES as symbol macros with the given EXPANSIONS. Within the
366 body, references to a NAME will effectively be replaced with the EXPANSION."
367   (funcall-in-symbol-macrolet-lexenv
368    macrobindings
369    (lambda (&key vars)
370      (ir1-translate-locally body start next result :vars vars))
371    :compile))
372 \f
373 ;;;; %PRIMITIVE
374 ;;;;
375 ;;;; Uses of %PRIMITIVE are either expanded into Lisp code or turned
376 ;;;; into a funny function.
377
378 ;;; Carefully evaluate a list of forms, returning a list of the results.
379 (defun eval-info-args (args)
380   (declare (list args))
381   (handler-case (mapcar #'eval args)
382     (error (condition)
383       (compiler-error "Lisp error during evaluation of info args:~%~A"
384                       condition))))
385
386 ;;; Convert to the %%PRIMITIVE funny function. The first argument is
387 ;;; the template, the second is a list of the results of any
388 ;;; codegen-info args, and the remaining arguments are the runtime
389 ;;; arguments.
390 ;;;
391 ;;; We do various error checking now so that we don't bomb out with
392 ;;; a fatal error during IR2 conversion.
393 ;;;
394 ;;; KLUDGE: It's confusing having multiple names floating around for
395 ;;; nearly the same concept: PRIMITIVE, TEMPLATE, VOP. Now that CMU
396 ;;; CL's *PRIMITIVE-TRANSLATORS* stuff is gone, we could call
397 ;;; primitives VOPs, rename TEMPLATE to VOP-TEMPLATE, rename
398 ;;; BACKEND-TEMPLATE-NAMES to BACKEND-VOPS, and rename %PRIMITIVE to
399 ;;; VOP or %VOP.. -- WHN 2001-06-11
400 ;;; FIXME: Look at doing this ^, it doesn't look too hard actually.
401 (def-ir1-translator %primitive ((name &rest args) start next result)
402   (declare (type symbol name))
403   (let* ((template (or (gethash name *backend-template-names*)
404                        (bug "undefined primitive ~A" name)))
405          (required (length (template-arg-types template)))
406          (info (template-info-arg-count template))
407          (min (+ required info))
408          (nargs (length args)))
409     (if (template-more-args-type template)
410         (when (< nargs min)
411           (bug "Primitive ~A was called with ~R argument~:P, ~
412                 but wants at least ~R."
413                name
414                nargs
415                min))
416         (unless (= nargs min)
417           (bug "Primitive ~A was called with ~R argument~:P, ~
418                 but wants exactly ~R."
419                name
420                nargs
421                min)))
422
423     (when (eq (template-result-types template) :conditional)
424       (bug "%PRIMITIVE was used with a conditional template."))
425
426     (when (template-more-results-type template)
427       (bug "%PRIMITIVE was used with an unknown values template."))
428
429     (ir1-convert start next result
430                  `(%%primitive ',template
431                                ',(eval-info-args
432                                   (subseq args required min))
433                                ,@(subseq args 0 required)
434                                ,@(subseq args min)))))
435 \f
436 ;;;; QUOTE
437
438 (def-ir1-translator quote ((thing) start next result)
439   #!+sb-doc
440   "QUOTE value
441
442 Return VALUE without evaluating it."
443   (reference-constant start next result thing))
444 \f
445 ;;;; FUNCTION and NAMED-LAMBDA
446 (defun name-lambdalike (thing)
447   (ecase (car thing)
448     ((named-lambda)
449      (second thing))
450     ((lambda instance-lambda)
451      `(lambda ,(second thing)))
452     ((lambda-with-lexenv)'
453      `(lambda ,(fifth thing)))))
454
455 (defun fun-name-leaf (thing)
456   (if (consp thing)
457       (cond
458         ((member (car thing)
459                  '(lambda named-lambda instance-lambda lambda-with-lexenv))
460          (values (ir1-convert-lambdalike
461                   thing
462                   :debug-name (name-lambdalike thing))
463                  t))
464         ((legal-fun-name-p thing)
465          (values (find-lexically-apparent-fun
466                   thing "as the argument to FUNCTION")
467                  nil))
468         (t
469          (compiler-error "~S is not a legal function name." thing)))
470       (values (find-lexically-apparent-fun
471                thing "as the argument to FUNCTION")
472               nil)))
473
474 (def-ir1-translator %%allocate-closures ((&rest leaves) start next result)
475   (aver (eq result 'nil))
476   (let ((lambdas leaves))
477     (ir1-convert start next result `(%allocate-closures ',lambdas))
478     (let ((allocator (node-dest (ctran-next start))))
479       (dolist (lambda lambdas)
480         (setf (functional-allocator lambda) allocator)))))
481
482 (defmacro with-fun-name-leaf ((leaf thing start &key global) &body body)
483   `(multiple-value-bind (,leaf allocate-p)
484        (if ,global
485            (find-global-fun ,thing t)
486            (fun-name-leaf ,thing))
487      (if allocate-p
488          (let ((.new-start. (make-ctran)))
489            (ir1-convert ,start .new-start. nil `(%%allocate-closures ,leaf))
490            (let ((,start .new-start.))
491              ,@body))
492          (locally
493              ,@body))))
494
495 (def-ir1-translator function ((thing) start next result)
496   #!+sb-doc
497   "FUNCTION name
498
499 Return the lexically apparent definition of the function NAME. NAME may also
500 be a lambda expression."
501   (with-fun-name-leaf (leaf thing start)
502     (reference-leaf start next result leaf)))
503
504 ;;; Like FUNCTION, but ignores local definitions and inline
505 ;;; expansions, and doesn't nag about undefined functions.
506 ;;; Used for optimizing things like (FUNCALL 'FOO).
507 (def-ir1-translator global-function ((thing) start next result)
508   (with-fun-name-leaf (leaf thing start :global t)
509     (reference-leaf start next result leaf)))
510
511 (defun constant-global-fun-name (thing)
512   (let ((constantp (sb!xc:constantp thing)))
513     (and constantp
514          (let ((name (constant-form-value thing)))
515            (and (legal-fun-name-p name) name)))))
516 \f
517 ;;;; FUNCALL
518
519 ;;; FUNCALL is implemented on %FUNCALL, which can only call functions
520 ;;; (not symbols). %FUNCALL is used directly in some places where the
521 ;;; call should always be open-coded even if FUNCALL is :NOTINLINE.
522 (deftransform funcall ((function &rest args) * *)
523   (let ((arg-names (make-gensym-list (length args))))
524     `(lambda (function ,@arg-names)
525        (%funcall ,(if (csubtypep (lvar-type function)
526                                  (specifier-type 'function))
527                       'function
528                       '(%coerce-callable-to-fun function))
529                  ,@arg-names))))
530
531 (def-ir1-translator %funcall ((function &rest args) start next result)
532   (cond ((and (consp function) (eq (car function) 'function))
533          (with-fun-name-leaf (leaf (second function) start)
534            (ir1-convert start next result `(,leaf ,@args))))
535         ((and (consp function) (eq (car function) 'global-function))
536          (with-fun-name-leaf (leaf (second function) start :global t)
537            (ir1-convert start next result `(,leaf ,@args))))
538         (t
539          (let ((ctran (make-ctran))
540                (fun-lvar (make-lvar)))
541            (ir1-convert start ctran fun-lvar `(the function ,function))
542            (ir1-convert-combination-args fun-lvar ctran next result args)))))
543
544 ;;; This source transform exists to reduce the amount of work for the
545 ;;; compiler. If the called function is a FUNCTION form, then convert
546 ;;; directly to %FUNCALL, instead of waiting around for type
547 ;;; inference.
548 (define-source-transform funcall (function &rest args)
549   (if (and (consp function) (eq (car function) 'function))
550       `(%funcall ,function ,@args)
551       (let ((name (constant-global-fun-name function)))
552         (if name
553             `(%funcall (global-function ,name) ,@args)
554             (values nil t)))))
555
556 (deftransform %coerce-callable-to-fun ((thing) (function) *)
557   "optimize away possible call to FDEFINITION at runtime"
558   'thing)
559 \f
560 ;;;; LET and LET*
561 ;;;;
562 ;;;; (LET and LET* can't be implemented as macros due to the fact that
563 ;;;; any pervasive declarations also affect the evaluation of the
564 ;;;; arguments.)
565
566 ;;; Given a list of binding specifiers in the style of LET, return:
567 ;;;  1. The list of var structures for the variables bound.
568 ;;;  2. The initial value form for each variable.
569 ;;;
570 ;;; The variable names are checked for legality and globally special
571 ;;; variables are marked as such. Context is the name of the form, for
572 ;;; error reporting purposes.
573 (declaim (ftype (function (list symbol) (values list list))
574                 extract-let-vars))
575 (defun extract-let-vars (bindings context)
576   (collect ((vars)
577             (vals)
578             (names))
579     (flet ((get-var (name)
580              (varify-lambda-arg name
581                                 (if (eq context 'let*)
582                                     nil
583                                     (names)))))
584       (dolist (spec bindings)
585         (cond ((atom spec)
586                (let ((var (get-var spec)))
587                  (vars var)
588                  (names spec)
589                  (vals nil)))
590               (t
591                (unless (proper-list-of-length-p spec 1 2)
592                  (compiler-error "The ~S binding spec ~S is malformed."
593                                  context
594                                  spec))
595                (let* ((name (first spec))
596                       (var (get-var name)))
597                  (vars var)
598                  (names name)
599                  (vals (second spec)))))))
600     (dolist (name (names))
601       (when (eq (info :variable :kind name) :macro)
602         (program-assert-symbol-home-package-unlocked
603          :compile name "lexically binding symbol-macro ~A")))
604     (values (vars) (vals))))
605
606 (def-ir1-translator let ((bindings &body body) start next result)
607   #!+sb-doc
608   "LET ({(var [value]) | var}*) declaration* form*
609
610 During evaluation of the FORMS, bind the VARS to the result of evaluating the
611 VALUE forms. The variables are bound in parallel after all of the VALUES forms
612 have been evaluated."
613   (cond ((null bindings)
614          (ir1-translate-locally body start next result))
615         ((listp bindings)
616          (multiple-value-bind (forms decls)
617              (parse-body body :doc-string-allowed nil)
618            (multiple-value-bind (vars values) (extract-let-vars bindings 'let)
619              (binding* ((ctran (make-ctran))
620                         (fun-lvar (make-lvar))
621                         ((next result)
622                          (processing-decls (decls vars nil next result
623                                                   post-binding-lexenv)
624                            (let ((fun (ir1-convert-lambda-body
625                                        forms
626                                        vars
627                                        :post-binding-lexenv post-binding-lexenv
628                                        :debug-name (debug-name 'let bindings))))
629                              (reference-leaf start ctran fun-lvar fun))
630                            (values next result))))
631                (ir1-convert-combination-args fun-lvar ctran next result values)))))
632         (t
633          (compiler-error "Malformed LET bindings: ~S." bindings))))
634
635 (def-ir1-translator let* ((bindings &body body)
636                           start next result)
637   #!+sb-doc
638   "LET* ({(var [value]) | var}*) declaration* form*
639
640 Similar to LET, but the variables are bound sequentially, allowing each VALUE
641 form to reference any of the previous VARS."
642   (if (listp bindings)
643       (multiple-value-bind (forms decls)
644           (parse-body body :doc-string-allowed nil)
645         (multiple-value-bind (vars values) (extract-let-vars bindings 'let*)
646           (processing-decls (decls vars nil next result post-binding-lexenv)
647             (ir1-convert-aux-bindings start
648                                       next
649                                       result
650                                       forms
651                                       vars
652                                       values
653                                       post-binding-lexenv))))
654       (compiler-error "Malformed LET* bindings: ~S." bindings)))
655
656 ;;; logic shared between IR1 translators for LOCALLY, MACROLET,
657 ;;; and SYMBOL-MACROLET
658 ;;;
659 ;;; Note that all these things need to preserve toplevel-formness,
660 ;;; but we don't need to worry about that within an IR1 translator,
661 ;;; since toplevel-formness is picked off by PROCESS-TOPLEVEL-FOO
662 ;;; forms before we hit the IR1 transform level.
663 (defun ir1-translate-locally (body start next result &key vars funs)
664   (declare (type ctran start next) (type (or lvar null) result)
665            (type list body))
666   (multiple-value-bind (forms decls) (parse-body body :doc-string-allowed nil)
667     (processing-decls (decls vars funs next result)
668       (ir1-convert-progn-body start next result forms))))
669
670 (def-ir1-translator locally ((&body body) start next result)
671   #!+sb-doc
672   "LOCALLY declaration* form*
673
674 Sequentially evaluate the FORMS in a lexical environment where the the
675 DECLARATIONS have effect. If LOCALLY is a top level form, then the FORMS are
676 also processed as top level forms."
677   (ir1-translate-locally body start next result))
678 \f
679 ;;;; FLET and LABELS
680
681 ;;; Given a list of local function specifications in the style of
682 ;;; FLET, return lists of the function names and of the lambdas which
683 ;;; are their definitions.
684 ;;;
685 ;;; The function names are checked for legality. CONTEXT is the name
686 ;;; of the form, for error reporting.
687 (declaim (ftype (function (list symbol) (values list list)) extract-flet-vars))
688 (defun extract-flet-vars (definitions context)
689   (collect ((names)
690             (defs))
691     (dolist (def definitions)
692       (when (or (atom def) (< (length def) 2))
693         (compiler-error "The ~S definition spec ~S is malformed." context def))
694
695       (let ((name (first def)))
696         (check-fun-name name)
697         (when (fboundp name)
698           (program-assert-symbol-home-package-unlocked
699            :compile name "binding ~A as a local function"))
700         (names name)
701         (multiple-value-bind (forms decls) (parse-body (cddr def))
702           (defs `(lambda ,(second def)
703                    ,@decls
704                    (block ,(fun-name-block-name name)
705                      . ,forms))))))
706     (values (names) (defs))))
707
708 (defun ir1-convert-fbindings (start next result funs body)
709   (let ((ctran (make-ctran))
710         (dx-p (find-if #'leaf-dynamic-extent funs)))
711     (when dx-p
712       (ctran-starts-block ctran)
713       (ctran-starts-block next))
714     (ir1-convert start ctran nil `(%%allocate-closures ,@funs))
715     (cond (dx-p
716            (let* ((dummy (make-ctran))
717                   (entry (make-entry))
718                   (cleanup (make-cleanup :kind :dynamic-extent
719                                          :mess-up entry
720                                          :info (list (node-dest
721                                                       (ctran-next start))))))
722              (push entry (lambda-entries (lexenv-lambda *lexenv*)))
723              (setf (entry-cleanup entry) cleanup)
724              (link-node-to-previous-ctran entry ctran)
725              (use-ctran entry dummy)
726
727              (let ((*lexenv* (make-lexenv :cleanup cleanup)))
728                (ir1-convert-progn-body dummy next result body))))
729           (t (ir1-convert-progn-body ctran next result body)))))
730
731 (def-ir1-translator flet ((definitions &body body)
732                           start next result)
733   #!+sb-doc
734   "FLET ({(name lambda-list declaration* form*)}*) declaration* body-form*
735
736 Evaluate the BODY-FORMS with local function definitions. The bindings do
737 not enclose the definitions; any use of NAME in the FORMS will refer to the
738 lexically apparent function definition in the enclosing environment."
739   (multiple-value-bind (forms decls)
740       (parse-body body :doc-string-allowed nil)
741     (multiple-value-bind (names defs)
742         (extract-flet-vars definitions 'flet)
743       (let ((fvars (mapcar (lambda (n d)
744                              (ir1-convert-lambda d
745                                                  :source-name n
746                                                  :debug-name (debug-name 'flet n)))
747                            names defs)))
748         (processing-decls (decls nil fvars next result)
749           (let ((*lexenv* (make-lexenv :funs (pairlis names fvars))))
750             (ir1-convert-fbindings start next result fvars forms)))))))
751
752 (def-ir1-translator labels ((definitions &body body) start next result)
753   #!+sb-doc
754   "LABELS ({(name lambda-list declaration* form*)}*) declaration* body-form*
755
756 Evaluate the BODY-FORMS with local function definitions. The bindings enclose
757 the new definitions, so the defined functions can call themselves or each
758 other."
759   (multiple-value-bind (forms decls) (parse-body body :doc-string-allowed nil)
760     (multiple-value-bind (names defs)
761         (extract-flet-vars definitions 'labels)
762       (let* (;; dummy LABELS functions, to be used as placeholders
763              ;; during construction of real LABELS functions
764              (placeholder-funs (mapcar (lambda (name)
765                                          (make-functional
766                                           :%source-name name
767                                           :%debug-name (debug-name
768                                                         'labels-placeholder
769                                                         name)))
770                                        names))
771              ;; (like PAIRLIS but guaranteed to preserve ordering:)
772              (placeholder-fenv (mapcar #'cons names placeholder-funs))
773              ;; the real LABELS functions, compiled in a LEXENV which
774              ;; includes the dummy LABELS functions
775              (real-funs
776               (let ((*lexenv* (make-lexenv :funs placeholder-fenv)))
777                 (mapcar (lambda (name def)
778                           (ir1-convert-lambda def
779                                               :source-name name
780                                               :debug-name (debug-name 'labels name)))
781                         names defs))))
782
783         ;; Modify all the references to the dummy function leaves so
784         ;; that they point to the real function leaves.
785         (loop for real-fun in real-funs and
786               placeholder-cons in placeholder-fenv do
787               (substitute-leaf real-fun (cdr placeholder-cons))
788               (setf (cdr placeholder-cons) real-fun))
789
790         ;; Voila.
791         (processing-decls (decls nil real-funs next result)
792           (let ((*lexenv* (make-lexenv
793                            ;; Use a proper FENV here (not the
794                            ;; placeholder used earlier) so that if the
795                            ;; lexical environment is used for inline
796                            ;; expansion we'll get the right functions.
797                            :funs (pairlis names real-funs))))
798             (ir1-convert-fbindings start next result real-funs forms)))))))
799
800 \f
801 ;;;; the THE special operator, and friends
802
803 ;;; A logic shared among THE and TRULY-THE.
804 (defun the-in-policy (type value policy start next result)
805   (let ((type (if (ctype-p type) type
806                    (compiler-values-specifier-type type))))
807     (cond ((or (eq type *wild-type*)
808                (eq type *universal-type*)
809                (and (leaf-p value)
810                     (values-subtypep (make-single-value-type (leaf-type value))
811                                      type))
812                (and (sb!xc:constantp value)
813                     (ctypep (constant-form-value value)
814                             (single-value-type type))))
815            (ir1-convert start next result value))
816           (t (let ((value-ctran (make-ctran))
817                    (value-lvar (make-lvar)))
818                (ir1-convert start value-ctran value-lvar value)
819                (let ((cast (make-cast value-lvar type policy)))
820                  (link-node-to-previous-ctran cast value-ctran)
821                  (setf (lvar-dest value-lvar) cast)
822                  (use-continuation cast next result)))))))
823
824 ;;; Assert that FORM evaluates to the specified type (which may be a
825 ;;; VALUES type). TYPE may be a type specifier or (as a hack) a CTYPE.
826 (def-ir1-translator the ((type value) start next result)
827   (the-in-policy type value (lexenv-policy *lexenv*) start next result))
828
829 ;;; This is like the THE special form, except that it believes
830 ;;; whatever you tell it. It will never generate a type check, but
831 ;;; will cause a warning if the compiler can prove the assertion is
832 ;;; wrong.
833 (def-ir1-translator truly-the ((type value) start next result)
834   #!+sb-doc
835   ""
836   #-nil
837   (let ((type (coerce-to-values (compiler-values-specifier-type type)))
838         (old (when result (find-uses result))))
839     (ir1-convert start next result value)
840     (when result
841       (do-uses (use result)
842         (unless (memq use old)
843           (derive-node-type use type)))))
844   #+nil
845   (the-in-policy type value '((type-check . 0)) start cont))
846 \f
847 ;;;; SETQ
848
849 ;;; If there is a definition in LEXENV-VARS, just set that, otherwise
850 ;;; look at the global information. If the name is for a constant,
851 ;;; then error out.
852 (def-ir1-translator setq ((&whole source &rest things) start next result)
853   (let ((len (length things)))
854     (when (oddp len)
855       (compiler-error "odd number of args to SETQ: ~S" source))
856     (if (= len 2)
857         (let* ((name (first things))
858                (leaf (or (lexenv-find name vars)
859                          (find-free-var name))))
860           (etypecase leaf
861             (leaf
862              (when (constant-p leaf)
863                (compiler-error "~S is a constant and thus can't be set." name))
864              (when (lambda-var-p leaf)
865                (let ((home-lambda (ctran-home-lambda-or-null start)))
866                  (when home-lambda
867                    (pushnew leaf (lambda-calls-or-closes home-lambda))))
868                (when (lambda-var-ignorep leaf)
869                  ;; ANSI's definition of "Declaration IGNORE, IGNORABLE"
870                  ;; requires that this be a STYLE-WARNING, not a full warning.
871                  (compiler-style-warn
872                   "~S is being set even though it was declared to be ignored."
873                   name)))
874              (setq-var start next result leaf (second things)))
875             (cons
876              (aver (eq (car leaf) 'macro))
877              ;; FIXME: [Free] type declaration. -- APD, 2002-01-26
878              (ir1-convert start next result
879                           `(setf ,(cdr leaf) ,(second things))))
880             (heap-alien-info
881              (ir1-convert start next result
882                           `(%set-heap-alien ',leaf ,(second things))))))
883         (collect ((sets))
884           (do ((thing things (cddr thing)))
885               ((endp thing)
886                (ir1-convert-progn-body start next result (sets)))
887             (sets `(setq ,(first thing) ,(second thing))))))))
888
889 ;;; This is kind of like REFERENCE-LEAF, but we generate a SET node.
890 ;;; This should only need to be called in SETQ.
891 (defun setq-var (start next result var value)
892   (declare (type ctran start next) (type (or lvar null) result)
893            (type basic-var var))
894   (let ((dest-ctran (make-ctran))
895         (dest-lvar (make-lvar))
896         (type (or (lexenv-find var type-restrictions)
897                   (leaf-type var))))
898     (ir1-convert start dest-ctran dest-lvar `(the ,type ,value))
899     (let ((res (make-set :var var :value dest-lvar)))
900       (setf (lvar-dest dest-lvar) res)
901       (setf (leaf-ever-used var) t)
902       (push res (basic-var-sets var))
903       (link-node-to-previous-ctran res dest-ctran)
904       (use-continuation res next result))))
905 \f
906 ;;;; CATCH, THROW and UNWIND-PROTECT
907
908 ;;; We turn THROW into a MULTIPLE-VALUE-CALL of a magical function,
909 ;;; since as as far as IR1 is concerned, it has no interesting
910 ;;; properties other than receiving multiple-values.
911 (def-ir1-translator throw ((tag result) start next result-lvar)
912   #!+sb-doc
913   "THROW tag form
914
915 Do a non-local exit, return the values of FORM from the CATCH whose tag is EQ
916 to TAG."
917   (ir1-convert start next result-lvar
918                `(multiple-value-call #'%throw ,tag ,result)))
919
920 ;;; This is a special special form used to instantiate a cleanup as
921 ;;; the current cleanup within the body. KIND is the kind of cleanup
922 ;;; to make, and MESS-UP is a form that does the mess-up action. We
923 ;;; make the MESS-UP be the USE of the MESS-UP form's continuation,
924 ;;; and introduce the cleanup into the lexical environment. We
925 ;;; back-patch the ENTRY-CLEANUP for the current cleanup to be the new
926 ;;; cleanup, since this inner cleanup is the interesting one.
927 (def-ir1-translator %within-cleanup
928     ((kind mess-up &body body) start next result)
929   (let ((dummy (make-ctran))
930         (dummy2 (make-ctran)))
931     (ir1-convert start dummy nil mess-up)
932     (let* ((mess-node (ctran-use dummy))
933            (cleanup (make-cleanup :kind kind
934                                   :mess-up mess-node))
935            (old-cup (lexenv-cleanup *lexenv*))
936            (*lexenv* (make-lexenv :cleanup cleanup)))
937       (setf (entry-cleanup (cleanup-mess-up old-cup)) cleanup)
938       (ir1-convert dummy dummy2 nil '(%cleanup-point))
939       (ir1-convert-progn-body dummy2 next result body))))
940
941 ;;; This is a special special form that makes an "escape function"
942 ;;; which returns unknown values from named block. We convert the
943 ;;; function, set its kind to :ESCAPE, and then reference it. The
944 ;;; :ESCAPE kind indicates that this function's purpose is to
945 ;;; represent a non-local control transfer, and that it might not
946 ;;; actually have to be compiled.
947 ;;;
948 ;;; Note that environment analysis replaces references to escape
949 ;;; functions with references to the corresponding NLX-INFO structure.
950 (def-ir1-translator %escape-fun ((tag) start next result)
951   (let ((fun (let ((*allow-instrumenting* nil))
952                (ir1-convert-lambda
953                 `(lambda ()
954                    (return-from ,tag (%unknown-values)))
955                 :debug-name (debug-name 'escape-fun tag))))
956         (ctran (make-ctran)))
957     (setf (functional-kind fun) :escape)
958     (ir1-convert start ctran nil `(%%allocate-closures ,fun))
959     (reference-leaf ctran next result fun)))
960
961 ;;; Yet another special special form. This one looks up a local
962 ;;; function and smashes it to a :CLEANUP function, as well as
963 ;;; referencing it.
964 (def-ir1-translator %cleanup-fun ((name) start next result)
965   ;; FIXME: Should this not be :TEST #'EQUAL? What happens to
966   ;; (SETF FOO) here?
967   (let ((fun (lexenv-find name funs)))
968     (aver (lambda-p fun))
969     (setf (functional-kind fun) :cleanup)
970     (reference-leaf start next result fun)))
971
972 (def-ir1-translator catch ((tag &body body) start next result)
973   #!+sb-doc
974   "CATCH tag form*
975
976 Evaluate TAG and instantiate it as a catcher while the body forms are
977 evaluated in an implicit PROGN. If a THROW is done to TAG within the dynamic
978 scope of the body, then control will be transferred to the end of the body and
979 the thrown values will be returned."
980   ;; We represent the possibility of the control transfer by making an
981   ;; "escape function" that does a lexical exit, and instantiate the
982   ;; cleanup using %WITHIN-CLEANUP.
983   (ir1-convert
984    start next result
985    (with-unique-names (exit-block)
986      `(block ,exit-block
987         (%within-cleanup
988          :catch (%catch (%escape-fun ,exit-block) ,tag)
989          ,@body)))))
990
991 (def-ir1-translator unwind-protect
992     ((protected &body cleanup) start next result)
993   #!+sb-doc
994   "UNWIND-PROTECT protected cleanup*
995
996 Evaluate the form PROTECTED, returning its values. The CLEANUP forms are
997 evaluated whenever the dynamic scope of the PROTECTED form is exited (either
998 due to normal completion or a non-local exit such as THROW)."
999   ;; UNWIND-PROTECT is similar to CATCH, but hairier. We make the
1000   ;; cleanup forms into a local function so that they can be referenced
1001   ;; both in the case where we are unwound and in any local exits. We
1002   ;; use %CLEANUP-FUN on this to indicate that reference by
1003   ;; %UNWIND-PROTECT isn't "real", and thus doesn't cause creation of
1004   ;; an XEP.
1005   (ir1-convert
1006    start next result
1007    (with-unique-names (cleanup-fun drop-thru-tag exit-tag next start count)
1008      `(flet ((,cleanup-fun () ,@cleanup nil))
1009         ;; FIXME: If we ever get DYNAMIC-EXTENT working, then
1010         ;; ,CLEANUP-FUN should probably be declared DYNAMIC-EXTENT,
1011         ;; and something can be done to make %ESCAPE-FUN have
1012         ;; dynamic extent too.
1013         (block ,drop-thru-tag
1014           (multiple-value-bind (,next ,start ,count)
1015               (block ,exit-tag
1016                 (%within-cleanup
1017                     :unwind-protect
1018                     (%unwind-protect (%escape-fun ,exit-tag)
1019                                      (%cleanup-fun ,cleanup-fun))
1020                   (return-from ,drop-thru-tag ,protected)))
1021             (,cleanup-fun)
1022             (%continue-unwind ,next ,start ,count)))))))
1023 \f
1024 ;;;; multiple-value stuff
1025
1026 (def-ir1-translator multiple-value-call ((fun &rest args) start next result)
1027   #!+sb-doc
1028   "MULTIPLE-VALUE-CALL function values-form*
1029
1030 Call FUNCTION, passing all the values of each VALUES-FORM as arguments,
1031 values from the first VALUES-FORM making up the first argument, etc."
1032   (let* ((ctran (make-ctran))
1033          (fun-lvar (make-lvar))
1034          (node (if args
1035                    ;; If there are arguments, MULTIPLE-VALUE-CALL
1036                    ;; turns into an MV-COMBINATION.
1037                    (make-mv-combination fun-lvar)
1038                    ;; If there are no arguments, then we convert to a
1039                    ;; normal combination, ensuring that a MV-COMBINATION
1040                    ;; always has at least one argument. This can be
1041                    ;; regarded as an optimization, but it is more
1042                    ;; important for simplifying compilation of
1043                    ;; MV-COMBINATIONS.
1044                    (make-combination fun-lvar))))
1045     (ir1-convert start ctran fun-lvar
1046                  (if (and (consp fun) (eq (car fun) 'function))
1047                      fun
1048                      (let ((name (constant-global-fun-name fun)))
1049                        (if name
1050                            `(global-function ,name)
1051                            `(%coerce-callable-to-fun ,fun)))))
1052     (setf (lvar-dest fun-lvar) node)
1053     (collect ((arg-lvars))
1054       (let ((this-start ctran))
1055         (dolist (arg args)
1056           (let ((this-ctran (make-ctran))
1057                 (this-lvar (make-lvar node)))
1058             (ir1-convert this-start this-ctran this-lvar arg)
1059             (setq this-start this-ctran)
1060             (arg-lvars this-lvar)))
1061         (link-node-to-previous-ctran node this-start)
1062         (use-continuation node next result)
1063         (setf (basic-combination-args node) (arg-lvars))))))
1064
1065 (def-ir1-translator multiple-value-prog1
1066     ((values-form &rest forms) start next result)
1067   #!+sb-doc
1068   "MULTIPLE-VALUE-PROG1 values-form form*
1069
1070 Evaluate VALUES-FORM and then the FORMS, but return all the values of
1071 VALUES-FORM."
1072   (let ((dummy (make-ctran)))
1073     (ctran-starts-block dummy)
1074     (ir1-convert start dummy result values-form)
1075     (ir1-convert-progn-body dummy next nil forms)))
1076 \f
1077 ;;;; interface to defining macros
1078
1079 ;;; Old CMUCL comment:
1080 ;;;
1081 ;;;   Return a new source path with any stuff intervening between the
1082 ;;;   current path and the first form beginning with NAME stripped
1083 ;;;   off.  This is used to hide the guts of DEFmumble macros to
1084 ;;;   prevent annoying error messages.
1085 ;;;
1086 ;;; Now that we have implementations of DEFmumble macros in terms of
1087 ;;; EVAL-WHEN, this function is no longer used.  However, it might be
1088 ;;; worth figuring out why it was used, and maybe doing analogous
1089 ;;; munging to the functions created in the expanders for the macros.
1090 (defun revert-source-path (name)
1091   (do ((path *current-path* (cdr path)))
1092       ((null path) *current-path*)
1093     (let ((first (first path)))
1094       (when (or (eq first name)
1095                 (eq first 'original-source-start))
1096         (return path)))))