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