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