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