more precise C type check support (const warnings) - added generic -W option support
[tinycc.git] / tcc-doc.texi
blobbc7aefa0322b734a8f221fdb538d34c6add1ac16
1 \input texinfo @c -*- texinfo -*-
2 @c %**start of header
3 @setfilename tcc-doc.info
4 @settitle Tiny C Compiler Reference Documentation
5 @c %**end of header
7 @include config.texi
9 @iftex
10 @titlepage
11 @afourpaper
12 @sp 7
13 @center @titlefont{Tiny C Compiler Reference Documentation}
14 @sp 3
15 @end titlepage
16 @headings double
17 @end iftex
19 @c @ifhtml
20 @contents
21 @c @end ifhtml
23 @ifnothtml
24 @node Top, Introduction, (dir), (dir)
25 @top Tiny C Compiler Reference Documentation
27 This manual documents version @value{VERSION} of the Tiny C Compiler.
29 @menu
30 * Introduction::                Introduction to tcc.
31 * Invoke::                      Invocation of tcc (command line, options).
32 * Bounds::                      Automatic bounds-checking of C code.
33 * Libtcc::                      The libtcc library.
34 @end menu
35 @end ifnothtml
37 @node Introduction
38 @chapter Introduction
40 TinyCC (aka TCC) is a small but hyper fast C compiler. Unlike other C
41 compilers, it is meant to be self-relying: you do not need an
42 external assembler or linker because TCC does that for you.
44 TCC compiles so @emph{fast} that even for big projects @code{Makefile}s may
45 not be necessary. 
47 TCC not only supports ANSI C, but also most of the new ISO C99
48 standard and many GNUC extensions including inline assembly.
50 TCC can also be used to make @emph{C scripts}, i.e. pieces of C source
51 that you run as a Perl or Python script. Compilation is so fast that
52 your script will be as fast as if it was an executable.
54 TCC can also automatically generate memory and bound checks
55 (@pxref{Bounds}) while allowing all C pointers operations. TCC can do
56 these checks even if non patched libraries are used.
58 With @code{libtcc}, you can use TCC as a backend for dynamic code
59 generation (@pxref{Libtcc}).
61 @node Invoke
62 @chapter Command line invocation
64 [This manual documents version @value{VERSION} of the Tiny C Compiler]
66 @section Quick start
68 @example
69 usage: tcc [-v] [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]
70            [-g] [-b] [-bt N] [-Ldir] [-llib] [-shared] [-static]
71            [infile1 infile2...] [-run infile args...]
72 @end example
74 @noindent
75 TCC options are a very much like gcc options. The main difference is that TCC
76 can also execute directly the resulting program and give it runtime
77 arguments.
79 Here are some examples to understand the logic:
81 @table @code
82 @item @samp{tcc -run a.c}
83 Compile @file{a.c} and execute it directly
85 @item @samp{tcc -run a.c arg1}
86 Compile a.c and execute it directly. arg1 is given as first argument to
87 the @code{main()} of a.c.
89 @item @samp{tcc a.c -run b.c arg1}
90 Compile @file{a.c} and @file{b.c}, link them together and execute them. arg1 is given
91 as first argument to the @code{main()} of the resulting program. Because
92 multiple C files are specified, @option{--} are necessary to clearly separate the
93 program arguments from the TCC options.
95 @item @samp{tcc -o myprog a.c b.c}
96 Compile @file{a.c} and @file{b.c}, link them and generate the executable @file{myprog}.
98 @item @samp{tcc -o myprog a.o b.o}
99 link @file{a.o} and @file{b.o} together and generate the executable @file{myprog}.
101 @item @samp{tcc -c a.c}
102 Compile @file{a.c} and generate object file @file{a.o}.
104 @item @samp{tcc -c asmfile.S}
105 Preprocess with C preprocess and assemble @file{asmfile.S} and generate
106 object file @file{asmfile.o}.
108 @item @samp{tcc -c asmfile.s}
109 Assemble (but not preprocess) @file{asmfile.s} and generate object file
110 @file{asmfile.o}.
112 @item @samp{tcc -r -o ab.o a.c b.c}
113 Compile @file{a.c} and @file{b.c}, link them together and generate the object file @file{ab.o}.
115 @end table
117 Scripting:
119 TCC can be invoked from @emph{scripts}, just as shell scripts. You just
120 need to add @code{#!/usr/local/bin/tcc -run} at the start of your C source:
122 @example
123 #!/usr/local/bin/tcc
124 #include <stdio.h>
126 int main() 
128     printf("Hello World\n");
129     return 0;
131 @end example
133 @section Option summary
135 General Options:
137 @table @option
138 @item -v
139 Display current TCC version.
141 @item -c
142 Generate an object file (@option{-o} option must also be given).
144 @item -o outfile
145 Put object file, executable, or dll into output file @file{outfile}.
147 @item -Bdir
148 Set the path where the tcc internal libraries can be found (default is
149 @file{PREFIX/lib/tcc}).
151 @item -bench
152 Output compilation statistics.
154 @item -run
155 Run compiled source.
156 @end table
158 Preprocessor options:
160 @table @option
161 @item -Idir
162 Specify an additional include path. Include paths are searched in the
163 order they are specified.
165 System include paths are always searched after. The default system
166 include paths are: @file{/usr/local/include}, @file{/usr/include}
167 and @file{PREFIX/lib/tcc/include}. (@file{PREFIX} is usually
168 @file{/usr} or @file{/usr/local}).
170 @item -Dsym[=val]
171 Define preprocessor symbol @samp{sym} to
172 val. If val is not present, its value is @samp{1}. Function-like macros can
173 also be defined: @option{-DF(a)=a+1}
175 @item -Usym
176 Undefine preprocessor symbol @samp{sym}.
177 @end table
179 Linker options:
181 @table @option
182 @item -Ldir
183 Specify an additional static library path for the @option{-l} option. The
184 default library paths are @file{/usr/local/lib}, @file{/usr/lib} and @file{/lib}.
186 @item -lxxx
187 Link your program with dynamic library libxxx.so or static library
188 libxxx.a. The library is searched in the paths specified by the
189 @option{-L} option.
191 @item -shared
192 Generate a shared library instead of an executable (@option{-o} option
193 must also be given).
195 @item -static
196 Generate a statically linked executable (default is a shared linked
197 executable) (@option{-o} option must also be given).
199 @item -r
200 Generate an object file combining all input files (@option{-o} option must
201 also be given).
203 @end table
205 Debugger options:
207 @table @option
208 @item -g
209 Generate run time debug information so that you get clear run time
210 error messages: @code{ test.c:68: in function 'test5()': dereferencing
211 invalid pointer} instead of the laconic @code{Segmentation
212 fault}.
214 @item -b
215 Generate additional support code to check
216 memory allocations and array/pointer bounds. @option{-g} is implied. Note
217 that the generated code is slower and bigger in this case.
219 @item -bt N
220 Display N callers in stack traces. This is useful with @option{-g} or
221 @option{-b}.
223 @end table
225 Note: GCC options @option{-Ox}, @option{-Wx}, @option{-fx} and @option{-mx} are
226 ignored.
228 @chapter C language support
230 @section ANSI C
232 TCC implements all the ANSI C standard, including structure bit fields
233 and floating point numbers (@code{long double}, @code{double}, and
234 @code{float} fully supported).
236 @section ISOC99 extensions
238 TCC implements many features of the new C standard: ISO C99. Currently
239 missing items are: complex and imaginary numbers and variable length
240 arrays.
242 Currently implemented ISOC99 features:
244 @itemize
246 @item 64 bit @code{long long} types are fully supported.
248 @item The boolean type @code{_Bool} is supported.
250 @item @code{__func__} is a string variable containing the current
251 function name.
253 @item Variadic macros: @code{__VA_ARGS__} can be used for
254    function-like macros:
255 @example
256     #define dprintf(level, __VA_ARGS__) printf(__VA_ARGS__)
257 @end example
259 @noindent
260 @code{dprintf} can then be used with a variable number of parameters.
262 @item Declarations can appear anywhere in a block (as in C++).
264 @item Array and struct/union elements can be initialized in any order by
265   using designators:
266 @example
267     struct @{ int x, y; @} st[10] = @{ [0].x = 1, [0].y = 2 @};
269     int tab[10] = @{ 1, 2, [5] = 5, [9] = 9@};
270 @end example
271     
272 @item Compound initializers are supported:
273 @example
274     int *p = (int [])@{ 1, 2, 3 @};
275 @end example
276 to initialize a pointer pointing to an initialized array. The same
277 works for structures and strings.
279 @item Hexadecimal floating point constants are supported:
280 @example
281           double d = 0x1234p10;
282 @end example
284 @noindent
285 is the same as writing 
286 @example
287           double d = 4771840.0;
288 @end example
290 @item @code{inline} keyword is ignored.
292 @item @code{restrict} keyword is ignored.
293 @end itemize
295 @section GNU C extensions
297 TCC implements some GNU C extensions:
299 @itemize
301 @item array designators can be used without '=': 
302 @example
303     int a[10] = @{ [0] 1, [5] 2, 3, 4 @};
304 @end example
306 @item Structure field designators can be a label: 
307 @example
308     struct @{ int x, y; @} st = @{ x: 1, y: 1@};
309 @end example
310 instead of
311 @example
312     struct @{ int x, y; @} st = @{ .x = 1, .y = 1@};
313 @end example
315 @item @code{\e} is ASCII character 27.
317 @item case ranges : ranges can be used in @code{case}s:
318 @example
319     switch(a) @{
320     case 1 @dots{} 9:
321           printf("range 1 to 9\n");
322           break;
323     default:
324           printf("unexpected\n");
325           break;
326     @}
327 @end example
329 @item The keyword @code{__attribute__} is handled to specify variable or
330 function attributes. The following attributes are supported:
331   @itemize
332   @item @code{aligned(n)}: align data to n bytes (must be a power of two).
334   @item @code{section(name)}: generate function or data in assembly
335   section name (name is a string containing the section name) instead
336   of the default section.
338   @item @code{unused}: specify that the variable or the function is unused.
340   @item @code{cdecl}: use standard C calling convention.
342   @item @code{stdcall}: use Pascal-like calling convention.
344   @end itemize
346 Here are some examples:
347 @example
348     int a __attribute__ ((aligned(8), section(".mysection")));
349 @end example
351 @noindent
352 align variable @code{a} to 8 bytes and put it in section @code{.mysection}.
354 @example
355     int my_add(int a, int b) __attribute__ ((section(".mycodesection"))) 
356     @{
357         return a + b;
358     @}
359 @end example
361 @noindent
362 generate function @code{my_add} in section @code{.mycodesection}.
364 @item GNU style variadic macros:
365 @example
366     #define dprintf(fmt, args@dots{}) printf(fmt, ## args)
368     dprintf("no arg\n");
369     dprintf("one arg %d\n", 1);
370 @end example
372 @item @code{__FUNCTION__} is interpreted as C99 @code{__func__} 
373 (so it has not exactly the same semantics as string literal GNUC
374 where it is a string literal).
376 @item The @code{__alignof__} keyword can be used as @code{sizeof} 
377 to get the alignment of a type or an expression.
379 @item The @code{typeof(x)} returns the type of @code{x}. 
380 @code{x} is an expression or a type.
382 @item Computed gotos: @code{&&label} returns a pointer of type 
383 @code{void *} on the goto label @code{label}. @code{goto *expr} can be
384 used to jump on the pointer resulting from @code{expr}.
386 @item Inline assembly with asm instruction:
387 @cindex inline assembly
388 @cindex assembly, inline
389 @cindex __asm__
390 @example
391 static inline void * my_memcpy(void * to, const void * from, size_t n)
393 int d0, d1, d2;
394 __asm__ __volatile__(
395         "rep ; movsl\n\t"
396         "testb $2,%b4\n\t"
397         "je 1f\n\t"
398         "movsw\n"
399         "1:\ttestb $1,%b4\n\t"
400         "je 2f\n\t"
401         "movsb\n"
402         "2:"
403         : "=&c" (d0), "=&D" (d1), "=&S" (d2)
404         :"0" (n/4), "q" (n),"1" ((long) to),"2" ((long) from)
405         : "memory");
406 return (to);
408 @end example
410 @noindent
411 @cindex gas
412 TCC includes its own x86 inline assembler with a @code{gas}-like (GNU
413 assembler) syntax. No intermediate files are generated. GCC 3.x named
414 operands are supported.
416 @end itemize
418 @section TinyCC extensions
420 @itemize
422 @item @code{__TINYC__} is a predefined macro to @code{1} to
423 indicate that you use TCC.
425 @item @code{#!} at the start of a line is ignored to allow scripting.
427 @item Binary digits can be entered (@code{0b101} instead of
428 @code{5}).
430 @item @code{__BOUNDS_CHECKING_ON} is defined if bound checking is activated.
432 @end itemize
434 @chapter TinyCC Assembler
436 Since version 0.9.16, TinyCC integrates its own assembler. TinyCC
437 assembler supports a gas-like syntax (GNU assembler). You can
438 desactivate assembler support if you want a smaller TinyCC executable
439 (the C compiler does not rely on the assembler).
441 TinyCC Assembler is used to handle files with @file{.S} (C
442 preprocessed assembler) and @file{.s} extensions. It is also used to
443 handle the GNU inline assembler with the @code{asm} keyword.
445 @section Syntax
447 TinyCC Assembler supports most of the gas syntax. The tokens are the
448 same as C.
450 @itemize
452 @item C and C++ comments are supported.
454 @item Identifiers are the same as C, so you cannot use '.' or '$'.
456 @item Only 32 bit integer numbers are supported.
458 @end itemize
460 @section Expressions
462 @itemize
464 @item Integers in decimal, octal and hexa are supported.
466 @item Unary operators: +, -, ~.
468 @item Binary operators in decreasing priority order:
470 @enumerate
471 @item *, /, %
472 @item &, |, ^
473 @item +, -
474 @end enumerate
476 @item A value is either an absolute number or a label plus an offset. 
477 All operators accept absolute values except '+' and '-'. '+' or '-' can be
478 used to add an offset to a label. '-' supports two labels only if they
479 are the same or if they are both defined and in the same section.
481 @end itemize
483 @section Labels
485 @itemize
487 @item All labels are considered as local, except undefined ones.
489 @item Numeric labels can be used as local @code{gas}-like labels. 
490 They can be defined several times in the same source. Use 'b'
491 (backward) or 'f' (forward) as suffix to reference them:
493 @example
494  1:
495       jmp 1b /* jump to '1' label before */
496       jmp 1f /* jump to '1' label after */
497  1:
498 @end example
500 @end itemize
502 @section Directives
503 @cindex assembler directives
504 @cindex directives, assembler
505 @cindex .align
506 @cindex .skip
507 @cindex .space
508 @cindex .byte
509 @cindex .word
510 @cindex .short
511 @cindex .int
512 @cindex .long
514 All directives are preceeded by a '.'. The following directives are
515 supported:
517 @itemize
518 @item .align n[,value]
519 @item .skip n[,value]
520 @item .space n[,value]
521 @item .byte value1[,value2...]
522 @item .word value1[,value2...]
523 @item .short value1[,value2...]
524 @item .int value1[,value2...]
525 @item .long value1[,value2...]
526 @end itemize
528 @section X86 Assembler
529 @cindex assembler
531 All X86 opcodes are supported. Only ATT syntax is supported (source
532 then destination operand order). If no size suffix is given, TinyCC
533 tries to guess it from the operand sizes.
535 Currently, MMX opcodes are supported but not SSE ones.
537 @chapter TinyCC Linker
538 @cindex linker
540 @section ELF file generation
541 @cindex ELF
543 TCC can directly output relocatable ELF files (object files),
544 executable ELF files and dynamic ELF libraries without relying on an
545 external linker.
547 Dynamic ELF libraries can be output but the C compiler does not generate
548 position independent code (PIC). It means that the dynamic librairy
549 code generated by TCC cannot be factorized among processes yet.
551 TCC linker cannot currently eliminate unused object code. But TCC
552 will soon integrate a novel feature not found in GNU tools: unused code
553 will be eliminated at the function or variable level, provided you only
554 use TCC to compile your files.
556 @section ELF file loader
558 TCC can load ELF object files, archives (.a files) and dynamic
559 libraries (.so).
561 @section GNU Linker Scripts
562 @cindex scripts, linker
563 @cindex linker scripts
564 @cindex GROUP, linker command
565 @cindex FILE, linker command
567 Because on many Linux systems some dynamic libraries (such as
568 @file{/usr/lib/libc.so}) are in fact GNU ld link scripts (horrible!),
569 the TCC linker also supports a subset of GNU ld scripts.
571 The @code{GROUP} and @code{FILE} commands are supported.
573 Example from @file{/usr/lib/libc.so}:
574 @example
575 /* GNU ld script
576    Use the shared library, but some functions are only in
577    the static library, so try that secondarily.  */
578 GROUP ( /lib/libc.so.6 /usr/lib/libc_nonshared.a )
579 @end example
581 @node Bounds
582 @chapter TinyCC Memory and Bound checks
583 @cindex bound checks
584 @cindex memory checks
586 This feature is activated with the @option{-b} (@pxref{Invoke}).
588 Note that pointer size is @emph{unchanged} and that code generated
589 with bound checks is @emph{fully compatible} with unchecked
590 code. When a pointer comes from unchecked code, it is assumed to be
591 valid. Even very obscure C code with casts should work correctly.
593 For more information about the ideas behind this method, see
594 @url{http://www.doc.ic.ac.uk/~phjk/BoundsChecking.html}.
596 Here are some examples of caught errors:
598 @table @asis
600 @item Invalid range with standard string function:
601 @example
603     char tab[10];
604     memset(tab, 0, 11);
606 @end example
608 @item Out of bounds-error in global or local arrays:
609 @example
611     int tab[10];
612     for(i=0;i<11;i++) @{
613         sum += tab[i];
614     @}
616 @end example
618 @item Out of bounds-error in malloc'ed data:
619 @example
621     int *tab;
622     tab = malloc(20 * sizeof(int));
623     for(i=0;i<21;i++) @{
624         sum += tab4[i];
625     @}
626     free(tab);
628 @end example
630 @item Access of freed memory:
631 @example
633     int *tab;
634     tab = malloc(20 * sizeof(int));
635     free(tab);
636     for(i=0;i<20;i++) @{
637         sum += tab4[i];
638     @}
640 @end example
642 @item Double free:
643 @example
645     int *tab;
646     tab = malloc(20 * sizeof(int));
647     free(tab);
648     free(tab);
650 @end example
652 @end table
654 @node Libtcc
655 @chapter The @code{libtcc} library
657 The @code{libtcc} library enables you to use TCC as a backend for
658 dynamic code generation. 
660 Read the @file{libtcc.h} to have an overview of the API. Read
661 @file{libtcc_test.c} to have a very simple example.
663 The idea consists in giving a C string containing the program you want
664 to compile directly to @code{libtcc}. Then you can access to any global
665 symbol (function or variable) defined.
667 @chapter Developer's guide
669 This chapter gives some hints to understand how TCC works. You can skip
670 it if you do not intend to modify the TCC code.
672 @section File reading
674 The @code{BufferedFile} structure contains the context needed to read a
675 file, including the current line number. @code{tcc_open()} opens a new
676 file and @code{tcc_close()} closes it. @code{inp()} returns the next
677 character.
679 @section Lexer
681 @code{next()} reads the next token in the current
682 file. @code{next_nomacro()} reads the next token without macro
683 expansion.
685 @code{tok} contains the current token (see @code{TOK_xxx})
686 constants. Identifiers and keywords are also keywords. @code{tokc}
687 contains additional infos about the token (for example a constant value
688 if number or string token).
690 @section Parser
692 The parser is hardcoded (yacc is not necessary). It does only one pass,
693 except:
695 @itemize
697 @item For initialized arrays with unknown size, a first pass 
698 is done to count the number of elements.
700 @item For architectures where arguments are evaluated in 
701 reverse order, a first pass is done to reverse the argument order.
703 @end itemize
705 @section Types
707 The types are stored in a single 'int' variable. It was choosen in the
708 first stages of development when tcc was much simpler. Now, it may not
709 be the best solution.
711 @example
712 #define VT_INT        0  /* integer type */
713 #define VT_BYTE       1  /* signed byte type */
714 #define VT_SHORT      2  /* short type */
715 #define VT_VOID       3  /* void type */
716 #define VT_PTR        4  /* pointer */
717 #define VT_ENUM       5  /* enum definition */
718 #define VT_FUNC       6  /* function type */
719 #define VT_STRUCT     7  /* struct/union definition */
720 #define VT_FLOAT      8  /* IEEE float */
721 #define VT_DOUBLE     9  /* IEEE double */
722 #define VT_LDOUBLE   10  /* IEEE long double */
723 #define VT_BOOL      11  /* ISOC99 boolean type */
724 #define VT_LLONG     12  /* 64 bit integer */
725 #define VT_LONG      13  /* long integer (NEVER USED as type, only
726                             during parsing) */
727 #define VT_BTYPE      0x000f /* mask for basic type */
728 #define VT_UNSIGNED   0x0010  /* unsigned type */
729 #define VT_ARRAY      0x0020  /* array type (also has VT_PTR) */
730 #define VT_BITFIELD   0x0040  /* bitfield modifier */
732 #define VT_STRUCT_SHIFT 16   /* structure/enum name shift (16 bits left) */
733 @end example
735 When a reference to another type is needed (for pointers, functions and
736 structures), the @code{32 - VT_STRUCT_SHIFT} high order bits are used to
737 store an identifier reference.
739 The @code{VT_UNSIGNED} flag can be set for chars, shorts, ints and long
740 longs.
742 Arrays are considered as pointers @code{VT_PTR} with the flag
743 @code{VT_ARRAY} set.
745 The @code{VT_BITFIELD} flag can be set for chars, shorts, ints and long
746 longs. If it is set, then the bitfield position is stored from bits
747 VT_STRUCT_SHIFT to VT_STRUCT_SHIFT + 5 and the bit field size is stored
748 from bits VT_STRUCT_SHIFT + 6 to VT_STRUCT_SHIFT + 11.
750 @code{VT_LONG} is never used except during parsing.
752 During parsing, the storage of an object is also stored in the type
753 integer:
755 @example
756 #define VT_EXTERN  0x00000080  /* extern definition */
757 #define VT_STATIC  0x00000100  /* static variable */
758 #define VT_TYPEDEF 0x00000200  /* typedef definition */
759 @end example
761 @section Symbols
763 All symbols are stored in hashed symbol stacks. Each symbol stack
764 contains @code{Sym} structures.
766 @code{Sym.v} contains the symbol name (remember
767 an idenfier is also a token, so a string is never necessary to store
768 it). @code{Sym.t} gives the type of the symbol. @code{Sym.r} is usually
769 the register in which the corresponding variable is stored. @code{Sym.c} is
770 usually a constant associated to the symbol.
772 Four main symbol stacks are defined:
774 @table @code
776 @item define_stack
777 for the macros (@code{#define}s).
779 @item global_stack
780 for the global variables, functions and types.
782 @item local_stack
783 for the local variables, functions and types.
785 @item global_label_stack
786 for the local labels (for @code{goto}).
788 @item label_stack
789 for GCC block local labels (see the @code{__label__} keyword).
791 @end table
793 @code{sym_push()} is used to add a new symbol in the local symbol
794 stack. If no local symbol stack is active, it is added in the global
795 symbol stack.
797 @code{sym_pop(st,b)} pops symbols from the symbol stack @var{st} until
798 the symbol @var{b} is on the top of stack. If @var{b} is NULL, the stack
799 is emptied.
801 @code{sym_find(v)} return the symbol associated to the identifier
802 @var{v}. The local stack is searched first from top to bottom, then the
803 global stack.
805 @section Sections
807 The generated code and datas are written in sections. The structure
808 @code{Section} contains all the necessary information for a given
809 section. @code{new_section()} creates a new section. ELF file semantics
810 is assumed for each section.
812 The following sections are predefined:
814 @table @code
816 @item text_section
817 is the section containing the generated code. @var{ind} contains the
818 current position in the code section.
820 @item data_section
821 contains initialized data
823 @item bss_section
824 contains uninitialized data
826 @item bounds_section
827 @itemx lbounds_section
828 are used when bound checking is activated
830 @item stab_section
831 @itemx stabstr_section
832 are used when debugging is actived to store debug information
834 @item symtab_section
835 @itemx strtab_section
836 contain the exported symbols (currently only used for debugging).
838 @end table
840 @section Code generation
841 @cindex code generation
843 @subsection Introduction
845 The TCC code generator directly generates linked binary code in one
846 pass. It is rather unusual these days (see gcc for example which
847 generates text assembly), but it can be very fast and surprisingly
848 little complicated.
850 The TCC code generator is register based. Optimization is only done at
851 the expression level. No intermediate representation of expression is
852 kept except the current values stored in the @emph{value stack}.
854 On x86, three temporary registers are used. When more registers are
855 needed, one register is spilled into a new temporary variable on the stack.
857 @subsection The value stack
858 @cindex value stack, introduction
860 When an expression is parsed, its value is pushed on the value stack
861 (@var{vstack}). The top of the value stack is @var{vtop}. Each value
862 stack entry is the structure @code{SValue}.
864 @code{SValue.t} is the type. @code{SValue.r} indicates how the value is
865 currently stored in the generated code. It is usually a CPU register
866 index (@code{REG_xxx} constants), but additional values and flags are
867 defined:
869 @example
870 #define VT_CONST     0x00f0
871 #define VT_LLOCAL    0x00f1
872 #define VT_LOCAL     0x00f2
873 #define VT_CMP       0x00f3
874 #define VT_JMP       0x00f4
875 #define VT_JMPI      0x00f5
876 #define VT_LVAL      0x0100
877 #define VT_SYM       0x0200
878 #define VT_MUSTCAST  0x0400
879 #define VT_MUSTBOUND 0x0800
880 #define VT_BOUNDED   0x8000
881 #define VT_LVAL_BYTE     0x1000
882 #define VT_LVAL_SHORT    0x2000
883 #define VT_LVAL_UNSIGNED 0x4000
884 #define VT_LVAL_TYPE     (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
885 @end example
887 @table @code
889 @item VT_CONST
890 indicates that the value is a constant. It is stored in the union
891 @code{SValue.c}, depending on its type.
893 @item VT_LOCAL
894 indicates a local variable pointer at offset @code{SValue.c.i} in the
895 stack.
897 @item VT_CMP
898 indicates that the value is actually stored in the CPU flags (i.e. the
899 value is the consequence of a test). The value is either 0 or 1. The
900 actual CPU flags used is indicated in @code{SValue.c.i}. 
902 If any code is generated which destroys the CPU flags, this value MUST be
903 put in a normal register.
905 @item VT_JMP
906 @itemx VT_JMPI
907 indicates that the value is the consequence of a conditional jump. For VT_JMP,
908 it is 1 if the jump is taken, 0 otherwise. For VT_JMPI it is inverted.
910 These values are used to compile the @code{||} and @code{&&} logical
911 operators.
913 If any code is generated, this value MUST be put in a normal
914 register. Otherwise, the generated code won't be executed if the jump is
915 taken.
917 @item VT_LVAL
918 is a flag indicating that the value is actually an lvalue (left value of
919 an assignment). It means that the value stored is actually a pointer to
920 the wanted value. 
922 Understanding the use @code{VT_LVAL} is very important if you want to
923 understand how TCC works.
925 @item VT_LVAL_BYTE
926 @itemx VT_LVAL_SHORT
927 @itemx VT_LVAL_UNSIGNED
928 if the lvalue has an integer type, then these flags give its real
929 type. The type alone is not enough in case of cast optimisations.
931 @item VT_LLOCAL
932 is a saved lvalue on the stack. @code{VT_LLOCAL} should be eliminated
933 ASAP because its semantics are rather complicated.
935 @item VT_MUSTCAST
936 indicates that a cast to the value type must be performed if the value
937 is used (lazy casting).
939 @item VT_SYM
940 indicates that the symbol @code{SValue.sym} must be added to the constant.
942 @item VT_MUSTBOUND
943 @itemx VT_BOUNDED
944 are only used for optional bound checking.
946 @end table
948 @subsection Manipulating the value stack
949 @cindex value stack
951 @code{vsetc()} and @code{vset()} pushes a new value on the value
952 stack. If the previous @var{vtop} was stored in a very unsafe place(for
953 example in the CPU flags), then some code is generated to put the
954 previous @var{vtop} in a safe storage.
956 @code{vpop()} pops @var{vtop}. In some cases, it also generates cleanup
957 code (for example if stacked floating point registers are used as on
958 x86).
960 The @code{gv(rc)} function generates code to evaluate @var{vtop} (the
961 top value of the stack) into registers. @var{rc} selects in which
962 register class the value should be put. @code{gv()} is the @emph{most
963 important function} of the code generator.
965 @code{gv2()} is the same as @code{gv()} but for the top two stack
966 entries.
968 @subsection CPU dependent code generation
969 @cindex CPU dependent
970 See the @file{i386-gen.c} file to have an example.
972 @table @code
974 @item load()
975 must generate the code needed to load a stack value into a register.
977 @item store()
978 must generate the code needed to store a register into a stack value
979 lvalue.
981 @item gfunc_start()
982 @itemx gfunc_param()
983 @itemx gfunc_call()
984 should generate a function call
986 @item gfunc_prolog()
987 @itemx gfunc_epilog()
988 should generate a function prolog/epilog.
990 @item gen_opi(op)
991 must generate the binary integer operation @var{op} on the two top
992 entries of the stack which are guaranted to contain integer types.
994 The result value should be put on the stack.
996 @item gen_opf(op)
997 same as @code{gen_opi()} for floating point operations. The two top
998 entries of the stack are guaranted to contain floating point values of
999 same types.
1001 @item gen_cvt_itof()
1002 integer to floating point conversion.
1004 @item gen_cvt_ftoi()
1005 floating point to integer conversion.
1007 @item gen_cvt_ftof()
1008 floating point to floating point of different size conversion.
1010 @item gen_bounded_ptr_add()
1011 @item gen_bounded_ptr_deref()
1012 are only used for bounds checking.
1014 @end table
1016 @section Optimizations done
1017 @cindex optimizations
1018 @cindex constant propagation
1019 @cindex strength reduction
1020 @cindex comparison operators
1021 @cindex caching processor flags
1022 @cindex flags, caching
1023 @cindex jump optimization
1024 Constant propagation is done for all operations. Multiplications and
1025 divisions are optimized to shifts when appropriate. Comparison
1026 operators are optimized by maintaining a special cache for the
1027 processor flags. &&, || and ! are optimized by maintaining a special
1028 'jump target' value. No other jump optimization is currently performed
1029 because it would require to store the code in a more abstract fashion.
1031 @unnumbered Concept Index
1032 @printindex cp
1034 @bye
1036 @c Local variables:
1037 @c fill-column: 78
1038 @c texinfo-column-for-description: 32
1039 @c End: