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