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