updated
[tinycc.git] / tcc-doc.texi
blobdf50133f11807ae8a5475082b48a9a95824a93e9
1 \input texinfo @c -*- texinfo -*-
3 @settitle Tiny C Compiler Reference Documentation
4 @titlepage
5 @sp 7
6 @center @titlefont{Tiny C Compiler Reference Documentation}
7 @sp 3
8 @end titlepage
10 @chapter Introduction
12 TinyCC (aka TCC) is a small but hyper fast C compiler. Unlike other C
13 compilers, it is meant to be self-suffisant: you do not need an
14 external assembler or linker because TCC does that for you.
16 TCC compiles so @emph{fast} that even for big projects @code{Makefile}s may
17 not be necessary. 
19 TCC not only supports ANSI C, but also most of the new ISO C99
20 standard and many GNUC extensions.
22 TCC can also be used to make @emph{C scripts}, i.e. pieces of C source
23 that you run as a Perl or Python script. Compilation is so fast that
24 your script will be as fast as if it was an executable.
26 TCC can also automatically generate memory and bound checks
27 (@xref{bounds}) while allowing all C pointers operations. TCC can do
28 these checks even if non patched libraries are used.
30 With @code{libtcc}, you can use TCC as a backend for dynamic code
31 generation (@xref{libtcc}).
33 @node invoke
34 @chapter Command line invocation
36 @section Quick start
38 @example
39 usage: tcc [-c] [-o outfile] [-Bdir] [-bench] [-Idir] [-Dsym[=val]] [-Usym]
40            [-g] [-b] [-Ldir] [-llib] [-shared] [-static]
41            [--] infile1 [infile2... --] [infile_args...]
42 @end example
44 TCC options are a very much like gcc. The main difference is that TCC
45 can also execute directly the resulting program and give it runtime
46 arguments.
48 Here are some examples to understand the logic:
50 @table @code
51 @item tcc a.c
52 Compile a.c and execute it directly
54 @item tcc a.c arg1
55 Compile a.c and execute it directly. arg1 is given as first argument to
56 the @code{main()} of a.c.
58 @item tcc -- a.c b.c -- arg1
59 Compile a.c and b.c, link them together and execute them. arg1 is given
60 as first argument to the @code{main()} of the resulting program. Because
61 multiple C files are specified, @code{--} are necessary to clearly separate the
62 program arguments from the TCC options.
64 @item tcc -o myprog a.c b.c
65 Compile a.c and b.c, link them and generate the executable myprog.
67 @item tcc -o myprog a.o b.o
68 link a.o and b.o together and generate the executable myprog.
70 @item tcc -c -o a.o a.c
71 Compile a.c and generate object file a.o
73 @end table
75 Scripting:
77 TCC can be invoked from @emph{scripts}, just as shell scripts. You just
78 need to add @code{#!/usr/local/bin/tcc} at the start of your C source:
80 @example
81 #!/usr/local/bin/tcc
82 #include <stdio.h>
84 int main() 
86     printf("Hello World\n");
87     return 0;
89 @end example
91 @section Option summary
93 General Options:
95 @table @samp
96 @item -c
97 Generate an object file (@samp{-o} option must also be given).
99 @item -o outfile
100 Put object file, executable, or dll into output file @file{outfile}.
102 @item -Bdir
103 Set the path where the tcc internal libraries can be found (default is
104 @file{PREFIX/lib/tcc}).
106 @item -bench
107 Output compilation statistics.
108 @end table
110 Preprocessor options:
112 @table @samp
113 @item -Idir
114 Specify an additionnal include path. Include paths are searched in the
115 order they are specified.
117 System include paths are always searched after. The default system
118 include paths are: @file{/usr/local/include}, @file{/usr/include}
119 and @file{PREFIX/lib/tcc/include}. (@code{PREFIX} is usually
120 @file{/usr} or @file{/usr/local}).
122 @item -Dsym[=val]
123 Define preprocessor symbol 'sym' to
124 val. If val is not present, its value is '1'. Function-like macros can
125 also be defined: @code{'-DF(a)=a+1'}
127 @item -Usym
128 Undefine preprocessor symbol 'sym'.
129 @end table
131 C compiler options:
133 @table @samp
134 @item -g
135 Generate run time debug information so that you get clear run time
136 error messages: @code{ test.c:68: in function 'test5()': dereferencing
137 invalid pointer} instead of the laconic @code{Segmentation
138 fault}.
140 @item -b
141 Generate additionnal support code to check
142 memory allocations and array/pointer bounds. '-g' is implied. Note
143 that the generated code is slower and bigger in this case.
144 @end table
146 Linker options:
148 @table @samp
149 @item -Ldir
150 Specify an additionnal static library path for the @samp{-l} option. The
151 default library paths are @file{/usr/local/lib}, @file{/usr/lib} and @file{/lib}.
153 @item -lxxx
154 Link your program with dynamic library libxxx.so or static library
155 libxxx.a. The library is searched in the paths specified by the
156 @samp{-L} option.
158 @item -shared
159 Generate a shared library instead of an executable (@samp{-o} option
160 must also be given).
162 @item -static
163 Generate a statically linked executable (default is a shared linked
164 executable) (@samp{-o} option must also be given).
166 @end table
168 @chapter C language support
170 @section ANSI C
172 TCC implements all the ANSI C standard, including structure bit fields
173 and floating point numbers (@code{long double}, @code{double}, and
174 @code{float} fully supported). The following limitations are known:
176 @itemize
177  @item The preprocessor tokens are the same as C. It means that in some
178   rare cases, preprocessed numbers are not handled exactly as in ANSI
179   C. This approach has the advantage of being simpler and FAST!
180 @end itemize
182 @section ISOC99 extensions
184 TCC implements many features of the new C standard: ISO C99. Currently
185 missing items are: complex and imaginary numbers and variable length
186 arrays.
188 Currently implemented ISOC99 features:
190 @itemize
192 @item 64 bit @code{'long long'} types are fully supported.
194 @item The boolean type @code{'_Bool'} is supported.
196 @item @code{'__func__'} is a string variable containing the current
197 function name.
199 @item Variadic macros: @code{__VA_ARGS__} can be used for
200    function-like macros:
201 @example
202     #define dprintf(level, __VA_ARGS__) printf(__VA_ARGS__)
203 @end example
204 @code{dprintf} can then be used with a variable number of parameters.
206 @item Declarations can appear anywhere in a block (as in C++).
208 @item Array and struct/union elements can be initialized in any order by
209   using designators:
210 @example
211     struct { int x, y; } st[10] = { [0].x = 1, [0].y = 2 };
213     int tab[10] = { 1, 2, [5] = 5, [9] = 9};
214 @end example
215     
216 @item Compound initializers are supported:
217 @example
218     int *p = (int []){ 1, 2, 3 };
219 @end example
220 to initialize a pointer pointing to an initialized array. The same
221 works for structures and strings.
223 @item Hexadecimal floating point constants are supported:
224 @example
225           double d = 0x1234p10;
226 @end example
227 is the same as writing 
228 @example
229           double d = 4771840.0;
230 @end example
232 @item @code{'inline'} keyword is ignored.
234 @item @code{'restrict'} keyword is ignored.
235 @end itemize
237 @section GNU C extensions
239 TCC implements some GNU C extensions:
241 @itemize
243 @item array designators can be used without '=': 
244 @example
245     int a[10] = { [0] 1, [5] 2, 3, 4 };
246 @end example
248 @item Structure field designators can be a label: 
249 @example
250     struct { int x, y; } st = { x: 1, y: 1};
251 @end example
252 instead of
253 @example
254     struct { int x, y; } st = { .x = 1, .y = 1};
255 @end example
257 @item @code{'\e'} is ASCII character 27.
259 @item case ranges : ranges can be used in @code{case}s:
260 @example
261     switch(a) {
262     case 1 ... 9:
263           printf("range 1 to 9\n");
264           break;
265     default:
266           printf("unexpected\n");
267           break;
268     }
269 @end example
271 @item The keyword @code{__attribute__} is handled to specify variable or
272 function attributes. The following attributes are supported:
273   @itemize
274   @item @code{aligned(n)}: align data to n bytes (must be a power of two).
276   @item @code{section(name)}: generate function or data in assembly
277   section name (name is a string containing the section name) instead
278   of the default section.
280   @item @code{unused}: specify that the variable or the function is unused.
282   @item @code{cdecl}: use standard C calling convention.
284   @item @code{stdcall}: use Pascal-like calling convention.
286   @end itemize
288 Here are some examples:
289 @example
290     int a __attribute__ ((aligned(8), section(".mysection")));
291 @end example
293 align variable @code{'a'} to 8 bytes and put it in section @code{.mysection}.
295 @example
296     int my_add(int a, int b) __attribute__ ((section(".mycodesection"))) 
297     {
298         return a + b;
299     }
300 @end example
302 generate function @code{'my_add'} in section @code{.mycodesection}.
304 @item GNU style variadic macros:
305 @example
306     #define dprintf(fmt, args...) printf(fmt, ## args)
308     dprintf("no arg\n");
309     dprintf("one arg %d\n", 1);
310 @end example
312 @end itemize
314 @section TinyCC extensions
316 @itemize
318 @item @code{__TINYC__} is a predefined macro to @code{'1'} to
319 indicate that you use TCC.
321 @item @code{'#!'} at the start of a line is ignored to allow scripting.
323 @item Binary digits can be entered (@code{'0b101'} instead of
324 @code{'5'}).
326 @item @code{__BOUNDS_CHECKING_ON} is defined if bound checking is activated.
328 @end itemize
330 @chapter TinyCC Linker
332 @section ELF file generation
334 TCC can directly output relocatable ELF files (object files),
335 executable ELF files and dynamic ELF libraries without relying on an
336 external linker.
338 Dynamic ELF libraries can be output but the C compiler does not generate
339 position independant code (PIC) code. It means that the dynamic librairy
340 code generated by TCC cannot be factorized among processes yet.
342 TCC linker cannot currently suppress unused object code. But TCC
343 will soon integrate a novel feature not found in GNU tools: unused code
344 will be suppressed at the function or variable level, provided you only
345 use TCC to compile your files.
347 @section ELF file loader
349 TCC can load ELF object files, archives (.a files) and dynamic
350 libraries (.so).
352 @section GNU Linker Scripts
354 Because on many Linux systems some dynamic libraries (such as
355 @file{/usr/lib/libc.so}) are in fact GNU ld link scripts (horrible!),
356 TCC linker also support a subset of GNU ld scripts.
358 The @code{GROUP} and @code{FILE} commands are supported.
360 Example from @file{/usr/lib/libc.so}:
361 @example
362 /* GNU ld script
363    Use the shared library, but some functions are only in
364    the static library, so try that secondarily.  */
365 GROUP ( /lib/libc.so.6 /usr/lib/libc_nonshared.a )
366 @end example
368 @node bounds
369 @chapter TinyCC Memory and Bound checks
371 This feature is activated with the @code{'-b'} (@xref{invoke}).
373 Note that pointer size is @emph{unchanged} and that code generated
374 with bound checks is @emph{fully compatible} with unchecked
375 code. When a pointer comes from unchecked code, it is assumed to be
376 valid. Even very obscure C code with casts should work correctly.
378 To have more information about the ideas behind this method, check at 
379 @url{http://www.doc.ic.ac.uk/~phjk/BoundsChecking.html}.
381 Here are some examples of catched errors:
383 @table @asis
385 @item Invalid range with standard string function:
386 @example
388     char tab[10];
389     memset(tab, 0, 11);
391 @end example
393 @item Bound error in global or local arrays:
394 @example
396     int tab[10];
397     for(i=0;i<11;i++) {
398         sum += tab[i];
399     }
401 @end example
403 @item Bound error in allocated data:
404 @example
406     int *tab;
407     tab = malloc(20 * sizeof(int));
408     for(i=0;i<21;i++) {
409         sum += tab4[i];
410     }
411     free(tab);
413 @end example
415 @item Access to a freed region:
416 @example
418     int *tab;
419     tab = malloc(20 * sizeof(int));
420     free(tab);
421     for(i=0;i<20;i++) {
422         sum += tab4[i];
423     }
425 @end example
427 @item Freeing an already freed region:
428 @example
430     int *tab;
431     tab = malloc(20 * sizeof(int));
432     free(tab);
433     free(tab);
435 @end example
437 @end table
439 @node libtcc
440 @chapter The @code{libtcc} library
442 The @code{libtcc} library enables you to use TCC as a backend for
443 dynamic code generation. 
445 Read the @file{libtcc.h} to have an overview of the API. Read
446 @file{libtcc_test.c} to have a very simple example.
448 The idea consists in giving a C string containing the program you want
449 to compile directly to @code{libtcc}. Then the @code{main()} function of
450 the compiled string can be launched.
452 @chapter Developper's guide
454 This chapter gives some hints to understand how TCC works. You can skip
455 it if you do not intend to modify the TCC code.
457 @section File reading
459 The @code{BufferedFile} structure contains the context needed to read a
460 file, including the current line number. @code{tcc_open()} opens a new
461 file and @code{tcc_close()} closes it. @code{inp()} returns the next
462 character.
464 @section Lexer
466 @code{next()} reads the next token in the current
467 file. @code{next_nomacro()} reads the next token without macro
468 expansion.
470 @code{tok} contains the current token (see @code{TOK_xxx})
471 constants. Identifiers and keywords are also keywords. @code{tokc}
472 contains additionnal infos about the token (for example a constant value
473 if number or string token).
475 @section Parser
477 The parser is hardcoded (yacc is not necessary). It does only one pass,
478 except:
480 @itemize
482 @item For initialized arrays with unknown size, a first pass 
483 is done to count the number of elements.
485 @item For architectures where arguments are evaluated in 
486 reverse order, a first pass is done to reverse the argument order.
488 @end itemize
490 @section Types
492 The types are stored in a single 'int' variable. It was choosen in the
493 first stages of development when tcc was much simpler. Now, it may not
494 be the best solution.
496 @example
497 #define VT_INT        0  /* integer type */
498 #define VT_BYTE       1  /* signed byte type */
499 #define VT_SHORT      2  /* short type */
500 #define VT_VOID       3  /* void type */
501 #define VT_PTR        4  /* pointer */
502 #define VT_ENUM       5  /* enum definition */
503 #define VT_FUNC       6  /* function type */
504 #define VT_STRUCT     7  /* struct/union definition */
505 #define VT_FLOAT      8  /* IEEE float */
506 #define VT_DOUBLE     9  /* IEEE double */
507 #define VT_LDOUBLE   10  /* IEEE long double */
508 #define VT_BOOL      11  /* ISOC99 boolean type */
509 #define VT_LLONG     12  /* 64 bit integer */
510 #define VT_LONG      13  /* long integer (NEVER USED as type, only
511                             during parsing) */
512 #define VT_BTYPE      0x000f /* mask for basic type */
513 #define VT_UNSIGNED   0x0010  /* unsigned type */
514 #define VT_ARRAY      0x0020  /* array type (also has VT_PTR) */
515 #define VT_BITFIELD   0x0040  /* bitfield modifier */
517 #define VT_STRUCT_SHIFT 16   /* structure/enum name shift (16 bits left) */
518 @end example
520 When a reference to another type is needed (for pointers, functions and
521 structures), the @code{32 - VT_STRUCT_SHIFT} high order bits are used to
522 store an identifier reference.
524 The @code{VT_UNSIGNED} flag can be set for chars, shorts, ints and long
525 longs.
527 Arrays are considered as pointers @code{VT_PTR} with the flag
528 @code{VT_ARRAY} set.
530 The @code{VT_BITFIELD} flag can be set for chars, shorts, ints and long
531 longs. If it is set, then the bitfield position is stored from bits
532 VT_STRUCT_SHIFT to VT_STRUCT_SHIFT + 5 and the bit field size is stored
533 from bits VT_STRUCT_SHIFT + 6 to VT_STRUCT_SHIFT + 11.
535 @code{VT_LONG} is never used except during parsing.
537 During parsing, the storage of an object is also stored in the type
538 integer:
540 @example
541 #define VT_EXTERN  0x00000080  /* extern definition */
542 #define VT_STATIC  0x00000100  /* static variable */
543 #define VT_TYPEDEF 0x00000200  /* typedef definition */
544 @end example
546 @section Symbols
548 All symbols are stored in hashed symbol stacks. Each symbol stack
549 contains @code{Sym} structures.
551 @code{Sym.v} contains the symbol name (remember
552 an idenfier is also a token, so a string is never necessary to store
553 it). @code{Sym.t} gives the type of the symbol. @code{Sym.r} is usually
554 the register in which the corresponding variable is stored. @code{Sym.c} is
555 usually a constant associated to the symbol.
557 Four main symbol stacks are defined:
559 @table @code
561 @item define_stack
562 for the macros (@code{#define}s).
564 @item global_stack
565 for the global variables, functions and types.
567 @item local_stack
568 for the local variables, functions and types.
570 @item label_stack
571 for the local labels (for @code{goto}).
573 @end table
575 @code{sym_push()} is used to add a new symbol in the local symbol
576 stack. If no local symbol stack is active, it is added in the global
577 symbol stack.
579 @code{sym_pop(st,b)} pops symbols from the symbol stack @var{st} until
580 the symbol @var{b} is on the top of stack. If @var{b} is NULL, the stack
581 is emptied.
583 @code{sym_find(v)} return the symbol associated to the identifier
584 @var{v}. The local stack is searched first from top to bottom, then the
585 global stack.
587 @section Sections
589 The generated code and datas are written in sections. The structure
590 @code{Section} contains all the necessary information for a given
591 section. @code{new_section()} creates a new section. ELF file semantics
592 is assumed for each section.
594 The following sections are predefined:
596 @table @code
598 @item text_section
599 is the section containing the generated code. @var{ind} contains the
600 current position in the code section.
602 @item data_section
603 contains initialized data
605 @item bss_section
606 contains uninitialized data
608 @item bounds_section
609 @itemx lbounds_section
610 are used when bound checking is activated
612 @item stab_section
613 @itemx stabstr_section
614 are used when debugging is actived to store debug information
616 @item symtab_section
617 @itemx strtab_section
618 contain the exported symbols (currently only used for debugging).
620 @end table
622 @section Code generation
624 @subsection Introduction
626 The TCC code generator directly generates linked binary code in one
627 pass. It is rather unusual these days (see gcc for example which
628 generates text assembly), but it allows to be very fast and surprisingly
629 not so complicated.
631 The TCC code generator is register based. Optimization is only done at
632 the expression level. No intermediate representation of expression is
633 kept except the current values stored in the @emph{value stack}.
635 On x86, three temporary registers are used. When more registers are
636 needed, one register is flushed in a new local variable.
638 @subsection The value stack
640 When an expression is parsed, its value is pushed on the value stack
641 (@var{vstack}). The top of the value stack is @var{vtop}. Each value
642 stack entry is the structure @code{SValue}.
644 @code{SValue.t} is the type. @code{SValue.r} indicates how the value is
645 currently stored in the generated code. It is usually a CPU register
646 index (@code{REG_xxx} constants), but additionnal values and flags are
647 defined:
649 @example
650 #define VT_CONST     0x00f0  /* constant in vc 
651                               (must be first non register value) */
652 #define VT_LLOCAL    0x00f1  /* lvalue, offset on stack */
653 #define VT_LOCAL     0x00f2  /* offset on stack */
654 #define VT_CMP       0x00f3  /* the value is stored in processor flags (in vc) */
655 #define VT_JMP       0x00f4  /* value is the consequence of jmp true (even) */
656 #define VT_JMPI      0x00f5  /* value is the consequence of jmp false (odd) */
657 #define VT_LVAL      0x0100  /* var is an lvalue */
658 #define VT_FORWARD   0x0200  /* value is forward reference */
659 #define VT_MUSTCAST  0x0400  /* value must be casted to be correct (used for
660                                 char/short stored in integer registers) */
661 #define VT_MUSTBOUND 0x0800  /* bound checking must be done before
662                                 dereferencing value */
663 #define VT_BOUNDED   0x8000  /* value is bounded. The address of the
664                                 bounding function call point is in vc */
665 #define VT_LVAL_BYTE     0x1000  /* lvalue is a byte */
666 #define VT_LVAL_SHORT    0x2000  /* lvalue is a short */
667 #define VT_LVAL_UNSIGNED 0x4000  /* lvalue is unsigned */
668 #define VT_LVAL_TYPE     (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
669 @end example
671 @table @code
673 @item VT_CONST
674 indicates that the value is a constant. It is stored in the union
675 @code{SValue.c}, depending on its type.
677 @item VT_LOCAL
678 indicates a local variable pointer at offset @code{SValue.c.i} in the
679 stack.
681 @item VT_CMP
682 indicates that the value is actually stored in the CPU flags (i.e. the
683 value is the consequence of a test). The value is either 0 or 1. The
684 actual CPU flags used is indicated in @code{SValue.c.i}.
686 @item VT_JMP
687 @itemx VT_JMPI
688 indicates that the value is the consequence of a jmp. For VT_JMP, it is
689 1 if the jump is taken, 0 otherwise. For VT_JMPI it is inverted.
691 These values are used to compile the @code{||} and @code{&&} logical
692 operators.
694 @item VT_LVAL
695 is a flag indicating that the value is actually an lvalue (left value of
696 an assignment). It means that the value stored is actually a pointer to
697 the wanted value. 
699 Understanding the use @code{VT_LVAL} is very important if you want to
700 understand how TCC works.
702 @item VT_LVAL_BYTE
703 @itemx VT_LVAL_SHORT
704 @itemx VT_LVAL_UNSIGNED
705 if the lvalue has an integer type, then these flags give its real
706 type. The type alone is not suffisant in case of cast optimisations.
708 @item VT_LLOCAL
709 is a saved lvalue on the stack. @code{VT_LLOCAL} should be suppressed
710 ASAP because its semantics are rather complicated.
712 @item VT_MUSTCAST
713 indicates that a cast to the value type must be performed if the value
714 is used (lazy casting).
716 @item VT_FORWARD
717 indicates that the value is a forward reference to a variable or a function.
719 @item VT_MUSTBOUND
720 @itemx VT_BOUNDED
721 are only used for optional bound checking.
723 @end table
725 @subsection Manipulating the value stack
727 @code{vsetc()} and @code{vset()} pushes a new value on the value
728 stack. If the previous @code{vtop} was stored in a very unsafe place(for
729 example in the CPU flags), then some code is generated to put the
730 previous @code{vtop} in a safe storage.
732 @code{vpop()} pops @code{vtop}. In some cases, it also generates cleanup
733 code (for example if stacked floating point registers are used as on
734 x86).
736 The @code{gv(rc)} function generates code to evaluate @code{vtop} (the
737 top value of the stack) into registers. @var{rc} selects in which
738 register class the value should be put. @code{gv()} is the @emph{most
739 important function} of the code generator.
741 @code{gv2()} is the same as @code{gv()} but for the top two stack
742 entries.
744 @subsection CPU dependent code generation
746 See the @file{i386-gen.c} file to have an example.
748 @table @code
750 @item load()
751 must generate the code needed to load a stack value into a register.
753 @item store()
754 must generate the code needed to store a register into a stack value
755 lvalue.
757 @item gfunc_start()
758 @itemx gfunc_param()
759 @itemx gfunc_call()
760 should generate a function call
762 @item gfunc_prolog()
763 @itemx gfunc_epilog()
764 should generate a function prolog/epilog.
766 @item gen_opi(op)
767 must generate the binary integer operation @var{op} on the two top
768 entries of the stack which are guaranted to contain integer types.
770 The result value should be put on the stack.
772 @item gen_opf(op)
773 same as @code{gen_opi()} for floating point operations. The two top
774 entries of the stack are guaranted to contain floating point values of
775 same types.
777 @item gen_cvt_itof()
778 integer to floating point conversion.
780 @item gen_cvt_ftoi()
781 floating point to integer conversion.
783 @item gen_cvt_ftof()
784 floating point to floating point of different size conversion.
786 @item gen_bounded_ptr_add()
787 @item gen_bounded_ptr_deref()
788 are only used for bound checking.
790 @end table
792 @section Optimizations done
794 Constant propagation is done for all operations. Multiplications and
795 divisions are optimized to shifts when appropriate. Comparison
796 operators are optimized by maintaining a special cache for the
797 processor flags. &&, || and ! are optimized by maintaining a special
798 'jump target' value. No other jump optimization is currently performed
799 because it would require to store the code in a more abstract fashion.