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