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