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