1 <chapter id="compiler"><title>The Compiler</>
3 <para>This chapter will discuss most compiler issues other than
4 efficiency, including compiler error messages, the &SBCL compiler's
5 unusual approach to type safety in the presence of type declarations,
6 the effects of various compiler optimization policies, and the way
7 that inlining and open coding may cause optimized code to differ from
8 a naive translation. Efficiency issues are sufficiently varied and
9 separate that they have <link linkend="efficiency">their own
10 chapter</link>.</para>
12 <sect1><title>Error Messages</>
13 <!--INDEX {error messages}{compiler}-->
14 <!--INDEX {compiler error messages}-->
16 <para>The compiler supplies a large amount of source location
17 information in error messages. The error messages contain a lot of
18 detail in a terse format, so they may be confusing at first. Error
19 messages will be illustrated using this example program:
20 <programlisting>(defmacro zoq (x)
21 `(roq (ploq (+ ,x 3))))
25 (zoq y))</programlisting>
26 The main problem with this program is that it is trying to add
27 <literal>3</> to a symbol. Note also that the functions
28 <function>roq</> and <function>ploq</> aren't defined anywhere.
31 <sect2><title>The Parts of the Error Message</>
33 <para>When processing this program, the compiler will produce this warning:
34 <screen>file: /tmp/foo.lisp
42 Result is a SYMBOL, not a NUMBER.</screen>
43 In this example we see each of the six possible parts of a compiler error
46 <listitem><para><computeroutput>File: /tmp/foo.lisp</>
47 This is the name of the file that the compiler read the
48 relevant code from. The file name is displayed because it
49 may not be immediately obvious when there is an
50 error during compilation of a large system, especially when
51 <function>with-compilation-unit</> is used to delay undefined
52 warnings.</para></listitem>
53 <listitem><para><computeroutput>in: DEFUN FOO</> This is the
54 definition top level form responsible for the error. It is
55 obtained by taking the first two elements of the enclosing form
56 whose first element is a symbol beginning with <quote><literal>def</></>.
57 If there is no such enclosing <quote><literal>def</></> form, then the
58 outermost form is used. If there are multiple <literal>def</>
59 forms, then they are all printed from the outside in, separated by
60 <literal>=></>'s. In this example, the problem was in the
61 <function>defun</> for <function>foo</>.</para></listitem>
62 <listitem><para><computeroutput>(ZOQ Y)</> This is the
63 <emphasis>original source</> form responsible for the error.
64 Original source means that the form directly appeared in the
65 original input to the compiler, i.e. in the lambda passed to
66 <function>compile</> or in the top level form read from the
67 source file. In this example, the expansion of the <function>zoq</>
68 macro was responsible for the error.</para></listitem>
69 <listitem><para><computeroutput>--> ROQ PLOQ +</> This is the
70 <emphasis>processing path</> that the compiler used to produce
71 the errorful code. The processing path is a representation of
72 the evaluated forms enclosing the actual source that the
73 compiler encountered when processing the original source.
74 The path is the first element of each form, or the form itself
75 if the form is not a list. These forms result from the
76 expansion of macros or source-to-source transformation done
77 by the compiler. In this example, the enclosing evaluated forms
78 are the calls to <function>roq</>, <function>ploq</> and
79 <function>+</>. These calls resulted from the expansion of
80 the <function>zoq</> macro.</para></listitem>
81 <listitem><para><computeroutput>==> Y</> This is the
82 <emphasis>actual source</> responsible for the error. If
83 the actual source appears in the explanation, then
84 we print the next enclosing evaluated form, instead of
85 printing the actual source twice. (This is the form
86 that would otherwise have been the last form of the processing
87 path.) In this example, the problem is with the evaluation of
88 the reference to the variable <varname>y</>.</para></listitem>
90 <computeroutput>caught WARNING: Result is a SYMBOL, not a NUMBER.</>
91 This is the <emphasis>explanation</> of the problem. In this
92 example, the problem is that <varname>y</> evaluates to a symbol,
93 but is in a context where a number is required (the argument
94 to <function>+</>).</para></listitem>
97 Note that each part of the error message is distinctively marked:
100 <listitem><para> <computeroutput>file:</> and <computeroutput>in:</>
101 mark the file and definition, respectively.</para></listitem>
102 <listitem><para> The original source is an indented form with no
103 prefix.</para></listitem>
104 <listitem><para> Each line of the processing path is prefixed with
105 <computeroutput>--></computeroutput></para></listitem>
106 <listitem><para> The actual source form is indented like the original
107 source, but is marked by a preceding <computeroutput>==></> line.
109 <listitem><para> The explanation is prefixed with the error
110 severity, which can be <computeroutput>caught ERROR:</>,
111 <computeroutput>caught WARNING:</>,
112 <computeroutput>caught STYLE-WARNING:</>, or
113 <computeroutput>note:</>. </para></listitem>
117 <para>Each part of the error message is more specific than the preceding
118 one. If consecutive error messages are for nearby locations, then the
119 front part of the error messages would be the same. In this case, the
120 compiler omits as much of the second message as in common with the
122 <screen>file: /tmp/foo.lisp
129 caught STYLE-WARNING:
130 undefined function: PLOQ
134 caught STYLE-WARNING:
135 undefined function: ROQ</screen>
136 In this example, the file, definition and original source are
137 identical for the two messages, so the compiler omits them in the
138 second message. If consecutive messages are entirely identical, then
139 the compiler prints only the first message, followed by:
140 <computeroutput>[Last message occurs <replaceable>repeats</> times]</>
141 where <replaceable>repeats</> is the number of times the message
144 <para>If the source was not from a file, then no file line is printed.
145 If the actual source is the same as the original source, then the
146 processing path and actual source will be omitted. If no forms
147 intervene between the original source and the actual source, then the
148 processing path will also be omitted.</para>
152 <sect2><title>The Original and Actual Source</>
154 <para>The <emphasis>original source</> displayed will almost always be
155 a list. If the actual source for an error message is a symbol, the
156 original source will be the immediately enclosing evaluated list form.
157 So even if the offending symbol does appear in the original source,
158 the compiler will print the enclosing list and then print the symbol
159 as the actual source (as though the symbol were introduced by a
162 <para>When the <emphasis>actual source</> is displayed
163 (and is not a symbol), it will always
164 be code that resulted from the expansion of a macro or a source-to-source
165 compiler optimization. This is code that did not appear in the original
166 source program; it was introduced by the compiler.</para>
168 <para>Keep in mind that when the compiler displays a source form
169 in an error message, it always displays the most specific (innermost)
170 responsible form. For example, compiling this function
171 <programlisting>(defun bar (x)
176 gives this error message
177 <screen>in: DEFUN BAR
178 (LET (A) (DECLARE (FIXNUM A)) (SETQ A (FOO X)) A)
179 caught WARNING: The binding of A is not a FIXNUM:
181 This error message is not saying <quote>there is a problem somewhere in
182 this <function>let</></quote> — it is saying that there is a
183 problem with the <function>let</> itself. In this example, the problem
184 is that <varname>a</>'s <literal>nil</> initial value is not a
185 <type>fixnum</>.</para>
189 <sect2><title>The Processing Path</>
190 <!--INDEX processing path-->
191 <!--INDEX macroexpansion-->
192 <!--INDEX source-to-source transformation-->
194 <para>The processing path is mainly useful for debugging macros, so if
195 you don't write macros, you can probably ignore it. Consider this
198 <programlisting>(defun foo (n)
199 (dotimes (i n *undefined*)))
202 Compiling results in this error message:
204 <screen>in: DEFUN FOO
205 (DOTIMES (I N *UNDEFINED*))
206 --> DO BLOCK LET TAGBODY RETURN-FROM
209 caught STYLE-WARNING:
210 undefined variable: *UNDEFINED*</screen>
212 Note that <function>do</> appears in the processing path. This is because
213 <function>dotimes</> expands into:
215 <programlisting>(do ((i 0 (1+ i)) (#:g1 n))
216 ((>= i #:g1) *undefined*)
217 (declare (type unsigned-byte i)))</programlisting>
219 The rest of the processing path results from the expansion
224 (let ((i 0) (#:g1 n))
225 (declare (type unsigned-byte i))
227 #:g2 (psetq i (1+ i))
228 #:g3 (unless (>= i #:g1) (go #:g2))
229 (return-from nil (progn *undefined*)))))
232 In this example, the compiler descended into the <function>block</>,
233 <function>let</>, <function>tagbody</> and <function>return-from</> to
234 reach the <function>progn</> printed as the actual source. This is a
235 place where the <quote>actual source appears in explanation</> rule
236 was applied. The innermost actual source form was the symbol
237 <varname>*undefined*</> itself, but that also appeared in the
238 explanation, so the compiler backed out one level.</para>
242 <sect2><title>Error Severity</>
243 <!--INDEX severity of compiler errors -->
244 <!--INDEX compiler error severity -->
246 <para>There are four levels of compiler error severity:
247 <wordasword>error</>, <wordasword>warning</>, <wordasword>style
248 warning</>, and <wordasword>note</>. The first three levels correspond
249 to condition classes which are defined in the &ANSI; standard for
250 &CommonLisp; and which have special significance to the
251 <function>compile</> and <function>compile-file</> functions. These
252 levels of compiler error severity occur when the compiler handles
253 conditions of these classes. The fourth level of compiler error
254 severity, <wordasword>note</>, is used for problems which are too mild
255 for the standard condition classes, typically hints about how
256 efficiency might be improved.</para>
260 <sect2><title>Errors During Macroexpansion</>
261 <!--INDEX {macroexpansion}{errors during}-->
263 <para>The compiler handles errors that happen during macroexpansion,
264 turning them into compiler errors. If you want to debug the error (to
265 debug a macro), you can set <varname>*break-on-signals*</> to
266 <literal>error</>. For example, this definition:
268 <programlisting>(defun foo (e l)
269 (do ((current l (cdr current))
270 ((atom current) nil))
271 (when (eq (car current) e) (return current))))</programlisting>
275 <screen>in: DEFUN FOO
276 (DO ((CURRENT L #) (# NIL)) (WHEN (EQ # E) (RETURN CURRENT)) )
278 (in macroexpansion of (DO # #))
279 (hint: For more precise location, try *BREAK-ON-SIGNALS*.)
280 DO step variable is not a symbol: (ATOM CURRENT)</screen>
285 <sect2><title>Read Errors</>
286 <!--INDEX {read errors}{compiler}-->
288 <para>&SBCL;'s compiler (unlike &CMUCL;'s) does not attempt to recover
289 from read errors when reading a source file, but instead just reports
290 the offending character position and gives up on the entire source
295 <!-- FIXME: How much control over error messages is in SBCL?
296 _ How much should be? How much of this documentation should
299 _ %%\node Error Message Parameterization, , Read Errors, Interpreting Error Messages
300 _ \subsection{Error Message Parameterization}
301 _ \cpsubindex{error messages}{verbosity}
302 _ \cpsubindex{verbosity}{of error messages}
304 _ There is some control over the verbosity of error messages. See also
305 _ \varref{undefined-warning-limit}, \code{*efficiency-note-limit*} and
306 _ \varref{efficiency-note-cost-threshold}.
308 _ \begin{defvar}{}{enclosing-source-cutoff}
310 _ This variable specifies the number of enclosing actual source forms
311 _ that are printed in full, rather than in the abbreviated processing
312 _ path format. Increasing the value from its default of \code{1}
313 _ allows you to see more of the guts of the macroexpanded source,
314 _ which is useful when debugging macros.
317 _ \begin{defvar}{}{error-print-length}
318 _ \defvarx{error-print-level}
320 _ These variables are the print level and print length used in
321 _ printing error messages. The default values are \code{5} and
322 _ \code{3}. If null, the global values of \code{*print-level*} and
323 _ \code{*print-length*} are used.
326 _ \begin{defmac}{extensions:}{define-source-context}{%
327 _ \args{\var{name} \var{lambda-list} \mstar{form}}}
329 _ This macro defines how to extract an abbreviated source context from
330 _ the \var{name}d form when it appears in the compiler input.
331 _ \var{lambda-list} is a \code{defmacro} style lambda-list used to
332 _ parse the arguments. The \var{body} should return a list of
333 _ subforms that can be printed on about one line. There are
334 _ predefined methods for \code{defstruct}, \code{defmethod}, etc. If
335 _ no method is defined, then the first two subforms are returned.
336 _ Note that this facility implicitly determines the string name
337 _ associated with anonymous functions.
344 <sect1><title>The Compiler's Handling of Types</>
346 <para>The most unusual features of the &SBCL; compiler (which is
347 very similar to the original &CMUCL compiler, also known as
348 &Python;) is its unusually sophisticated understanding of the
349 &CommonLisp; type system and its unusually conservative approach to
350 the implementation of type declarations. These two features reward the
351 use of type declarations throughout development, even when high
352 performance is not a concern. (Also, as discussed <link
353 linkend="efficiency">in the chapter on performance</>, the use of
354 appropriate type declarations can be very important for performance as
357 <para>The &SBCL; compiler, like the related compiler in &CMUCL;,
358 treats type declarations much differently than other Lisp compilers.
359 By default (<emphasis>i.e.</>, at ordinary levels of the
360 <parameter>safety</> compiler optimization parameter), the compiler
361 doesn't blindly believe most type declarations; it considers them
362 assertions about the program that should be checked.</para>
364 <para>The &SBCL; compiler also has a greater knowledge of the
365 &CommonLisp; type system than other compilers. Support is incomplete
366 only for the <type>not</>, <type>and</> and <type>satisfies</>
368 <!-- FIXME: See also sections \ref{advanced-type-stuff}
369 and \ref{type-inference}, once we snarf them from the
373 <sect2 id=compiler-impl-limitations><title>Implementation Limitations</>
376 Ideally, the compiler would consider <emphasis>all</> type declarations to
377 be assertions, so that adding type declarations to a program, no
378 matter how incorrect they might be, would <emphasis>never</> cause
379 undefined behavior. As of &SBCL; version 0.8.1, the compiler is known to
380 fall short of this goal in two areas:
382 <listitem><para><function>Proclaim</>ed constraints on argument and
383 result types of a function are supposed to be checked by the
384 function. If the function type is proclaimed before function
385 definition, type checks are inserted by the compiler, but the
386 standard allows the reversed order, in which case the compiler
387 will trust the declaration.</para></listitem>
388 <listitem><para>The compiler cannot check types of an unknown number
389 of values; if the number of generated values is unknown, but the
390 number of consumed is known, only consumed values are
391 checked.</para></listitem>
392 <listitem><para>There are a few poorly characterized but apparently
393 very uncommon situations where a type declaration in an unexpected
394 location will be trusted and never checked by the
395 compiler.</para></listitem>
396 </itemizedlist></para>
398 <para>These are important bugs, but are not necessarily easy to fix,
399 so they may, alas, remain in the system for a while.</para>
403 <sect2><title>Type Errors at Compile Time</>
404 <!--INDEX compile time type errors-->
405 <!--INDEX type checking}{at compile time}-->
407 <para>If the compiler can prove at compile time that some portion of
408 the program cannot be executed without a type error, then it will give
409 a warning at compile time. It is possible that the offending code
410 would never actually be executed at run-time due to some higher level
411 consistency constraint unknown to the compiler, so a type warning
412 doesn't always indicate an incorrect program. For example, consider
415 <programlisting>(defun raz (foo)
424 Compilation produces this warning:
426 <screen>in: DEFUN RAZ
427 (CASE FOO (:THIS 13) (:THAT 9) (:THE-OTHER 42))
428 --> LET COND IF COND IF COND IF
431 caught WARNING: This is not a FIXNUM:
434 In this case, the warning means that if <varname>foo</> isn't any of
435 <literal>:this</>, <literal>:that</> or <literal>:the-other</>, then
436 <varname>x</> will be initialized to <literal>nil</>, which the
437 <type>fixnum</> declaration makes illegal. The warning will go away if
438 <function>ecase</> is used instead of <function>case</>, or if
439 <literal>:the-other</> is changed to <literal>t</>.</para>
441 <para>This sort of spurious type warning happens moderately often in
442 the expansion of complex macros and in inline functions. In such
443 cases, there may be dead code that is impossible to correctly execute.
444 The compiler can't always prove this code is dead (could never be
445 executed), so it compiles the erroneous code (which will always signal
446 an error if it is executed) and gives a warning.</para>
449 Type warnings are inhibited when the
450 <parameter>sb-ext:inhibit-warnings</> optimization quality is
451 <literal>3</>. (See <link linkend="compiler-policy">the section
452 on compiler policy</>.) This can be used in a local declaration
453 to inhibit type warnings in a code fragment that has spurious
458 <sect2 id="precisetypechecking"><title>Precise Type Checking</>
459 <!--INDEX precise type checking-->
460 <!--INDEX {type checking}{precise}-->
462 <para>With the default compilation policy, all type declarations are
463 precisely checked, except in a few situations where they are simply
464 ignored instead. Precise checking means that the check is done as
465 though <function>typep</> had been called with the exact type
466 specifier that appeared in the declaration. In &SBCL;, adding type
467 declarations makes code safer. (Except that as noted <link
468 linkend="compiler-impl-limitations">elsewhere</link>, remaining bugs
469 in the compiler's handling of types unfortunately provide some
470 exceptions to this rule.)</para>
472 <para>If a variable is declared to be
473 <type>(integer 3 17)</> then its value must always be an integer
474 between <literal>3</> and <literal>17</>. If multiple type
475 declarations apply to a single variable, then all the declarations
476 must be correct; it is as though all the types were intersected
477 producing a single <type>and</> type specifier.</para>
479 <para>Argument and result type declarations are automatically
480 enforced. If you declare the type of a function argument, a type check
481 will be done when that function is called. In a function call, the
482 called function does the argument type checking.</para>
484 <para>The types of structure slots are also checked. The value of a
485 structure slot must always be of the type indicated in any
486 <literal>:type</> slot option. </para>
488 <para>In traditional &CommonLisp; compilers, not all type assertions
489 are checked, and type checks are not precise. Traditional compilers
490 blindly trust explicit type declarations, but may check the argument
491 type assertions for built-in functions. Type checking is not precise,
492 since the argument type checks will be for the most general type legal
493 for that argument. In many systems, type declarations suppress what
494 little type checking is being done, so adding type declarations makes
495 code unsafe. This is a problem since it discourages writing type
496 declarations during initial coding. In addition to being more error
497 prone, adding type declarations during tuning also loses all the
498 benefits of debugging with checked type assertions.</para>
500 <para>To gain maximum benefit from the compiler's type checking, you
501 should always declare the types of function arguments and structure
502 slots as precisely as possible. This often involves the use of
503 <type>or</>, <type>member</>, and other list-style type specifiers.</para>
507 <sect2 id="weakened-type-checking"><title>Weakened Type Checking</>
508 <!--INDEX weakened type checking-->
509 <!--INDEX {type checking}{weakened}-->
511 <para>At one time, &CMUCL; supported another level of type checking,
512 <quote>weakened type checking</>, when the value for the
513 <parameter>speed</> optimization quality is greater than
514 <parameter>safety</>, and <parameter>safety</> is not <literal>0</>.
515 The &CMUCL; manual still has a description of it, but even the CMU CL
516 code no longer corresponds to the manual. Some of this partial safety
517 checking lingers on in SBCL, but it's not a supported feature, and
518 should not be relied on. If you ask the compiler to optimize
519 <parameter>speed</> to a higher level than <parameter>safety</>,
520 your program is performing without a safety net, because &SBCL; may
521 at its option believe any or all type declarations with either partial
522 or nonexistent runtime checking.</para>
526 <sect2><title>Getting Existing Programs to Run</>
527 <!--INDEX {existing programs}{to run}-->
528 <!--INDEX {types}{portability}-->
529 <!--INDEX {compatibility with other Lisps}
530 (should also have an entry in the non-&ANSI;-isms section)-->
532 <para>Since &SBCL;'s compiler, like &CMUCL;'s compiler, does much more
533 comprehensive type checking than most Lisp compilers, &SBCL; may
534 detect type errors in programs that have been debugged using other
535 compilers. These errors are mostly incorrect declarations, although
536 compile-time type errors can find actual bugs if parts of the program
537 have never been tested.</para>
539 <para>Some incorrect declarations can only be detected by run-time
540 type checking. It is very important to initially compile a program
541 with full type checks (high <parameter>safety</> optimization) and
542 then test this safe version. After the checking version has been
543 tested, then you can consider weakening or eliminating type checks.
544 <emphasis>This applies even to previously debugged
545 programs,</emphasis> because the &SBCL; compiler does much more type
546 inference than other &CommonLisp; compilers, so an incorrect
547 declaration can do more damage.</para>
549 <para>The most common problem is with variables whose constant initial
550 value doesn't match the type declaration. Incorrect constant initial
551 values will always be flagged by a compile-time type error, and they
552 are simple to fix once located. Consider this code fragment:
554 <programlisting>(prog (foo)
555 (declare (fixnum foo))
557 ...)</programlisting>
559 Here <varname>foo</> is given an initial value of <literal>nil</>, but
560 is declared to be a <type>fixnum</>. Even if it is never read, the
561 initial value of a variable must match the declared type. There are
562 two ways to fix this problem. Change the declaration
564 <programlisting>(prog (foo)
565 (declare (type (or fixnum null) foo))
567 ...)</programlisting>
569 or change the initial value
571 <programlisting>(prog ((foo 0))
572 (declare (fixnum foo))
574 ...)</programlisting>
576 It is generally preferable to change to a legal initial value rather
577 than to weaken the declaration, but sometimes it is simpler to weaken
578 the declaration than to try to make an initial value of the
579 appropriate type.</para>
581 <para>Another declaration problem occasionally encountered is
582 incorrect declarations on <function>defmacro</> arguments. This can happen
583 when a function is converted into a macro. Consider this macro:
585 <programlisting>(defmacro my-1+ (x)
587 `(the fixnum (1+ ,x)))</programlisting>
589 Although legal and well-defined &CommonLisp; code, this meaning of
590 this definition is almost certainly not what the writer intended. For
591 example, this call is illegal:
593 <programlisting>(my-1+ (+ 4 5))</>
595 This call is illegal because the argument to the macro is
596 <literal>(+ 4 5)</>, which is a <type>list</>, not a
597 <type>fixnum</>. Because of
598 macro semantics, it is hardly ever useful to declare the types of
599 macro arguments. If you really want to assert something about the
600 type of the result of evaluating a macro argument, then put a
601 <function>the</> in the expansion:
603 <programlisting>(defmacro my-1+ (x)
604 `(the fixnum (1+ (the fixnum ,x))))</programlisting>
606 In this case, it would be stylistically preferable to change this
607 macro back to a function and declare it inline.
608 <!--FIXME: <xref>inline-expansion</>, once we crib the
609 relevant text from the CMU CL manual.-->
613 Some more subtle problems are caused by incorrect declarations that
614 can't be detected at compile time. Consider this code:
616 <programlisting>(do ((pos 0 (position #\a string :start (1+ pos))))
618 (declare (fixnum pos))
619 ...)</programlisting>
621 Although <varname>pos</> is almost always a <varname>fixnum</>, it is
622 <literal>nil</> at the end of the loop. If this example is compiled
623 with full type checks (the default), then running it will signal a
624 type error at the end of the loop. If compiled without type checks,
625 the program will go into an infinite loop (or perhaps
626 <function>position</> will complain because <literal>(1+ nil)</> isn't
627 a sensible start.) Why? Because if you compile without type checks,
628 the compiler just quietly believes the type declaration. Since the
629 compiler believes that <varname>pos</> is always a <type>fixnum</>, it
630 believes that <varname>pos</> is never <literal>nil</>, so
631 <literal>(null pos)</> is never true, and the loop exit test is
632 optimized away. Such errors are sometimes flagged by unreachable code
633 notes, but it is still important to initially compile and test any
634 system with full type checks, even if the system works fine when
635 compiled using other compilers.</para>
637 <para>In this case, the fix is to weaken the type declaration to
638 <type>(or fixnum null)</>.
639 <footnote><para>Actually, this declaration is
640 unnecessary in &SBCL;, since it already knows that <function>position</>
641 returns a non-negative <type>fixnum</> or <literal>nil</>.
644 Note that there is usually little performance penalty for weakening a
645 declaration in this way. Any numeric operations in the body can still
646 assume that the variable is a <type>fixnum</>, since <literal>nil</>
647 is not a legal numeric argument. Another possible fix would be to say:
649 <programlisting>(do ((pos 0 (position #\a string :start (1+ pos))))
652 (declare (fixnum pos))
653 ...))</programlisting>
655 This would be preferable in some circumstances, since it would allow a
656 non-standard representation to be used for the local <varname>pos</>
657 variable in the loop body.
658 <!-- FIXME: <xref>ND-variables</>, once we crib the text from the
666 <sect1 id="compiler-policy"><title>Compiler Policy</>
668 <para>As of version 0.6.4, &SBCL; still uses most of the &CMUCL; code
669 for compiler policy. The &CMUCL; code has many features and high-quality
670 documentation, but the two unfortunately do not match. So this area of
671 the compiler and its interface needs to be cleaned up. Meanwhile, here
672 is some rudimentary documentation on the current behavior of the
675 <para>Compiler policy is controlled by the <parameter>optimize</>
676 declaration. The compiler supports the &ANSI; optimization qualities,
677 and also an extension <parameter>sb-ext:inhibit-warnings</>.</para>
679 <para>Ordinarily, when the <parameter>speed</> quality is high, the
680 compiler emits notes to notify the programmer about its inability to
681 apply various optimizations. Setting
682 <parameter>sb-ext:inhibit-warnings</> to a value at least as large as
683 the <parameter>speed</> quality inhibits this notification. This can
684 be useful to suppress notes about code which is known to be
685 unavoidably inefficient. (For example, the compiler issues notes about
686 having to use generic arithmetic instead of fixnum arithmetic, which
687 is not helpful for code which by design supports arbitrary-sized
688 integers instead of being limited to fixnums.)</para>
690 <note><para>The basic functionality of the <parameter>optimize
691 inhibit-warnings</> extension will probably be supported in all future
692 versions of the system, but it will probably be renamed when the
693 compiler and its interface are cleaned up. The current name is
694 misleading, because it mostly inhibits optimization notes, not
695 warnings. And making it an optimization quality is misleading, because
696 it shouldn't affect the resulting code at all. It may become a
697 declaration identifier with a name like
698 <parameter>sb-ext:inhibit-notes</>, so that what's currently written
700 <programlisting>(declaim (optimize (sb-ext:inhibit-warnings 2)))</>
702 would become something like
704 <programlisting>(declaim (sb-ext:inhibit-notes 2))</>
708 <para> (In early versions of SBCL, a <parameter>speed</> value of zero
709 was used to enable byte compilation, but since version 0.7.0, SBCL
710 only supports native compilation.)</para>
712 <para>When <parameter>safety</> is zero, almost all runtime checking
713 of types, array bounds, and so forth is suppressed.</para>
715 <para>When <parameter>safety</> is less than <parameter>speed</>, any
716 and all type checks may be suppressed. At some point in the past,
717 &CMUCL; had <link linkend="weakened-type-checking">a more nuanced
718 interpretation of this</link>. However, &SBCL; doesn't support that
719 interpretation, and setting <parameter>safety</> less than
720 <parameter>speed</> may have roughly the same effect as setting
721 <parameter>safety</> to zero.</para>
723 <para>The value of <parameter>space</> mostly influences the
724 compiler's decision whether to inline operations, which tend to
725 increase the size of programs. Use the value <literal>0</> with
726 caution, since it can cause the compiler to inline operations so
727 indiscriminately that the net effect is to slow the program by causing
728 cache misses or swapping.</para>
730 <!-- FIXME: old CMU CL compiler policy, should perhaps be adapted
731 _ for SBCL. (Unfortunately, the CMU CL docs are out of sync with the
732 _ CMU CL code, so adapting this requires not only reformatting
733 _ the documentation, but rooting out code rot.)
735 _<sect2 id="compiler-policy"><title>Compiler Policy</>
736 _ INDEX {policy}{compiler}
737 _ INDEX compiler policy
739 _<para>The policy is what tells the compiler <emphasis>how</> to
740 _compile a program. This is logically (and often textually) distinct
741 _from the program itself. Broad control of policy is provided by the
742 _<parameter>optimize</> declaration; other declarations and variables
743 _control more specific aspects of compilation.</para>
746 _* The Optimize Declaration::
747 _* The Optimize-Interface Declaration::
750 _%%\node The Optimize Declaration, The Optimize-Interface Declaration, Compiler Policy, Compiler Policy
751 _\subsection{The Optimize Declaration}
752 _\label{optimize-declaration}
753 _\cindex{optimize declaration}
754 _\cpsubindex{declarations}{\code{optimize}}
756 _The \code{optimize} declaration recognizes six different
757 _\var{qualities}. The qualities are conceptually independent aspects
758 _of program performance. In reality, increasing one quality tends to
759 _have adverse effects on other qualities. The compiler compares the
760 _relative values of qualities when it needs to make a trade-off; i.e.,
761 _if \code{speed} is greater than \code{safety}, then improve speed at
764 _The default for all qualities (except \code{debug}) is \code{1}.
765 _Whenever qualities are equal, ties are broken according to a broad
766 _idea of what a good default environment is supposed to be. Generally
767 _this downplays \code{speed}, \code{compile-speed} and \code{space} in
768 _favor of \code{safety} and \code{debug}. Novice and casual users
769 _should stick to the default policy. Advanced users often want to
770 _improve speed and memory usage at the cost of safety and
773 _If the value for a quality is \code{0} or \code{3}, then it may have a
774 _special interpretation. A value of \code{0} means ``totally
775 _unimportant'', and a \code{3} means ``ultimately important.'' These
776 _extreme optimization values enable ``heroic'' compilation strategies
777 _that are not always desirable and sometimes self-defeating.
778 _Specifying more than one quality as \code{3} is not desirable, since
779 _it doesn't tell the compiler which quality is most important.
782 _These are the optimization qualities:
785 _\item[\code{speed}] \cindex{speed optimization quality}How fast the
786 _ program should is run. \code{speed 3} enables some optimizations
787 _ that hurt debuggability.
789 _\item[\code{compilation-speed}] \cindex{compilation-speed optimization
790 _ quality}How fast the compiler should run. Note that increasing
791 _ this above \code{safety} weakens type checking.
793 _\item[\code{space}] \cindex{space optimization quality}How much space
794 _ the compiled code should take up. Inline expansion is mostly
795 _ inhibited when \code{space} is greater than \code{speed}. A value
796 _ of \code{0} enables indiscriminate inline expansion. Wide use of a
797 _ \code{0} value is not recommended, as it may waste so much space
798 _ that run time is slowed. \xlref{inline-expansion} for a discussion
799 _ of inline expansion.
801 _\item[\code{debug}] \cindex{debug optimization quality}How debuggable
802 _ the program should be. The quality is treated differently from the
803 _ other qualities: each value indicates a particular level of debugger
804 _ information; it is not compared with the other qualities.
805 _ \xlref{debugger-policy} for more details.
807 _\item[\code{safety}] \cindex{safety optimization quality}How much
808 _ error checking should be done. If \code{speed}, \code{space} or
809 _ \code{compilation-speed} is more important than \code{safety}, then
810 _ type checking is weakened (\pxlref{weakened-type-checks}). If
811 _ \code{safety} if \code{0}, then no run time error checking is done.
812 _ In addition to suppressing type checks, \code{0} also suppresses
813 _ argument count checking, unbound-symbol checking and array bounds
816 _\item[\code{extensions:inhibit-warnings}] \cindex{inhibit-warnings
817 _ optimization quality}This is a CMU extension that determines how
818 _ little (or how much) diagnostic output should be printed during
819 _ compilation. This quality is compared to other qualities to
820 _ determine whether to print style notes and warnings concerning those
821 _ qualities. If \code{speed} is greater than \code{inhibit-warnings},
822 _ then notes about how to improve speed will be printed, etc. The
823 _ default value is \code{1}, so raising the value for any standard
824 _ quality above its default enables notes for that quality. If
825 _ \code{inhibit-warnings} is \code{3}, then all notes and most
826 _ non-serious warnings are inhibited. This is useful with
827 _ \code{declare} to suppress warnings about unavoidable problems.
830 _%%\node The Optimize-Interface Declaration, , The Optimize Declaration, Compiler Policy
831 _\subsection{The Optimize-Interface Declaration}
832 _\label{optimize-interface-declaration}
833 _\cindex{optimize-interface declaration}
834 _\cpsubindex{declarations}{\code{optimize-interface}}
836 _The \code{extensions:optimize-interface} declaration is identical in
837 _syntax to the \code{optimize} declaration, but it specifies the policy
838 _used during compilation of code the compiler automatically generates
839 _to check the number and type of arguments supplied to a function. It
840 _is useful to specify this policy separately, since even thoroughly
841 _debugged functions are vulnerable to being passed the wrong arguments.
842 _The \code{optimize-interface} declaration can specify that arguments
843 _should be checked even when the general \code{optimize} policy is
846 _Note that this argument checking is the checking of user-supplied
847 _arguments to any functions defined within the scope of the
848 _declaration, \code{not} the checking of arguments to \llisp{}
849 _primitives that appear in those definitions.
851 _The idea behind this declaration is that it allows the definition of
852 _functions that appear fully safe to other callers, but that do no
853 _internal error checking. Of course, it is possible that arguments may
854 _be invalid in ways other than having incorrect type. Functions
855 _compiled unsafely must still protect themselves against things like
856 _user-supplied array indices that are out of bounds and improper lists.
857 _See also the \kwd{context-declarations} option to
858 _\macref{with-compilation-unit}.
860 _(end of section on compiler policy)
865 <sect1><title>Open Coding and Inline Expansion</>
866 <!--INDEX open-coding-->
867 <!--INDEX inline expansion-->
868 <!--INDEX static functions-->
870 <para>Since &CommonLisp; forbids the redefinition of standard
871 functions, the compiler can have special knowledge of these standard
872 functions embedded in it. This special knowledge is used in various
873 ways (open coding, inline expansion, source transformation), but the
874 implications to the user are basically the same:
876 <listitem><para> Attempts to redefine standard functions may
877 be frustrated, since the function may never be called. Although
878 it is technically illegal to redefine standard functions, users
879 sometimes want to implicitly redefine these functions when they
880 are debugging using the <function>trace</> macro. Special-casing
881 of standard functions can be inhibited using the
882 <parameter>notinline</> declaration.</para></listitem>
883 <listitem><para> The compiler can have multiple alternate
884 implementations of standard functions that implement different
885 trade-offs of speed, space and safety. This selection is
886 based on the <link linkend="compiler-policy">compiler policy</link>.
891 <para>When a function call is <emphasis>open coded</>, inline code whose
892 effect is equivalent to the function call is substituted for that
893 function call. When a function call is <emphasis>closed coded</>, it
894 is usually left as is, although it might be turned into a call to a
895 different function with different arguments. As an example, if
896 <function>nthcdr</> were to be open coded, then
898 <programlisting>(nthcdr 4 foobar)</programlisting>
902 <programlisting>(cdr (cdr (cdr (cdr foobar))))</>
906 <programlisting>(do ((i 0 (1+ i))
907 (list foobar (cdr foobar)))
908 ((= i 4) list))</programlisting>
910 If <function>nth</> is closed coded, then
916 might stay the same, or turn into something like
923 <para>In general, open coding sacrifices space for speed, but some
924 functions (such as <function>car</>) are so simple that they are always
925 open-coded. Even when not open-coded, a call to a standard function
926 may be transformed into a different function call (as in the last
927 example) or compiled as <emphasis>static call</>. Static function call
928 uses a more efficient calling convention that forbids