594999d997a9e0bd033bc346c38dd68bc870dfec
[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          (ir1-convert-lambdalike
444                           thing
445                           :debug-name (debug-namify "#'" thing)))
446         ((legal-fun-name-p thing)
447          (find-lexically-apparent-fun
448                      thing "as the argument to FUNCTION"))
449         (t
450          (compiler-error "~S is not a legal function name." thing)))
451       (find-lexically-apparent-fun
452        thing "as the argument to FUNCTION")))
453
454 (def-ir1-translator function ((thing) start next result)
455   #!+sb-doc
456   "FUNCTION Name
457   Return the lexically apparent definition of the function Name. Name may also
458   be a lambda expression."
459   (reference-leaf start next result (fun-name-leaf thing)))
460 \f
461 ;;;; FUNCALL
462
463 ;;; FUNCALL is implemented on %FUNCALL, which can only call functions
464 ;;; (not symbols). %FUNCALL is used directly in some places where the
465 ;;; call should always be open-coded even if FUNCALL is :NOTINLINE.
466 (deftransform funcall ((function &rest args) * *)
467   (let ((arg-names (make-gensym-list (length args))))
468     `(lambda (function ,@arg-names)
469        (%funcall ,(if (csubtypep (lvar-type function)
470                                  (specifier-type 'function))
471                       'function
472                       '(%coerce-callable-to-fun function))
473                  ,@arg-names))))
474
475 (def-ir1-translator %funcall ((function &rest args) start next result)
476   (if (and (consp function) (eq (car function) 'function))
477       (ir1-convert start next result
478                    `(,(fun-name-leaf (second function)) ,@args))
479       (let ((ctran (make-ctran))
480             (fun-lvar (make-lvar)))
481         (ir1-convert start ctran fun-lvar `(the function ,function))
482         (ir1-convert-combination-args fun-lvar ctran next result args))))
483
484 ;;; This source transform exists to reduce the amount of work for the
485 ;;; compiler. If the called function is a FUNCTION form, then convert
486 ;;; directly to %FUNCALL, instead of waiting around for type
487 ;;; inference.
488 (define-source-transform funcall (function &rest args)
489   (if (and (consp function) (eq (car function) 'function))
490       `(%funcall ,function ,@args)
491       (values nil t)))
492
493 (deftransform %coerce-callable-to-fun ((thing) (function) *)
494   "optimize away possible call to FDEFINITION at runtime"
495   'thing)
496 \f
497 ;;;; LET and LET*
498 ;;;;
499 ;;;; (LET and LET* can't be implemented as macros due to the fact that
500 ;;;; any pervasive declarations also affect the evaluation of the
501 ;;;; arguments.)
502
503 ;;; Given a list of binding specifiers in the style of LET, return:
504 ;;;  1. The list of var structures for the variables bound.
505 ;;;  2. The initial value form for each variable.
506 ;;;
507 ;;; The variable names are checked for legality and globally special
508 ;;; variables are marked as such. Context is the name of the form, for
509 ;;; error reporting purposes.
510 (declaim (ftype (function (list symbol) (values list list))
511                 extract-let-vars))
512 (defun extract-let-vars (bindings context)
513   (collect ((vars)
514             (vals)
515             (names))
516     (flet ((get-var (name)
517              (varify-lambda-arg name
518                                 (if (eq context 'let*)
519                                     nil
520                                     (names)))))
521       (dolist (spec bindings)
522         (cond ((atom spec)
523                (let ((var (get-var spec)))
524                  (vars var)
525                  (names spec)
526                  (vals nil)))
527               (t
528                (unless (proper-list-of-length-p spec 1 2)
529                  (compiler-error "The ~S binding spec ~S is malformed."
530                                  context
531                                  spec))
532                (let* ((name (first spec))
533                       (var (get-var name)))
534                  (vars var)
535                  (names name)
536                  (vals (second spec)))))))
537     (dolist (name (names))
538       (when (eq (info :variable :kind name) :macro)
539         (compiler-assert-symbol-home-package-unlocked
540          name "lexically binding symbol-macro ~A")))
541     (values (vars) (vals))))
542
543 (def-ir1-translator let ((bindings &body body) start next result)
544   #!+sb-doc
545   "LET ({(Var [Value]) | Var}*) Declaration* Form*
546   During evaluation of the Forms, bind the Vars to the result of evaluating the
547   Value forms. The variables are bound in parallel after all of the Values are
548   evaluated."
549   (cond ((null bindings)
550          (ir1-translate-locally body start next result))
551         ((listp bindings)
552          (multiple-value-bind (forms decls)
553              (parse-body body :doc-string-allowed nil)
554            (multiple-value-bind (vars values) (extract-let-vars bindings 'let)
555              (binding* ((ctran (make-ctran))
556                         (fun-lvar (make-lvar))
557                         ((next result)
558                          (processing-decls (decls vars nil next result)
559                                            (let ((fun (ir1-convert-lambda-body
560                                                        forms
561                                                        vars
562                                                        :debug-name (debug-namify "LET S"
563                                                                                  bindings))))
564                                              (reference-leaf start ctran fun-lvar fun))
565                                            (values next result))))
566                        (ir1-convert-combination-args fun-lvar ctran next result values)))))
567         (t
568          (compiler-error "Malformed LET bindings: ~S." bindings))))
569
570 (def-ir1-translator let* ((bindings &body body)
571                           start next result)
572   #!+sb-doc
573   "LET* ({(Var [Value]) | Var}*) Declaration* Form*
574   Similar to LET, but the variables are bound sequentially, allowing each Value
575   form to reference any of the previous Vars."
576   (if (listp bindings)
577       (multiple-value-bind (forms decls)
578           (parse-body body :doc-string-allowed nil)
579         (multiple-value-bind (vars values) (extract-let-vars bindings 'let*)
580           (processing-decls (decls vars nil start next)
581                             (ir1-convert-aux-bindings start 
582                                                       next 
583                                                       result
584                                                       forms
585                                                       vars 
586                                                       values))))
587       (compiler-error "Malformed LET* bindings: ~S." bindings)))
588   
589 ;;; logic shared between IR1 translators for LOCALLY, MACROLET,
590 ;;; and SYMBOL-MACROLET
591 ;;;
592 ;;; Note that all these things need to preserve toplevel-formness,
593 ;;; but we don't need to worry about that within an IR1 translator,
594 ;;; since toplevel-formness is picked off by PROCESS-TOPLEVEL-FOO
595 ;;; forms before we hit the IR1 transform level.
596 (defun ir1-translate-locally (body start next result &key vars funs)
597   (declare (type ctran start next) (type (or lvar null) result)
598            (type list body))
599   (multiple-value-bind (forms decls) (parse-body body :doc-string-allowed nil)
600     (processing-decls (decls vars funs next result)
601       (ir1-convert-progn-body start next result forms))))
602
603 (def-ir1-translator locally ((&body body) start next result)
604   #!+sb-doc
605   "LOCALLY Declaration* Form*
606   Sequentially evaluate the Forms in a lexical environment where the
607   the Declarations have effect. If LOCALLY is a top level form, then
608   the Forms are also processed as top level forms."
609   (ir1-translate-locally body start next result))
610 \f
611 ;;;; FLET and LABELS
612
613 ;;; Given a list of local function specifications in the style of
614 ;;; FLET, return lists of the function names and of the lambdas which
615 ;;; are their definitions.
616 ;;;
617 ;;; The function names are checked for legality. CONTEXT is the name
618 ;;; of the form, for error reporting.
619 (declaim (ftype (function (list symbol) (values list list)) extract-flet-vars))
620 (defun extract-flet-vars (definitions context)
621   (collect ((names)
622             (defs))
623     (dolist (def definitions)
624       (when (or (atom def) (< (length def) 2))
625         (compiler-error "The ~S definition spec ~S is malformed." context def))
626
627       (let ((name (first def)))
628         (check-fun-name name)
629         (when (fboundp name)
630           (compiler-assert-symbol-home-package-unlocked
631            name "binding ~A as a local function"))
632         (names name)
633         (multiple-value-bind (forms decls) (parse-body (cddr def))
634           (defs `(lambda ,(second def)
635                    ,@decls
636                    (block ,(fun-name-block-name name)
637                      . ,forms))))))
638     (values (names) (defs))))
639
640 (def-ir1-translator flet ((definitions &body body)
641                           start next result)
642   #!+sb-doc
643   "FLET ({(Name Lambda-List Declaration* Form*)}*) Declaration* Body-Form*
644   Evaluate the Body-Forms with some local function definitions. The bindings
645   do not enclose the definitions; any use of Name in the Forms will refer to
646   the lexically apparent function definition in the enclosing environment."
647   (multiple-value-bind (forms decls)
648       (parse-body body :doc-string-allowed nil)
649     (multiple-value-bind (names defs)
650         (extract-flet-vars definitions 'flet)
651       (let ((fvars (mapcar (lambda (n d)
652                              (ir1-convert-lambda d
653                                                  :source-name n
654                                                  :debug-name (debug-namify
655                                                               "FLET " n)))
656                            names defs)))
657         (processing-decls (decls nil fvars next result)
658           (let ((*lexenv* (make-lexenv :funs (pairlis names fvars))))
659             (ir1-convert-progn-body start 
660                                     next 
661                                     result
662                                     forms)))))))
663
664 (def-ir1-translator labels ((definitions &body body) start next result)
665   #!+sb-doc
666   "LABELS ({(Name Lambda-List Declaration* Form*)}*) Declaration* Body-Form*
667   Evaluate the Body-Forms with some local function definitions. The bindings
668   enclose the new definitions, so the defined functions can call themselves or
669   each other."
670   (multiple-value-bind (forms decls) (parse-body body :doc-string-allowed nil)
671     (multiple-value-bind (names defs)
672         (extract-flet-vars definitions 'labels)
673       (let* (;; dummy LABELS functions, to be used as placeholders
674              ;; during construction of real LABELS functions
675              (placeholder-funs (mapcar (lambda (name)
676                                          (make-functional
677                                           :%source-name name
678                                           :%debug-name (debug-namify
679                                                         "LABELS placeholder "
680                                                         name)))
681                                        names))
682              ;; (like PAIRLIS but guaranteed to preserve ordering:)
683              (placeholder-fenv (mapcar #'cons names placeholder-funs))
684              ;; the real LABELS functions, compiled in a LEXENV which
685              ;; includes the dummy LABELS functions
686              (real-funs
687               (let ((*lexenv* (make-lexenv :funs placeholder-fenv)))
688                 (mapcar (lambda (name def)
689                           (ir1-convert-lambda def
690                                               :source-name name
691                                               :debug-name (debug-namify
692                                                            "LABELS " name)))
693                         names defs))))
694         
695         ;; Modify all the references to the dummy function leaves so
696         ;; that they point to the real function leaves.
697         (loop for real-fun in real-funs and
698               placeholder-cons in placeholder-fenv do
699               (substitute-leaf real-fun (cdr placeholder-cons))
700               (setf (cdr placeholder-cons) real-fun))
701         
702         ;; Voila.
703         (processing-decls (decls nil real-funs next result)
704           (let ((*lexenv* (make-lexenv
705                            ;; Use a proper FENV here (not the
706                            ;; placeholder used earlier) so that if the
707                            ;; lexical environment is used for inline
708                            ;; expansion we'll get the right functions.
709                            :funs (pairlis names real-funs))))
710             (ir1-convert-progn-body start 
711                                     next 
712                                     result
713                                     forms)))))))
714
715 \f
716 ;;;; the THE special operator, and friends
717
718 ;;; A logic shared among THE and TRULY-THE.
719 (defun the-in-policy (type value policy start next result)
720   (let ((type (if (ctype-p type) type
721                    (compiler-values-specifier-type type))))
722     (cond ((or (eq type *wild-type*)
723                (eq type *universal-type*)
724                (and (leaf-p value)
725                     (values-subtypep (make-single-value-type (leaf-type value))
726                                      type))
727                (and (sb!xc:constantp value)
728                     (ctypep (constant-form-value value)
729                             (single-value-type type))))
730            (ir1-convert start next result value))
731           (t (let ((value-ctran (make-ctran))
732                    (value-lvar (make-lvar)))
733                (ir1-convert start value-ctran value-lvar value)
734                (let ((cast (make-cast value-lvar type policy)))
735                  (link-node-to-previous-ctran cast value-ctran)
736                  (setf (lvar-dest value-lvar) cast)
737                  (use-continuation cast next result)))))))
738
739 ;;; Assert that FORM evaluates to the specified type (which may be a
740 ;;; VALUES type). TYPE may be a type specifier or (as a hack) a CTYPE.
741 (def-ir1-translator the ((type value) start next result)
742   (the-in-policy type value (lexenv-policy *lexenv*) start next result))
743
744 ;;; This is like the THE special form, except that it believes
745 ;;; whatever you tell it. It will never generate a type check, but
746 ;;; will cause a warning if the compiler can prove the assertion is
747 ;;; wrong.
748 (def-ir1-translator truly-the ((type value) start next result)
749   #!+sb-doc
750   ""
751   #-nil
752   (let ((type (coerce-to-values (compiler-values-specifier-type type)))
753         (old (when result (find-uses result))))
754     (ir1-convert start next result value)
755     (when result
756       (do-uses (use result)
757         (unless (memq use old)
758           (derive-node-type use type)))))
759   #+nil
760   (the-in-policy type value '((type-check . 0)) start cont))
761 \f
762 ;;;; SETQ
763
764 ;;; If there is a definition in LEXENV-VARS, just set that, otherwise
765 ;;; look at the global information. If the name is for a constant,
766 ;;; then error out.
767 (def-ir1-translator setq ((&whole source &rest things) start next result)
768   (let ((len (length things)))
769     (when (oddp len)
770       (compiler-error "odd number of args to SETQ: ~S" source))
771     (if (= len 2)
772         (let* ((name (first things))
773                (leaf (or (lexenv-find name vars)
774                          (find-free-var name))))
775           (etypecase leaf
776             (leaf
777              (when (constant-p leaf)
778                (compiler-error "~S is a constant and thus can't be set." name))
779              (when (lambda-var-p leaf)
780                (let ((home-lambda (ctran-home-lambda-or-null start)))
781                  (when home-lambda
782                    (pushnew leaf (lambda-calls-or-closes home-lambda))))
783                (when (lambda-var-ignorep leaf)
784                  ;; ANSI's definition of "Declaration IGNORE, IGNORABLE"
785                  ;; requires that this be a STYLE-WARNING, not a full warning.
786                  (compiler-style-warn
787                   "~S is being set even though it was declared to be ignored."
788                   name)))
789              (setq-var start next result leaf (second things)))
790             (cons
791              (aver (eq (car leaf) 'MACRO))
792              ;; FIXME: [Free] type declaration. -- APD, 2002-01-26
793              (ir1-convert start next result
794                           `(setf ,(cdr leaf) ,(second things))))
795             (heap-alien-info
796              (ir1-convert start next result
797                           `(%set-heap-alien ',leaf ,(second things))))))
798         (collect ((sets))
799           (do ((thing things (cddr thing)))
800               ((endp thing)
801                (ir1-convert-progn-body start next result (sets)))
802             (sets `(setq ,(first thing) ,(second thing))))))))
803
804 ;;; This is kind of like REFERENCE-LEAF, but we generate a SET node.
805 ;;; This should only need to be called in SETQ.
806 (defun setq-var (start next result var value)
807   (declare (type ctran start next) (type (or lvar null) result)
808            (type basic-var var))
809   (let ((dest-ctran (make-ctran))
810         (dest-lvar (make-lvar))
811         (type (or (lexenv-find var type-restrictions)
812                   (leaf-type var))))
813     (ir1-convert start dest-ctran dest-lvar `(the ,type ,value))
814     (let ((res (make-set :var var :value dest-lvar)))
815       (setf (lvar-dest dest-lvar) res)
816       (setf (leaf-ever-used var) t)
817       (push res (basic-var-sets var))
818       (link-node-to-previous-ctran res dest-ctran)
819       (use-continuation res next result))))
820 \f
821 ;;;; CATCH, THROW and UNWIND-PROTECT
822
823 ;;; We turn THROW into a MULTIPLE-VALUE-CALL of a magical function,
824 ;;; since as as far as IR1 is concerned, it has no interesting
825 ;;; properties other than receiving multiple-values.
826 (def-ir1-translator throw ((tag result) start next result-lvar)
827   #!+sb-doc
828   "Throw Tag Form
829   Do a non-local exit, return the values of Form from the CATCH whose tag
830   evaluates to the same thing as Tag."
831   (ir1-convert start next result-lvar
832                `(multiple-value-call #'%throw ,tag ,result)))
833
834 ;;; This is a special special form used to instantiate a cleanup as
835 ;;; the current cleanup within the body. KIND is the kind of cleanup
836 ;;; to make, and MESS-UP is a form that does the mess-up action. We
837 ;;; make the MESS-UP be the USE of the MESS-UP form's continuation,
838 ;;; and introduce the cleanup into the lexical environment. We
839 ;;; back-patch the ENTRY-CLEANUP for the current cleanup to be the new
840 ;;; cleanup, since this inner cleanup is the interesting one.
841 (def-ir1-translator %within-cleanup
842     ((kind mess-up &body body) start next result)
843   (let ((dummy (make-ctran))
844         (dummy2 (make-ctran)))
845     (ir1-convert start dummy nil mess-up)
846     (let* ((mess-node (ctran-use dummy))
847            (cleanup (make-cleanup :kind kind
848                                   :mess-up mess-node))
849            (old-cup (lexenv-cleanup *lexenv*))
850            (*lexenv* (make-lexenv :cleanup cleanup)))
851       (setf (entry-cleanup (cleanup-mess-up old-cup)) cleanup)
852       (ir1-convert dummy dummy2 nil '(%cleanup-point))
853       (ir1-convert-progn-body dummy2 next result body))))
854
855 ;;; This is a special special form that makes an "escape function"
856 ;;; which returns unknown values from named block. We convert the
857 ;;; function, set its kind to :ESCAPE, and then reference it. The
858 ;;; :ESCAPE kind indicates that this function's purpose is to
859 ;;; represent a non-local control transfer, and that it might not
860 ;;; actually have to be compiled.
861 ;;;
862 ;;; Note that environment analysis replaces references to escape
863 ;;; functions with references to the corresponding NLX-INFO structure.
864 (def-ir1-translator %escape-fun ((tag) start next result)
865   (let ((fun (let ((*allow-instrumenting* nil))
866                (ir1-convert-lambda
867                 `(lambda ()
868                    (return-from ,tag (%unknown-values)))
869                 :debug-name (debug-namify "escape function for " tag)))))
870     (setf (functional-kind fun) :escape)
871     (reference-leaf start next result fun)))
872
873 ;;; Yet another special special form. This one looks up a local
874 ;;; function and smashes it to a :CLEANUP function, as well as
875 ;;; referencing it.
876 (def-ir1-translator %cleanup-fun ((name) start next result)
877   (let ((fun (lexenv-find name funs)))
878     (aver (lambda-p fun))
879     (setf (functional-kind fun) :cleanup)
880     (reference-leaf start next result fun)))
881
882 (def-ir1-translator catch ((tag &body body) start next result)
883   #!+sb-doc
884   "Catch Tag Form*
885   Evaluate TAG and instantiate it as a catcher while the body forms are
886   evaluated in an implicit PROGN. If a THROW is done to TAG within the dynamic
887   scope of the body, then control will be transferred to the end of the body
888   and the thrown values will be returned."
889   ;; We represent the possibility of the control transfer by making an
890   ;; "escape function" that does a lexical exit, and instantiate the
891   ;; cleanup using %WITHIN-CLEANUP.
892   (ir1-convert
893    start next result
894    (with-unique-names (exit-block)
895      `(block ,exit-block
896         (%within-cleanup
897          :catch (%catch (%escape-fun ,exit-block) ,tag)
898          ,@body)))))
899
900 (def-ir1-translator unwind-protect
901     ((protected &body cleanup) start next result)
902   #!+sb-doc
903   "Unwind-Protect Protected Cleanup*
904   Evaluate the form PROTECTED, returning its values. The CLEANUP forms are
905   evaluated whenever the dynamic scope of the PROTECTED form is exited (either
906   due to normal completion or a non-local exit such as THROW)."
907   ;; UNWIND-PROTECT is similar to CATCH, but hairier. We make the
908   ;; cleanup forms into a local function so that they can be referenced
909   ;; both in the case where we are unwound and in any local exits. We
910   ;; use %CLEANUP-FUN on this to indicate that reference by
911   ;; %UNWIND-PROTECT isn't "real", and thus doesn't cause creation of
912   ;; an XEP.
913   (ir1-convert
914    start next result
915    (with-unique-names (cleanup-fun drop-thru-tag exit-tag next start count)
916      `(flet ((,cleanup-fun () ,@cleanup nil))
917         ;; FIXME: If we ever get DYNAMIC-EXTENT working, then
918         ;; ,CLEANUP-FUN should probably be declared DYNAMIC-EXTENT,
919         ;; and something can be done to make %ESCAPE-FUN have
920         ;; dynamic extent too.
921         (block ,drop-thru-tag
922           (multiple-value-bind (,next ,start ,count)
923               (block ,exit-tag
924                 (%within-cleanup
925                     :unwind-protect
926                     (%unwind-protect (%escape-fun ,exit-tag)
927                                      (%cleanup-fun ,cleanup-fun))
928                   (return-from ,drop-thru-tag ,protected)))
929             (,cleanup-fun)
930             (%continue-unwind ,next ,start ,count)))))))
931 \f
932 ;;;; multiple-value stuff
933
934 (def-ir1-translator multiple-value-call ((fun &rest args) start next result)
935   #!+sb-doc
936   "MULTIPLE-VALUE-CALL Function Values-Form*
937   Call FUNCTION, passing all the values of each VALUES-FORM as arguments,
938   values from the first VALUES-FORM making up the first argument, etc."
939   (let* ((ctran (make-ctran))
940          (fun-lvar (make-lvar))
941          (node (if args
942                    ;; If there are arguments, MULTIPLE-VALUE-CALL
943                    ;; turns into an MV-COMBINATION.
944                    (make-mv-combination fun-lvar)
945                    ;; If there are no arguments, then we convert to a
946                    ;; normal combination, ensuring that a MV-COMBINATION
947                    ;; always has at least one argument. This can be
948                    ;; regarded as an optimization, but it is more
949                    ;; important for simplifying compilation of
950                    ;; MV-COMBINATIONS.
951                    (make-combination fun-lvar))))
952     (ir1-convert start ctran fun-lvar
953                  (if (and (consp fun) (eq (car fun) 'function))
954                      fun
955                      `(%coerce-callable-to-fun ,fun)))
956     (setf (lvar-dest fun-lvar) node)
957     (collect ((arg-lvars))
958       (let ((this-start ctran))
959         (dolist (arg args)
960           (let ((this-ctran (make-ctran))
961                 (this-lvar (make-lvar node)))
962             (ir1-convert this-start this-ctran this-lvar arg)
963             (setq this-start this-ctran)
964             (arg-lvars this-lvar)))
965         (link-node-to-previous-ctran node this-start)
966         (use-continuation node next result)
967         (setf (basic-combination-args node) (arg-lvars))))))
968
969 (def-ir1-translator multiple-value-prog1
970     ((values-form &rest forms) start next result)
971   #!+sb-doc
972   "MULTIPLE-VALUE-PROG1 Values-Form Form*
973   Evaluate Values-Form and then the Forms, but return all the values of
974   Values-Form."
975   (let ((dummy (make-ctran)))
976     (ctran-starts-block dummy)
977     (ir1-convert start dummy result values-form)
978     (ir1-convert-progn-body dummy next nil forms)))
979 \f
980 ;;;; interface to defining macros
981
982 ;;; Old CMUCL comment:
983 ;;;
984 ;;;   Return a new source path with any stuff intervening between the
985 ;;;   current path and the first form beginning with NAME stripped
986 ;;;   off.  This is used to hide the guts of DEFmumble macros to
987 ;;;   prevent annoying error messages.
988 ;;;
989 ;;; Now that we have implementations of DEFmumble macros in terms of
990 ;;; EVAL-WHEN, this function is no longer used.  However, it might be
991 ;;; worth figuring out why it was used, and maybe doing analogous
992 ;;; munging to the functions created in the expanders for the macros.
993 (defun revert-source-path (name)
994   (do ((path *current-path* (cdr path)))
995       ((null path) *current-path*)
996     (let ((first (first path)))
997       (when (or (eq first name)
998                 (eq first 'original-source-start))
999         (return path)))))