1.0.28.48: fix regressions from 1.0.28.47
[sbcl.git] / doc / manual / compiler.texinfo
1 @node Compiler
2 @comment  node-name,  next,  previous,  up
3 @chapter Compiler
4
5 This chapter will discuss most compiler issues other than efficiency,
6 including compiler error messages, the SBCL compiler's unusual
7 approach to type safety in the presence of type declarations, the
8 effects of various compiler optimization policies, and the way that
9 inlining and open coding may cause optimized code to differ from a
10 naive translation. Efficiency issues are sufficiently varied and
11 separate that they have their own chapter, @ref{Efficiency}.
12
13 @menu
14 * Diagnostic Messages::
15 * Handling of Types::           
16 * Compiler Policy::             
17 * Compiler Errors::             
18 * Open Coding and Inline Expansion::  
19 * Interpreter::
20 @end menu
21
22 @node  Diagnostic Messages
23 @comment  node-name,  next,  previous,  up
24 @section Diagnostic Messages
25 @cindex Messages, Compiler
26 @cindex Compiler messages
27
28 @menu
29 * Controlling Verbosity::       
30 * Diagnostic Severity::         
31 * Understanding Compiler Diagnostics::  
32 @end menu
33
34 @node Controlling Verbosity
35 @comment  node-name,  next,  previous,  up
36 @subsection Controlling Verbosity
37
38 The compiler can be quite verbose in its diagnostic reporting, rather
39 more then some users would prefer -- the amount of noise emitted can
40 be controlled, however.
41
42 To control emission of compiler diagnostics (of any severity other
43 than @code{error}: @pxref{Diagnostic Severity}) use the
44 @code{sb-ext:muffle-conditions} and @code{sb-ext:unmuffle-conditions}
45 declarations, specifying the type of condition that is to be muffled
46 (the muffling is done using an associated @code{muffle-warning} restart).
47
48 Global control:
49 @lisp
50 ;;; Muffle compiler-notes globally
51 (declaim (sb-ext:muffle-conditions sb-ext:compiler-note))
52 @end lisp
53
54 Local control:
55 @lisp
56 ;;; Muffle compiler-notes based on lexical scope
57 (defun foo (x)
58   (declare (optimize speed) (fixnum x)
59            (sb-ext:muffle-conditions sb-ext:compiler-note))
60   (values (* x 5) ; no compiler note from this
61     (locally
62       (declare (sb-ext:unmuffle-conditions sb-ext:compiler-note))
63       ;; this one gives a compiler note
64       (* x -5))))
65 @end lisp
66
67 @deffn {Declaration} sb-ext:muffle-conditions
68 Syntax: type*
69
70 Muffles the diagnostic messages that would be caused by compile-time
71 signals of given types.
72 @end deffn
73
74 @deffn {Declaration} sb-ext:unmuffle-conditions
75 Syntax: type*
76
77 Cancels the effect of a previous @code{sb-ext:muffle-condition}
78 declaration.
79 @end deffn
80
81 Various details of @emph{how} the compiler messages are printed can be
82 controlled via the alist
83 @code{sb-ext:*compiler-print-variable-alist*}.
84
85 @include var-sb-ext-star-compiler-print-variable-alist-star.texinfo
86
87 For information about muffling warnings signaled outside of the
88 compiler, see @ref{Customization Hooks for Users}.
89
90 @c <!-- FIXME: How much control over error messages is in SBCL?
91 @c      _     How much should be? How much of this documentation should
92 @c      _     we save or adapt? 
93 @c      _ 
94 @c      _ %%\node Error Message Parameterization,  , Read Errors, Interpreting Error Messages
95 @c      _ \subsection{Error Message Parameterization}
96 @c      _ \cpsubindex{error messages}{verbosity}
97 @c      _ \cpsubindex{verbosity}{of error messages}
98 @c      _ 
99 @c      _ There is some control over the verbosity of error messages.  See also
100 @c      _ \varref{undefined-warning-limit}, \code{*efficiency-note-limit*} and
101 @c      _ \varref{efficiency-note-cost-threshold}.
102 @c      _ 
103 @c      _ \begin{defvar}{}{enclosing-source-cutoff}
104 @c      _ 
105 @c      _   This variable specifies the number of enclosing actual source forms
106 @c      _   that are printed in full, rather than in the abbreviated processing
107 @c      _   path format.  Increasing the value from its default of \code{1}
108 @c      _   allows you to see more of the guts of the macroexpanded source,
109 @c      _   which is useful when debugging macros.
110 @c      _ \end{defvar}
111 @c      _ 
112 @c      _ \begin{defmac}{extensions:}{define-source-context}{%
113 @c      _     \args{\var{name} \var{lambda-list} \mstar{form}}}
114 @c      _ 
115 @c      _   This macro defines how to extract an abbreviated source context from
116 @c      _   the \var{name}d form when it appears in the compiler input.
117 @c      _   \var{lambda-list} is a \code{defmacro} style lambda-list used to
118 @c      _   parse the arguments.  The \var{body} should return a list of
119 @c      _   subforms that can be printed on about one line.  There are
120 @c      _   predefined methods for \code{defstruct}, \code{defmethod}, etc.  If
121 @c      _   no method is defined, then the first two subforms are returned.
122 @c      _   Note that this facility implicitly determines the string name
123 @c      _   associated with anonymous functions.
124 @c      _ \end{defmac}
125 @c      _ 
126 @c      _ -->
127
128 @node  Diagnostic Severity
129 @comment  node-name,  next,  previous,  up
130 @subsection Diagnostic Severity
131 @cindex Severity of compiler messages
132 @cindex Compiler Diagnostic Severity
133 @tindex error
134 @tindex warning
135 @tindex style-warning
136 @tindex compiler-note
137 @tindex code-deletion-note
138
139 There are four levels of compiler diagnostic severity: 
140
141 @enumerate 1
142 @item error
143 @item warning
144 @item style warning
145 @item note
146 @end enumerate
147
148 The first three levels correspond to condition classes which are
149 defined in the ANSI standard for Common Lisp and which have special
150 significance to the @code{compile} and @code{compile-file} functions.
151 These levels of compiler error severity occur when the compiler
152 handles conditions of these classes. 
153
154 The fourth level of compiler error severity, @emph{note}, corresponds
155 to the @code{sb-ext:compiler-note}, and is used for problems which are
156 too mild for the standard condition classes, typically hints about how
157 efficiency might be improved. The @code{sb-ext:code-deletion-note}, a
158 subtype of @code{compiler-note}, is signalled when the compiler
159 deletes user-supplied code after proving that the code in question is
160 unreachable.
161
162 Future work for SBCL includes expanding this hierarchy of types to
163 allow more fine-grained control over emission of diagnostic messages.
164
165 @include condition-sb-ext-compiler-note.texinfo
166 @include condition-sb-ext-code-deletion-note.texinfo
167
168
169 @node Understanding Compiler Diagnostics
170 @comment  node-name,  next,  previous,  up
171 @subsection Understanding Compile Diagnostics
172
173 The messages emitted by the compiler contain a lot of detail in a
174 terse format, so they may be confusing at first. The messages will be
175 illustrated using this example program:
176
177 @lisp
178 (defmacro zoq (x)
179   `(roq (ploq (+ ,x 3))))
180
181 (defun foo (y)
182   (declare (symbol y))
183   (zoq y))
184 @end lisp
185
186 The main problem with this program is that it is trying to add
187 @code{3} to a symbol. Note also that the functions @code{roq} and
188 @code{ploq} aren't defined anywhere.
189
190 @menu
191 * The Parts of a Compiler Diagnostic::  
192 * The Original and Actual Source::  
193 * The Processing Path::         
194 @end menu
195
196 @node  The Parts of a Compiler Diagnostic
197 @comment  node-name,  next,  previous,  up
198 @subsubsection The Parts of a Compiler Diagnostic
199
200 When processing this program, the compiler will produce this warning:
201
202 @example
203 ; file: /tmp/foo.lisp
204 ; in: DEFUN FOO
205 ;     (ZOQ Y)
206 ; --> ROQ PLOQ
207 ; ==>
208 ;   (+ Y 3)
209 ;
210 ; caught WARNING:
211 ;   Asserted type NUMBER conflicts with derived type (VALUES SYMBOL &OPTIONAL).
212 @end example
213
214 In this example we see each of the six possible parts of a compiler
215 diagnostic:
216
217 @enumerate
218
219 @item
220 @findex with-compilation-unit
221 @samp{file: /tmp/foo.lisp} This is the name of the file that the
222 compiler read the relevant code from.  The file name is displayed
223 because it may not be immediately obvious when there is an error
224 during compilation of a large system, especially when
225 @code{with-compilation-unit} is used to delay undefined warnings.
226
227 @item
228 @samp{in: DEFUN FOO} This is the definition top level form responsible
229 for the diagnostic. It is obtained by taking the first two elements of
230 the enclosing form whose first element is a symbol beginning with
231 ``@samp{def}''. If there is no such enclosing ``@samp{def}'' form,
232 then the outermost form is used. If there are multiple @samp{def}
233 forms, then they are all printed from the outside in, separated by
234 @samp{=>}'s. In this example, the problem was in the @code{defun} for
235 @code{foo}.
236
237 @item
238 @cindex Original Source
239 @samp{(ZOQ Y)} This is the @dfn{original source} form responsible for
240 the diagnostic. Original source means that the form directly appeared
241 in the original input to the compiler, i.e. in the lambda passed to
242 @code{compile} or in the top level form read from the source file. In
243 this example, the expansion of the @code{zoq} macro was responsible
244 for the message.
245
246 @item
247 @cindex Processing Path
248 @samp{--> ROQ PLOQ} This is the @dfn{processing path} that the
249 compiler used to produce the code that caused the message to be
250 emitted. The processing path is a representation of the evaluated
251 forms enclosing the actual source that the compiler encountered when
252 processing the original source. The path is the first element of each
253 form, or the form itself if the form is not a list. These forms result
254 from the expansion of macros or source-to-source transformation done
255 by the compiler. In this example, the enclosing evaluated forms are
256 the calls to @code{roq} and @code{ploq}. These calls resulted from the
257 expansion of the @code{zoq} macro.
258
259 @item
260 @cindex Actual Source
261 @samp{==> (+ Y 3)} This is the @dfn{actual source} responsible for the
262 diagnostic. If the actual source appears in the explanation, then we
263 print the next enclosing evaluated form, instead of printing the
264 actual source twice. (This is the form that would otherwise have been
265 the last form of the processing path.) In this example, the problem is
266 with the evaluation of the reference to the variable @code{y}.
267
268 @item
269 @samp{caught WARNING: Asserted type NUMBER conflicts with derived type
270 (VALUES SYMBOL &OPTIONAL).}  This is the @dfn{explanation} of the
271 problem. In this example, the problem is that, while the call to
272 @code{+} requires that its arguments are all of type @code{number},
273 the compiler has derived that @code{y} will evaluate to a
274 @code{symbol}.  Note that @samp{(VALUES SYMBOL &OPTIONAL)} expresses
275 that @code{y} evaluates to precisely one value.
276
277 @end enumerate
278
279 Note that each part of the message is distinctively marked:
280
281 @itemize
282
283 @item
284  @samp{file:} and @samp{in:} mark the file and definition,
285 respectively.
286
287 @item
288 The original source is an indented form with no prefix.
289
290 @item
291 Each line of the processing path is prefixed with @samp{-->}
292
293 @item
294 The actual source form is indented like the original source, but is
295 marked by a preceding @samp{==>} line.
296 @comment no it isn't.
297
298 @item
299 The explanation is prefixed with the diagnostic severity, which can be
300 @samp{caught ERROR:}, @samp{caught WARNING:}, @samp{caught
301 STYLE-WARNING:}, or @samp{note:}.
302
303 @end itemize
304
305 Each part of the message is more specific than the preceding one. If
306 consecutive messages are for nearby locations, then the front part of
307 the messages would be the same. In this case, the compiler omits as
308 much of the second message as in common with the first. For example:
309
310 @example
311 ; file: /tmp/foo.lisp
312 ; in: DEFUN FOO
313 ;     (ZOQ Y)
314 ; --> ROQ
315 ; ==>
316 ;   (PLOQ (+ Y 3))
317 ;
318 ; caught STYLE-WARNING:
319 ;   undefined function: PLOQ
320  
321 ; ==>
322 ;   (ROQ (PLOQ (+ Y 3)))
323 ;
324 ; caught STYLE-WARNING:
325 ;   undefined function: ROQ
326 @end example
327 @comment fixing that weird blank line might be good
328
329 In this example, the file, definition and original source are
330 identical for the two messages, so the compiler omits them in the
331 second message. If consecutive messages are entirely identical, then
332 the compiler prints only the first message, followed by: @samp{[Last
333 message occurs @var{repeats} times]} where @var{repeats} is the number
334 of times the message was given.
335
336 If the source was not from a file, then no file line is printed. If
337 the actual source is the same as the original source, then the
338 processing path and actual source will be omitted. If no forms
339 intervene between the original source and the actual source, then the
340 processing path will also be omitted.
341
342
343 @node  The Original and Actual Source
344 @comment  node-name,  next,  previous,  up
345 @subsubsection The Original and Actual Source
346 @cindex Original Source
347 @cindex Actual Source
348
349 The @emph{original source} displayed will almost always be a list. If
350 the actual source for an message is a symbol, the original source will
351 be the immediately enclosing evaluated list form. So even if the
352 offending symbol does appear in the original source, the compiler will
353 print the enclosing list and then print the symbol as the actual
354 source (as though the symbol were introduced by a macro.)
355
356 When the @emph{actual source} is displayed (and is not a symbol), it
357 will always be code that resulted from the expansion of a macro or a
358 source-to-source compiler optimization. This is code that did not
359 appear in the original source program; it was introduced by the
360 compiler.
361
362 Keep in mind that when the compiler displays a source form in an
363 diagnostic message, it always displays the most specific (innermost)
364 responsible form. For example, compiling this function
365
366 @lisp
367 (defun bar (x)
368   (let (a)
369     (declare (fixnum a))
370     (setq a (foo x))
371     a))
372 @end lisp
373
374 gives this error message
375
376 @example
377 ; file: /tmp/foo.lisp
378 ; in: DEFUN BAR
379 ;     (LET (A)
380 ;     (DECLARE (FIXNUM A))
381 ;     (SETQ A (FOO X))
382 ;     A)
383 ;
384 ; caught WARNING:
385 ;   Asserted type FIXNUM conflicts with derived type (VALUES NULL &OPTIONAL).
386 @end example
387
388 This message is not saying ``there is a problem somewhere in this
389 @code{let}'' -- it is saying that there is a problem with the
390 @code{let} itself. In this example, the problem is that @code{a}'s
391 @code{nil} initial value is not a @code{fixnum}.
392
393 @node The Processing Path
394 @comment  node-name,  next,  previous,  up
395 @subsubsection The Processing Path
396 @cindex Processing Path
397 @cindex Macroexpansion
398 @cindex Source-to-source transformation
399
400 The processing path is mainly useful for debugging macros, so if you
401 don't write macros, you can probably ignore it. Consider this example:
402
403 @lisp
404 (defun foo (n)
405   (dotimes (i n *undefined*)))
406 @end lisp
407
408 Compiling results in this error message:
409
410 @example
411 ; in: DEFUN FOO
412 ;     (DOTIMES (I N *UNDEFINED*))
413 ; --> DO BLOCK LET TAGBODY RETURN-FROM
414 ; ==>
415 ;   (PROGN *UNDEFINED*)
416 ;
417 ; caught WARNING:
418 ;   undefined variable: *UNDEFINED*
419 @end example
420
421 Note that @code{do} appears in the processing path. This is because
422 @code{dotimes} expands into:
423
424 @lisp
425 (do ((i 0 (1+ i)) (#:g1 n))
426     ((>= i #:g1) *undefined*)
427   (declare (type unsigned-byte i)))
428 @end lisp
429
430 The rest of the processing path results from the expansion of
431 @code{do}:
432
433 @lisp
434 (block nil
435   (let ((i 0) (#:g1 n))
436     (declare (type unsigned-byte i))
437     (tagbody (go #:g3)
438       #:g2    (psetq i (1+ i))
439       #:g3    (unless (>= i #:g1) (go #:g2))
440       (return-from nil (progn *undefined*)))))
441 @end lisp
442
443 In this example, the compiler descended into the @code{block},
444 @code{let}, @code{tagbody} and @code{return-from} to reach the
445 @code{progn} printed as the actual source. This is a place where the
446 ``actual source appears in explanation'' rule was applied. The
447 innermost actual source form was the symbol @code{*undefined*} itself,
448 but that also appeared in the explanation, so the compiler backed out
449 one level.
450
451
452
453
454
455 @node  Handling of Types
456 @comment  node-name,  next,  previous,  up
457 @section Handling of Types
458
459 One of the most important features of the SBCL compiler (similar to
460 the original CMUCL compiler, also known as @dfn{Python}) is its fairly
461 sophisticated understanding of the Common Lisp type system and its
462 conservative approach to the implementation of type declarations.
463
464 These two features reward the use of type declarations throughout
465 development, even when high performance is not a concern. Also, as
466 discussed in the chapter on performance (@pxref{Efficiency}), the use
467 of appropriate type declarations can be very important for performance
468 as well.
469
470 @findex satisfies
471 The SBCL compiler also has a greater knowledge of the Common Lisp
472 type system than other compilers. Support is incomplete only for types
473 involving the @code{satisfies} type specifier.
474
475 @c <!-- FIXME: See also sections \ref{advanced-type-stuff}
476 @c      and \ref{type-inference}, once we snarf them from the
477 @c      CMU CL manual. -->
478 @c
479 @c Also see my paper on improving Baker, when I get round to it.
480 @c
481 @c Whose paper?
482
483 @menu
484 * Declarations as Assertions::  
485 * Precise Type Checking::       
486 * Getting Existing Programs to Run::  
487 * Implementation Limitations::  
488 @end menu
489
490 @node Declarations as Assertions
491 @comment  node-name,  next,  previous,  up
492 @subsection Declarations as Assertions
493 @findex safety
494
495 The SBCL compiler treats type declarations differently from most other
496 Lisp compilers. Under default compilation policy the compiler doesn't
497 blindly believe type declarations, but considers them assertions about
498 the program that should be checked: all type declarations that have
499 not been proven to always hold are asserted at runtime.
500
501 @quotation
502 @emph{Remaining bugs in the compiler's handling of types unfortunately
503 provide some exceptions to this rule, see @ref{Implementation
504 Limitations}.}
505 @end quotation
506
507 CLOS slot types form a notable exception. Types declared using the
508 @code{:type} slot option in @code{defclass} are asserted if and only
509 if the class was defined in @emph{safe code} and the slot access
510 location is in @emph{safe code} as well. This laxness does not pose
511 any internal consistency issues, as the CLOS slot types are not
512 available for the type inferencer, nor do CLOS slot types provide any
513 efficiency benefits.
514
515 There are three type checking policies available in SBCL, selectable
516 via @code{optimize} declarations.
517
518 @table @strong
519
520 @c FIXME: This should be properly integrated with general policy
521 @c stuff, once that gets cleaned up.
522
523 @item Full Type Checks
524 All declarations are considered assertions to be checked at runtime,
525 and all type checks are precise. The default compilation policy
526 provides full type checks.
527
528 Used when @code{(or (>= safety 2) (>= safety speed 1))}.
529
530 @item Weak Type Checks
531 Declared types may be simplified into faster to check supertypes: for
532 example, @code{(or (integer -17 -7) (integer 7 17))} is simplified
533 into @code{(integer -17 17)}.
534
535 @strong{Note}: it is relatively easy to corrupt the heap when weak
536 type checks are used if the program contains type-errors.
537
538 Used when @code{(and (< safety 2) (< safety speed))}
539
540 @item No Type Checks
541 All declarations are believed without assertions. Also disables
542 argument count and array bounds checking.
543
544 @strong{Note}: any type errors in code where type checks are not
545 performed are liable to corrupt the heap.
546
547 Used when @code{(= safety 0)}.
548
549 @end table
550
551 @node  Precise Type Checking
552 @comment  node-name,  next,  previous,  up
553 @subsection Precise Type Checking
554 @cindex Precise type checking
555 @cindex Type checking, precise
556
557 Precise checking means that the check is done as though @code{typep}
558 had been called with the exact type specifier that appeared in the
559 declaration.
560
561 If a variable is declared to be @code{(integer 3 17)} then its value
562 must always be an integer between @code{3} and @code{17}. If multiple
563 type declarations apply to a single variable, then all the
564 declarations must be correct; it is as though all the types were
565 intersected producing a single @code{and} type specifier.
566
567 To gain maximum benefit from the compiler's type checking, you should
568 always declare the types of function arguments and structure slots as
569 precisely as possible. This often involves the use of @code{or},
570 @code{member}, and other list-style type specifiers. 
571
572
573 @node  Getting Existing Programs to Run
574 @comment  node-name,  next,  previous,  up
575 @subsection Getting Existing Programs to Run
576 @cindex Existing programs, to run
577 @cindex Types, portability
578 @cindex Compatibility with other Lisps
579 @c     (should also have an entry in the non-ANSI-isms section)-->
580
581 Since SBCL's compiler does much more comprehensive type checking than
582 most Lisp compilers, SBCL may detect type errors in programs that have
583 been debugged using other compilers. These errors are mostly incorrect
584 declarations, although compile-time type errors can find actual bugs
585 if parts of the program have never been tested.
586
587 Some incorrect declarations can only be detected by run-time type
588 checking. It is very important to initially compile a program with
589 full type checks (high @code{safety} optimization) and then test this
590 safe version. After the checking version has been tested, then you can
591 consider weakening or eliminating type checks.  @emph{This applies
592 even to previously debugged programs,} because the SBCL compiler does
593 much more type inference than other Common Lisp compilers, so an
594 incorrect declaration can do more damage.
595
596 The most common problem is with variables whose constant initial value
597 doesn't match the type declaration. Incorrect constant initial values
598 will always be flagged by a compile-time type error, and they are
599 simple to fix once located. Consider this code fragment:
600
601 @lisp
602 (prog (foo)
603   (declare (fixnum foo))
604   (setq foo ...)
605   ...)
606 @end lisp
607
608 Here @code{foo} is given an initial value of @code{nil}, but is
609 declared to be a @code{fixnum}.  Even if it is never read, the initial
610 value of a variable must match the declared type.  There are two ways
611 to fix this problem. Change the declaration
612
613 @lisp
614 (prog (foo)
615   (declare (type (or fixnum null) foo))
616   (setq foo ...)
617   ...)
618 @end lisp
619
620 or change the initial value
621
622 @lisp
623 (prog ((foo 0))
624   (declare (fixnum foo))
625   (setq foo ...)
626   ...)
627 @end lisp
628
629 It is generally preferable to change to a legal initial value rather
630 than to weaken the declaration, but sometimes it is simpler to weaken
631 the declaration than to try to make an initial value of the
632 appropriate type.
633
634 Another declaration problem occasionally encountered is incorrect
635 declarations on @code{defmacro} arguments. This can happen when a
636 function is converted into a macro. Consider this macro:
637
638 @lisp
639 (defmacro my-1+ (x)
640   (declare (fixnum x))
641   `(the fixnum (1+ ,x)))
642 @end lisp
643
644 Although legal and well-defined Common Lisp code, this meaning of this
645 definition is almost certainly not what the writer intended. For
646 example, this call is illegal:
647
648 @lisp
649 (my-1+ (+ 4 5))
650 @end lisp
651
652 This call is illegal because the argument to the macro is @code{(+ 4
653 5)}, which is a @code{list}, not a @code{fixnum}.  Because of macro
654 semantics, it is hardly ever useful to declare the types of macro
655 arguments.  If you really want to assert something about the type of
656 the result of evaluating a macro argument, then put a @code{the} in
657 the expansion:
658
659 @lisp
660 (defmacro my-1+ (x)
661   `(the fixnum (1+ (the fixnum ,x))))
662 @end lisp
663
664 In this case, it would be stylistically preferable to change this
665 macro back to a function and declare it inline. 
666 @c <!--FIXME: <xref>inline-expansion, once we crib the 
667 @c      relevant text from the CMU CL manual.-->
668
669 Some more subtle problems are caused by incorrect declarations that
670 can't be detected at compile time.  Consider this code:
671   
672 @lisp
673 (do ((pos 0 (position #\a string :start (1+ pos))))
674   ((null pos))
675   (declare (fixnum pos))
676   ...)
677 @end lisp
678
679 Although @code{pos} is almost always a @code{fixnum}, it is @code{nil}
680 at the end of the loop. If this example is compiled with full type
681 checks (the default), then running it will signal a type error at the
682 end of the loop. If compiled without type checks, the program will go
683 into an infinite loop (or perhaps @code{position} will complain
684 because @code{(1+ nil)} isn't a sensible start.) Why? Because if you
685 compile without type checks, the compiler just quietly believes the
686 type declaration. Since the compiler believes that @code{pos} is
687 always a @code{fixnum}, it believes that @code{pos} is never
688 @code{nil}, so @code{(null pos)} is never true, and the loop exit test
689 is optimized away. Such errors are sometimes flagged by unreachable
690 code notes, but it is still important to initially compile and test
691 any system with full type checks, even if the system works fine when
692 compiled using other compilers.
693
694 In this case, the fix is to weaken the type declaration to @code{(or
695 fixnum null)} @footnote{Actually, this declaration is unnecessary in
696 SBCL, since it already knows that @code{position} returns a
697 non-negative @code{fixnum} or @code{nil}.}.
698
699 Note that there is usually little performance penalty for weakening a
700 declaration in this way. Any numeric operations in the body can still
701 assume that the variable is a @code{fixnum}, since @code{nil} is not a
702 legal numeric argument. Another possible fix would be to say:
703
704 @lisp
705 (do ((pos 0 (position #\a string :start (1+ pos))))
706     ((null pos))
707   (let ((pos pos))
708     (declare (fixnum pos))
709     ...))
710 @end lisp
711
712 This would be preferable in some circumstances, since it would allow a
713 non-standard representation to be used for the local @code{pos}
714 variable in the loop body.
715 @c <!-- FIXME: <xref>ND-variables, once we crib the text from the 
716 @c      CMU CL manual. -->
717
718 @node  Implementation Limitations
719 @comment  node-name,  next,  previous,  up
720 @subsection Implementation Limitations
721
722 Ideally, the compiler would consider @emph{all} type declarations to
723 be assertions, so that adding type declarations to a program, no
724 matter how incorrect they might be, would @emph{never} cause undefined
725 behavior. However, the compiler is known to fall short of this goal in
726 two areas:
727
728 @itemize
729
730 @item
731 @emph{Proclaimed} constraints on argument and result types of a
732 function are supposed to be checked by the function. If the function
733 type is proclaimed before function definition, type checks are
734 inserted by the compiler, but the standard allows the reversed order,
735 in which case the compiler will trust the declaration.
736
737 @item
738 The compiler cannot check types of an unknown number of values; if the
739 number of generated values is unknown, but the number of consumed is
740 known, only consumed values are checked.
741
742 For example,
743
744 @lisp
745 (defun foo (x) 
746   (the integer (bar x)))
747 @end lisp
748
749 causes the following compiler diagnostic to be emitted:
750
751 @example
752 ; note: type assertion too complex to check:
753 ;  (VALUES INTEGER &REST T).
754 @end example
755
756 A partial workaround is instead write:
757
758 @lisp
759 (defun foo (x)
760   (the (values integer &optional) (bar x)))
761 @end lisp
762
763 @end itemize
764
765 These are important issues, but are not necessarily easy to fix, so
766 they may, alas, remain in the system for a while.
767
768 @node Compiler Policy
769 @comment  node-name,  next,  previous,  up
770 @section Compiler Policy
771
772 Compiler policy is controlled by the @code{optimize} declaration,
773 supporting all ANSI optimization qualities (@code{debug},
774 @code{safety}, @code{space}, and @code{speed}).@footnote{A deprecated
775 extension @code{sb-ext:inhibit-warnings} is still supported, but
776 liable to go away at any time.}
777
778 For effects of various optimization qualities on type-safety and
779 debuggability see @ref{Declarations as Assertions} and @ref{Debugger
780 Policy Control}.
781
782 Ordinarily, when the @code{speed} quality is high, the compiler emits
783 notes to notify the programmer about its inability to apply various
784 optimizations. For selective muffling of these notes @xref{Controlling
785 Verbosity}.
786
787 The value of @code{space} mostly influences the compiler's decision
788 whether to inline operations, which tend to increase the size of
789 programs. Use the value @code{0} with caution, since it can cause the
790 compiler to inline operations so indiscriminately that the net effect
791 is to slow the program by causing cache misses or even swapping.
792
793 @c <!-- FIXME: old CMU CL compiler policy, should perhaps be adapted
794 @c      _    for SBCL. (Unfortunately, the CMU CL docs are out of sync with the
795 @c      _    CMU CL code, so adapting this requires not only reformatting
796 @c      _    the documentation, but rooting out code rot.)
797 @c      _
798 @c      _<sect2 id="compiler-policy"><title>Compiler Policy</1000
799 @c      _  INDEX {policy}{compiler}
800 @c      _  INDEX compiler policy
801 @c      _
802 @c      _<para>The policy is what tells the compiler <emphasis>how</emphasis> to
803 @c      _compile a program. This is logically (and often textually) distinct
804 @c      _from the program itself. Broad control of policy is provided by the
805 @c      _<parameter>optimize</parameter> declaration; other declarations and variables
806 @c      _control more specific aspects of compilation.
807 @c      _
808 @c      _\begin{comment}
809 @c      _* The Optimize Declaration::
810 @c      _* The Optimize-Interface Declaration::
811 @c      _\end{comment}
812 @c      _
813 @c      _%%\node The Optimize Declaration, The Optimize-Interface Declaration, Compiler Policy, Compiler Policy
814 @c      _\subsection{The Optimize Declaration}
815 @c      _\label{optimize-declaration}
816 @c      _\cindex{optimize declaration}
817 @c      _\cpsubindex{declarations}{\code{optimize}}
818 @c      _
819 @c      _The \code{optimize} declaration recognizes six different
820 @c      _\var{qualities}.  The qualities are conceptually independent aspects
821 @c      _of program performance.  In reality, increasing one quality tends to
822 @c      _have adverse effects on other qualities.  The compiler compares the
823 @c      _relative values of qualities when it needs to make a trade-off; i.e.,
824 @c      _if \code{speed} is greater than \code{safety}, then improve speed at
825 @c      _the cost of safety.
826 @c      _
827 @c      _The default for all qualities (except \code{debug}) is \code{1}.
828 @c      _Whenever qualities are equal, ties are broken according to a broad
829 @c      _idea of what a good default environment is supposed to be.  Generally
830 @c      _this downplays \code{speed}, \code{compile-speed} and \code{space} in
831 @c      _favor of \code{safety} and \code{debug}.  Novice and casual users
832 @c      _should stick to the default policy.  Advanced users often want to
833 @c      _improve speed and memory usage at the cost of safety and
834 @c      _debuggability.
835 @c      _
836 @c      _If the value for a quality is \code{0} or \code{3}, then it may have a
837 @c      _special interpretation.  A value of \code{0} means ``totally
838 @c      _unimportant'', and a \code{3} means ``ultimately important.''  These
839 @c      _extreme optimization values enable ``heroic'' compilation strategies
840 @c      _that are not always desirable and sometimes self-defeating.
841 @c      _Specifying more than one quality as \code{3} is not desirable, since
842 @c      _it doesn't tell the compiler which quality is most important.
843 @c      _
844 @c      _
845 @c      _These are the optimization qualities:
846 @c      _\begin{Lentry}
847 @c      _
848 @c      _\item[\code{speed}] \cindex{speed optimization quality}How fast the
849 @c      _  program should is run.  \code{speed 3} enables some optimizations
850 @c      _  that hurt debuggability.
851 @c      _
852 @c      _\item[\code{compilation-speed}] \cindex{compilation-speed optimization
853 @c      _    quality}How fast the compiler should run.  Note that increasing
854 @c      _  this above \code{safety} weakens type checking.
855 @c      _
856 @c      _\item[\code{space}] \cindex{space optimization quality}How much space
857 @c      _  the compiled code should take up.  Inline expansion is mostly
858 @c      _  inhibited when \code{space} is greater than \code{speed}.  A value
859 @c      _  of \code{0} enables indiscriminate inline expansion.  Wide use of a
860 @c      _  \code{0} value is not recommended, as it may waste so much space
861 @c      _  that run time is slowed.  \xlref{inline-expansion} for a discussion
862 @c      _  of inline expansion.
863 @c      _
864 @c      _\item[\code{debug}] \cindex{debug optimization quality}How debuggable
865 @c      _  the program should be.  The quality is treated differently from the
866 @c      _  other qualities: each value indicates a particular level of debugger
867 @c      _  information; it is not compared with the other qualities.
868 @c      _  \xlref{debugger-policy} for more details.
869 @c      _
870 @c      _\item[\code{safety}] \cindex{safety optimization quality}How much
871 @c      _  error checking should be done.  If \code{speed}, \code{space} or
872 @c      _  \code{compilation-speed} is more important than \code{safety}, then
873 @c      _  type checking is weakened (\pxlref{weakened-type-checks}).  If
874 @c      _  \code{safety} if \code{0}, then no run time error checking is done.
875 @c      _  In addition to suppressing type checks, \code{0} also suppresses
876 @c      _  argument count checking, unbound-symbol checking and array bounds
877 @c      _  checks.
878 @c      _  ... and checking of tag existence in RETURN-FROM and GO.
879 @c      _
880 @c      _\item[\code{extensions:inhibit-warnings}] \cindex{inhibit-warnings
881 @c      _    optimization quality}This is a CMU extension that determines how
882 @c      _  little (or how much) diagnostic output should be printed during
883 @c      _  compilation.  This quality is compared to other qualities to
884 @c      _  determine whether to print style notes and warnings concerning those
885 @c      _  qualities.  If \code{speed} is greater than \code{inhibit-warnings},
886 @c      _  then notes about how to improve speed will be printed, etc.  The
887 @c      _  default value is \code{1}, so raising the value for any standard
888 @c      _  quality above its default enables notes for that quality.  If
889 @c      _  \code{inhibit-warnings} is \code{3}, then all notes and most
890 @c      _  non-serious warnings are inhibited.  This is useful with
891 @c      _  \code{declare} to suppress warnings about unavoidable problems.
892 @c      _\end{Lentry}
893 @c      _
894 @c      _%%\node The Optimize-Interface Declaration,  , The Optimize Declaration, Compiler Policy
895 @c      _\subsection{The Optimize-Interface Declaration}
896 @c      _\label{optimize-interface-declaration}
897 @c      _\cindex{optimize-interface declaration}
898 @c      _\cpsubindex{declarations}{\code{optimize-interface}}
899 @c      _
900 @c      _The \code{extensions:optimize-interface} declaration is identical in
901 @c      _syntax to the \code{optimize} declaration, but it specifies the policy
902 @c      _used during compilation of code the compiler automatically generates
903 @c      _to check the number and type of arguments supplied to a function.  It
904 @c      _is useful to specify this policy separately, since even thoroughly
905 @c      _debugged functions are vulnerable to being passed the wrong arguments.
906 @c      _The \code{optimize-interface} declaration can specify that arguments
907 @c      _should be checked even when the general \code{optimize} policy is
908 @c      _unsafe.
909 @c      _
910 @c      _Note that this argument checking is the checking of user-supplied
911 @c      _arguments to any functions defined within the scope of the
912 @c      _declaration, \code{not} the checking of arguments to \llisp{}
913 @c      _primitives that appear in those definitions.
914 @c      _
915 @c      _The idea behind this declaration is that it allows the definition of
916 @c      _functions that appear fully safe to other callers, but that do no
917 @c      _internal error checking.  Of course, it is possible that arguments may
918 @c      _be invalid in ways other than having incorrect type.  Functions
919 @c      _compiled unsafely must still protect themselves against things like
920 @c      _user-supplied array indices that are out of bounds and improper lists.
921 @c      _See also the \kwd{context-declarations} option to
922 @c      _\macref{with-compilation-unit}.
923 @c      _
924 @c      _(end of section on compiler policy)
925 @c      _-->
926
927 @node Compiler Errors
928 @comment  node-name,  next,  previous,  up
929 @section Compiler Errors
930
931 @menu
932 * Type Errors at Compile Time::  
933 * Errors During Macroexpansion::  
934 * Read Errors::                 
935 @end menu
936
937 @node  Type Errors at Compile Time
938 @comment  node-name,  next,  previous,  up
939 @subsection Type Errors at Compile Time
940 @cindex Compile time type errors
941 @cindex Type checking, at compile time
942
943 If the compiler can prove at compile time that some portion of the
944 program cannot be executed without a type error, then it will give a
945 warning at compile time.
946
947 It is possible that the offending code would never actually be
948 executed at run-time due to some higher level consistency constraint
949 unknown to the compiler, so a type warning doesn't always indicate an
950 incorrect program.
951
952 For example, consider this code fragment:
953
954 @lisp
955 (defun raz (foo)
956   (let ((x (case foo
957               (:this 13)
958               (:that 9)
959               (:the-other 42))))
960     (declare (fixnum x))
961     (foo x)))
962 @end lisp
963
964 Compilation produces this warning:
965
966 @example
967 ; in: DEFUN RAZ
968 ;     (CASE FOO (:THIS 13) (:THAT 9) (:THE-OTHER 42))
969 ; --> LET COND IF COND IF COND IF
970 ; ==>
971 ;   (COND)
972 ;
973 ; caught WARNING:
974 ;   This is not a FIXNUM:
975 ;   NIL
976 @end example
977
978 In this case, the warning means that if @code{foo} isn't any of
979 @code{:this}, @code{:that} or @code{:the-other}, then @code{x} will be
980 initialized to @code{nil}, which the @code{fixnum} declaration makes
981 illegal. The warning will go away if @code{ecase} is used instead of
982 @code{case}, or if @code{:the-other} is changed to @code{t}.
983
984 This sort of spurious type warning happens moderately often in the
985 expansion of complex macros and in inline functions. In such cases,
986 there may be dead code that is impossible to correctly execute. The
987 compiler can't always prove this code is dead (could never be
988 executed), so it compiles the erroneous code (which will always signal
989 an error if it is executed) and gives a warning.
990
991 @node  Errors During Macroexpansion
992 @comment  node-name,  next,  previous,  up
993 @subsection Errors During Macroexpansion
994 @cindex Macroexpansion, errors during
995
996 The compiler handles errors that happen during macroexpansion, turning
997 them into compiler errors. If you want to debug the error (to debug a
998 macro), you can set @code{*break-on-signals*} to @code{error}. For
999 example, this definition:
1000
1001 @lisp
1002 (defun foo (e l)
1003   (do ((current l (cdr current))
1004        ((atom current) nil))
1005       (when (eq (car current) e) (return current))))
1006 @end lisp
1007
1008 gives this error:
1009
1010 @example
1011 ; in: DEFUN FOO
1012 ;     (DO ((CURRENT L (CDR CURRENT))
1013 ;        ((ATOM CURRENT) NIL))
1014 ;       (WHEN (EQ (CAR CURRENT) E) (RETURN CURRENT)))
1015 ;
1016 ; caught ERROR:
1017 ;   (in macroexpansion of (DO # #))
1018 ;   (hint: For more precise location, try *BREAK-ON-SIGNALS*.)
1019 ;   DO step variable is not a symbol: (ATOM CURRENT)
1020 @end example
1021
1022
1023 @node  Read Errors
1024 @comment  node-name,  next,  previous,  up
1025 @subsection Read Errors
1026 @cindex Read errors, compiler
1027
1028 SBCL's compiler does not attempt to recover from read errors when
1029 reading a source file, but instead just reports the offending
1030 character position and gives up on the entire source file.
1031
1032 @node  Open Coding and Inline Expansion
1033 @comment  node-name,  next,  previous,  up
1034 @section Open Coding and Inline Expansion
1035 @cindex Open-coding
1036 @cindex Inline expansion
1037 @cindex Static functions
1038
1039 Since Common Lisp forbids the redefinition of standard functions, the
1040 compiler can have special knowledge of these standard functions
1041 embedded in it. This special knowledge is used in various ways (open
1042 coding, inline expansion, source transformation), but the implications
1043 to the user are basically the same:
1044
1045 @itemize
1046
1047 @item
1048 Attempts to redefine standard functions may be frustrated, since the
1049 function may never be called. Although it is technically illegal to
1050 redefine standard functions, users sometimes want to implicitly
1051 redefine these functions when they are debugging using the
1052 @code{trace} macro.  Special-casing of standard functions can be
1053 inhibited using the @code{notinline} declaration, but even then some
1054 phases of analysis such as type inferencing are applied by the
1055 compiler.
1056
1057 @item
1058 The compiler can have multiple alternate implementations of standard
1059 functions that implement different trade-offs of speed, space and
1060 safety.  This selection is based on the compiler policy, @ref{Compiler
1061 Policy}.
1062
1063 @end itemize
1064
1065 When a function call is @emph{open coded}, inline code whose effect is
1066 equivalent to the function call is substituted for that function
1067 call. When a function call is @emph{closed coded}, it is usually left
1068 as is, although it might be turned into a call to a different function
1069 with different arguments. As an example, if @code{nthcdr} were to be
1070 open coded, then
1071
1072 @lisp
1073 (nthcdr 4 foobar)
1074 @end lisp
1075
1076 might turn into
1077
1078 @lisp
1079 (cdr (cdr (cdr (cdr foobar))))
1080 @end lisp
1081
1082 or even
1083
1084 @lisp
1085 (do ((i 0 (1+ i))
1086   (list foobar (cdr foobar)))
1087   ((= i 4) list))
1088 @end lisp
1089
1090 If @code{nth} is closed coded, then
1091
1092 @lisp
1093 (nth x l)
1094 @end lisp
1095
1096 might stay the same, or turn into something like
1097
1098 @lisp
1099 (car (nthcdr x l))
1100 @end lisp
1101
1102 In general, open coding sacrifices space for speed, but some functions
1103 (such as @code{car}) are so simple that they are always
1104 open-coded. Even when not open-coded, a call to a standard function
1105 may be transformed into a different function call (as in the last
1106 example) or compiled as @emph{static call}. Static function call uses
1107 a more efficient calling convention that forbids redefinition.
1108
1109 @node  Interpreter
1110 @comment  node-name,  next,  previous,  up
1111 @section Interpreter
1112 @cindex Interpreter
1113 @vindex sb-ext:*evaluator-mode*
1114
1115 By default SBCL implements @code{eval} by calling the native code
1116 compiler. SBCL also includes an interpreter for use in special cases
1117 where using the compiler is undesirable, for example due to compilation
1118 overhead. Unlike in some other Lisp implementations, in SBCL interpreted
1119 code is not safer or more debuggable than compiled code.
1120
1121 Switching between the compiler and the interpreter is done using the
1122 special variable @code{sb-ext:*evaluator-mode*}. As of 0.9.17, valid
1123 values for @code{sb-ext:*evaluator-mode*} are @code{:compile} and
1124 @code{:interpret}.