update options
[tinycc.git] / tcc-doc.texi
blob3a9a10e673b35bea15e971f31238641d30fa569f
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] [-bench] [-Idir] [-Dsym[=val]] [-Usym]
40            [-g] [-b] [-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 -bench
103 Output compilation statistics
104 @end table
106 Preprocessor options:
108 @table @samp
109 @item -Idir
110 Specify an additionnal include path. The default ones are:
111 @file{/usr/include}, @code{prefix}@file{/lib/tcc/include} (@code{prefix}
112 is usually @file{/usr} or @file{/usr/local}).
114 @item -Dsym[=val]
115 Define preprocessor symbol 'sym' to
116 val. If val is not present, its value is '1'. Function-like macros can
117 also be defined: @code{'-DF(a)=a+1'}
119 @item -Usym
120 Undefine preprocessor symbol 'sym'.
121 @end table
123 C compiler options:
125 @table @samp
126 @item -g
127 Generate run time debug information so that you get clear run time
128 error messages: @code{ test.c:68: in function 'test5()': dereferencing
129 invalid pointer} instead of the laconic @code{Segmentation
130 fault}.
132 @item -b
133 Generate additionnal support code to check
134 memory allocations and array/pointer bounds. '-g' is implied. Note
135 that the generated code is slower and bigger in this case.
136 @end table
138 Linker options:
140 @table @samp
141 @item -lxxx
142 Dynamically link your program with library
143 libxxx.so. Standard library paths are checked, including those
144 specified with LD_LIBRARY_PATH.
146 @item -shared
147 Generate a shared library instead of an executable  (@samp{-o} option must also be given).
149 @item -static
150 Generate a statically linked executable (default is a shared linked
151 executable) (@samp{-o} option must also be given).
153 @end table
155 @chapter C language support
157 @section ANSI C
159 TCC implements all the ANSI C standard, including structure bit fields
160 and floating point numbers (@code{long double}, @code{double}, and
161 @code{float} fully supported). The following limitations are known:
163 @itemize
164  @item The preprocessor tokens are the same as C. It means that in some
165   rare cases, preprocessed numbers are not handled exactly as in ANSI
166   C. This approach has the advantage of being simpler and FAST!
167 @end itemize
169 @section ISOC99 extensions
171 TCC implements many features of the new C standard: ISO C99. Currently
172 missing items are: complex and imaginary numbers and variable length
173 arrays.
175 Currently implemented ISOC99 features:
177 @itemize
179 @item 64 bit @code{'long long'} types are fully supported.
181 @item The boolean type @code{'_Bool'} is supported.
183 @item @code{'__func__'} is a string variable containing the current
184 function name.
186 @item Variadic macros: @code{__VA_ARGS__} can be used for
187    function-like macros:
188 @example
189     #define dprintf(level, __VA_ARGS__) printf(__VA_ARGS__)
190 @end example
191 @code{dprintf} can then be used with a variable number of parameters.
193 @item Declarations can appear anywhere in a block (as in C++).
195 @item Array and struct/union elements can be initialized in any order by
196   using designators:
197 @example
198     struct { int x, y; } st[10] = { [0].x = 1, [0].y = 2 };
200     int tab[10] = { 1, 2, [5] = 5, [9] = 9};
201 @end example
202     
203 @item Compound initializers are supported:
204 @example
205     int *p = (int []){ 1, 2, 3 };
206 @end example
207 to initialize a pointer pointing to an initialized array. The same
208 works for structures and strings.
210 @item Hexadecimal floating point constants are supported:
211 @example
212           double d = 0x1234p10;
213 @end example
214 is the same as writing 
215 @example
216           double d = 4771840.0;
217 @end example
219 @item @code{'inline'} keyword is ignored.
221 @item @code{'restrict'} keyword is ignored.
222 @end itemize
224 @section GNU C extensions
226 TCC implements some GNU C extensions:
228 @itemize
230 @item array designators can be used without '=': 
231 @example
232     int a[10] = { [0] 1, [5] 2, 3, 4 };
233 @end example
235 @item Structure field designators can be a label: 
236 @example
237     struct { int x, y; } st = { x: 1, y: 1};
238 @end example
239 instead of
240 @example
241     struct { int x, y; } st = { .x = 1, .y = 1};
242 @end example
244 @item @code{'\e'} is ASCII character 27.
246 @item case ranges : ranges can be used in @code{case}s:
247 @example
248     switch(a) {
249     case 1 ... 9:
250           printf("range 1 to 9\n");
251           break;
252     default:
253           printf("unexpected\n");
254           break;
255     }
256 @end example
258 @item The keyword @code{__attribute__} is handled to specify variable or
259 function attributes. The following attributes are supported:
260   @itemize
261   @item @code{aligned(n)}: align data to n bytes (must be a power of two).
263   @item @code{section(name)}: generate function or data in assembly
264   section name (name is a string containing the section name) instead
265   of the default section.
267   @item @code{unused}: specify that the variable or the function is unused.
269   @item @code{cdecl}: use standard C calling convention.
271   @item @code{stdcall}: use Pascal-like calling convention.
273   @end itemize
275 Here are some examples:
276 @example
277     int a __attribute__ ((aligned(8), section(".mysection")));
278 @end example
280 align variable @code{'a'} to 8 bytes and put it in section @code{.mysection}.
282 @example
283     int my_add(int a, int b) __attribute__ ((section(".mycodesection"))) 
284     {
285         return a + b;
286     }
287 @end example
289 generate function @code{'my_add'} in section @code{.mycodesection}.
291 @item GNU style variadic macros:
292 @example
293     #define dprintf(fmt, args...) printf(fmt, ## args)
295     dprintf("no arg\n");
296     dprintf("one arg %d\n", 1);
297 @end example
299 @end itemize
301 @section TinyCC extensions
303 @itemize
305 @item @code{__TINYC__} is a predefined macro to @code{'1'} to
306 indicate that you use TCC.
308 @item @code{'#!'} at the start of a line is ignored to allow scripting.
310 @item Binary digits can be entered (@code{'0b101'} instead of
311 @code{'5'}).
313 @item @code{__BOUNDS_CHECKING_ON} is defined if bound checking is activated.
315 @end itemize
317 @node bounds
318 @chapter TinyCC Memory and Bound checks
320 This feature is activated with the @code{'-b'} (@xref{invoke}).
322 Note that pointer size is @emph{unchanged} and that code generated
323 with bound checks is @emph{fully compatible} with unchecked
324 code. When a pointer comes from unchecked code, it is assumed to be
325 valid. Even very obscure C code with casts should work correctly.
327 To have more information about the ideas behind this method, check at 
328 @url{http://www.doc.ic.ac.uk/~phjk/BoundsChecking.html}.
330 Here are some examples of catched errors:
332 @table @asis
334 @item Invalid range with standard string function:
335 @example
337     char tab[10];
338     memset(tab, 0, 11);
340 @end example
342 @item Bound error in global or local arrays:
343 @example
345     int tab[10];
346     for(i=0;i<11;i++) {
347         sum += tab[i];
348     }
350 @end example
352 @item Bound error in allocated data:
353 @example
355     int *tab;
356     tab = malloc(20 * sizeof(int));
357     for(i=0;i<21;i++) {
358         sum += tab4[i];
359     }
360     free(tab);
362 @end example
364 @item Access to a freed region:
365 @example
367     int *tab;
368     tab = malloc(20 * sizeof(int));
369     free(tab);
370     for(i=0;i<20;i++) {
371         sum += tab4[i];
372     }
374 @end example
376 @item Freeing an already freed region:
377 @example
379     int *tab;
380     tab = malloc(20 * sizeof(int));
381     free(tab);
382     free(tab);
384 @end example
386 @end table
388 @node libtcc
389 @chapter The @code{libtcc} library
391 The @code{libtcc} library enables you to use TCC as a backend for
392 dynamic code generation. 
394 Read the @file{libtcc.h} to have an overview of the API. Read
395 @file{libtcc_test.c} to have a very simple example.
397 The idea consists in giving a C string containing the program you want
398 to compile directly to @code{libtcc}. Then the @code{main()} function of
399 the compiled string can be launched.
401 @chapter Developper's guide
403 This chapter gives some hints to understand how TCC works. You can skip
404 it if you do not intend to modify the TCC code.
406 @section File reading
408 The @code{BufferedFile} structure contains the context needed to read a
409 file, including the current line number. @code{tcc_open()} opens a new
410 file and @code{tcc_close()} closes it. @code{inp()} returns the next
411 character.
413 @section Lexer
415 @code{next()} reads the next token in the current
416 file. @code{next_nomacro()} reads the next token without macro
417 expansion.
419 @code{tok} contains the current token (see @code{TOK_xxx})
420 constants. Identifiers and keywords are also keywords. @code{tokc}
421 contains additionnal infos about the token (for example a constant value
422 if number or string token).
424 @section Parser
426 The parser is hardcoded (yacc is not necessary). It does only one pass,
427 except:
429 @itemize
431 @item For initialized arrays with unknown size, a first pass 
432 is done to count the number of elements.
434 @item For architectures where arguments are evaluated in 
435 reverse order, a first pass is done to reverse the argument order.
437 @end itemize
439 @section Types
441 The types are stored in a single 'int' variable. It was choosen in the
442 first stages of development when tcc was much simpler. Now, it may not
443 be the best solution.
445 @example
446 #define VT_INT        0  /* integer type */
447 #define VT_BYTE       1  /* signed byte type */
448 #define VT_SHORT      2  /* short type */
449 #define VT_VOID       3  /* void type */
450 #define VT_PTR        4  /* pointer */
451 #define VT_ENUM       5  /* enum definition */
452 #define VT_FUNC       6  /* function type */
453 #define VT_STRUCT     7  /* struct/union definition */
454 #define VT_FLOAT      8  /* IEEE float */
455 #define VT_DOUBLE     9  /* IEEE double */
456 #define VT_LDOUBLE   10  /* IEEE long double */
457 #define VT_BOOL      11  /* ISOC99 boolean type */
458 #define VT_LLONG     12  /* 64 bit integer */
459 #define VT_LONG      13  /* long integer (NEVER USED as type, only
460                             during parsing) */
461 #define VT_BTYPE      0x000f /* mask for basic type */
462 #define VT_UNSIGNED   0x0010  /* unsigned type */
463 #define VT_ARRAY      0x0020  /* array type (also has VT_PTR) */
464 #define VT_BITFIELD   0x0040  /* bitfield modifier */
466 #define VT_STRUCT_SHIFT 16   /* structure/enum name shift (16 bits left) */
467 @end example
469 When a reference to another type is needed (for pointers, functions and
470 structures), the @code{32 - VT_STRUCT_SHIFT} high order bits are used to
471 store an identifier reference.
473 The @code{VT_UNSIGNED} flag can be set for chars, shorts, ints and long
474 longs.
476 Arrays are considered as pointers @code{VT_PTR} with the flag
477 @code{VT_ARRAY} set.
479 The @code{VT_BITFIELD} flag can be set for chars, shorts, ints and long
480 longs. If it is set, then the bitfield position is stored from bits
481 VT_STRUCT_SHIFT to VT_STRUCT_SHIFT + 5 and the bit field size is stored
482 from bits VT_STRUCT_SHIFT + 6 to VT_STRUCT_SHIFT + 11.
484 @code{VT_LONG} is never used except during parsing.
486 During parsing, the storage of an object is also stored in the type
487 integer:
489 @example
490 #define VT_EXTERN  0x00000080  /* extern definition */
491 #define VT_STATIC  0x00000100  /* static variable */
492 #define VT_TYPEDEF 0x00000200  /* typedef definition */
493 @end example
495 @section Symbols
497 All symbols are stored in hashed symbol stacks. Each symbol stack
498 contains @code{Sym} structures.
500 @code{Sym.v} contains the symbol name (remember
501 an idenfier is also a token, so a string is never necessary to store
502 it). @code{Sym.t} gives the type of the symbol. @code{Sym.r} is usually
503 the register in which the corresponding variable is stored. @code{Sym.c} is
504 usually a constant associated to the symbol.
506 Four main symbol stacks are defined:
508 @table @code
510 @item define_stack
511 for the macros (@code{#define}s).
513 @item global_stack
514 for the global variables, functions and types.
516 @item extern_stack
517 for the external symbols shared between files.
519 @item local_stack
520 for the local variables, functions and types.
522 @item label_stack
523 for the local labels (for @code{goto}).
525 @end table
527 @code{sym_push()} is used to add a new symbol in the local symbol
528 stack. If no local symbol stack is active, it is added in the global
529 symbol stack.
531 @code{sym_pop(st,b)} pops symbols from the symbol stack @var{st} until
532 the symbol @var{b} is on the top of stack. If @var{b} is NULL, the stack
533 is emptied.
535 @code{sym_find(v)} return the symbol associated to the identifier
536 @var{v}. The local stack is searched first from top to bottom, then the
537 global stack.
539 @section Sections
541 The generated code and datas are written in sections. The structure
542 @code{Section} contains all the necessary information for a given
543 section. @code{new_section()} creates a new section. ELF file semantics
544 is assumed for each section.
546 The following sections are predefined:
548 @table @code
550 @item text_section
551 is the section containing the generated code. @var{ind} contains the
552 current position in the code section.
554 @item data_section
555 contains initialized data
557 @item bss_section
558 contains uninitialized data
560 @item bounds_section
561 @itemx lbounds_section
562 are used when bound checking is activated
564 @item stab_section
565 @itemx stabstr_section
566 are used when debugging is actived to store debug information
568 @item symtab_section
569 @itemx strtab_section
570 contain the exported symbols (currently only used for debugging).
572 @end table
574 @section Code generation
576 @subsection Introduction
578 The TCC code generator directly generates linked binary code in one
579 pass. It is rather unusual these days (see gcc for example which
580 generates text assembly), but it allows to be very fast and surprisingly
581 not so complicated.
583 The TCC code generator is register based. Optimization is only done at
584 the expression level. No intermediate representation of expression is
585 kept except the current values stored in the @emph{value stack}.
587 On x86, three temporary registers are used. When more registers are
588 needed, one register is flushed in a new local variable.
590 @subsection The value stack
592 When an expression is parsed, its value is pushed on the value stack
593 (@var{vstack}). The top of the value stack is @var{vtop}. Each value
594 stack entry is the structure @code{SValue}.
596 @code{SValue.t} is the type. @code{SValue.r} indicates how the value is
597 currently stored in the generated code. It is usually a CPU register
598 index (@code{REG_xxx} constants), but additionnal values and flags are
599 defined:
601 @example
602 #define VT_CONST     0x00f0  /* constant in vc 
603                               (must be first non register value) */
604 #define VT_LLOCAL    0x00f1  /* lvalue, offset on stack */
605 #define VT_LOCAL     0x00f2  /* offset on stack */
606 #define VT_CMP       0x00f3  /* the value is stored in processor flags (in vc) */
607 #define VT_JMP       0x00f4  /* value is the consequence of jmp true (even) */
608 #define VT_JMPI      0x00f5  /* value is the consequence of jmp false (odd) */
609 #define VT_LVAL      0x0100  /* var is an lvalue */
610 #define VT_FORWARD   0x0200  /* value is forward reference */
611 #define VT_MUSTCAST  0x0400  /* value must be casted to be correct (used for
612                                 char/short stored in integer registers) */
613 #define VT_MUSTBOUND 0x0800  /* bound checking must be done before
614                                 dereferencing value */
615 #define VT_BOUNDED   0x8000  /* value is bounded. The address of the
616                                 bounding function call point is in vc */
617 #define VT_LVAL_BYTE     0x1000  /* lvalue is a byte */
618 #define VT_LVAL_SHORT    0x2000  /* lvalue is a short */
619 #define VT_LVAL_UNSIGNED 0x4000  /* lvalue is unsigned */
620 #define VT_LVAL_TYPE     (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
621 @end example
623 @table @code
625 @item VT_CONST
626 indicates that the value is a constant. It is stored in the union
627 @code{SValue.c}, depending on its type.
629 @item VT_LOCAL
630 indicates a local variable pointer at offset @code{SValue.c.i} in the
631 stack.
633 @item VT_CMP
634 indicates that the value is actually stored in the CPU flags (i.e. the
635 value is the consequence of a test). The value is either 0 or 1. The
636 actual CPU flags used is indicated in @code{SValue.c.i}.
638 @item VT_JMP
639 @itemx VT_JMPI
640 indicates that the value is the consequence of a jmp. For VT_JMP, it is
641 1 if the jump is taken, 0 otherwise. For VT_JMPI it is inverted.
643 These values are used to compile the @code{||} and @code{&&} logical
644 operators.
646 @item VT_LVAL
647 is a flag indicating that the value is actually an lvalue (left value of
648 an assignment). It means that the value stored is actually a pointer to
649 the wanted value. 
651 Understanding the use @code{VT_LVAL} is very important if you want to
652 understand how TCC works.
654 @item VT_LVAL_BYTE
655 @itemx VT_LVAL_SHORT
656 @itemx VT_LVAL_UNSIGNED
657 if the lvalue has an integer type, then these flags give its real
658 type. The type alone is not suffisant in case of cast optimisations.
660 @item VT_LLOCAL
661 is a saved lvalue on the stack. @code{VT_LLOCAL} should be suppressed
662 ASAP because its semantics are rather complicated.
664 @item VT_MUSTCAST
665 indicates that a cast to the value type must be performed if the value
666 is used (lazy casting).
668 @item VT_FORWARD
669 indicates that the value is a forward reference to a variable or a function.
671 @item VT_MUSTBOUND
672 @itemx VT_BOUNDED
673 are only used for optional bound checking.
675 @end table
677 @subsection Manipulating the value stack
679 @code{vsetc()} and @code{vset()} pushes a new value on the value
680 stack. If the previous @code{vtop} was stored in a very unsafe place(for
681 example in the CPU flags), then some code is generated to put the
682 previous @code{vtop} in a safe storage.
684 @code{vpop()} pops @code{vtop}. In some cases, it also generates cleanup
685 code (for example if stacked floating point registers are used as on
686 x86).
688 The @code{gv(rc)} function generates code to evaluate @code{vtop} (the
689 top value of the stack) into registers. @var{rc} selects in which
690 register class the value should be put. @code{gv()} is the @emph{most
691 important function} of the code generator.
693 @code{gv2()} is the same as @code{gv()} but for the top two stack
694 entries.
696 @subsection CPU dependent code generation
698 See the @file{i386-gen.c} file to have an example.
700 @table @code
702 @item load()
703 must generate the code needed to load a stack value into a register.
705 @item store()
706 must generate the code needed to store a register into a stack value
707 lvalue.
709 @item gfunc_start()
710 @itemx gfunc_param()
711 @itemx gfunc_call()
712 should generate a function call
714 @item gfunc_prolog()
715 @itemx gfunc_epilog()
716 should generate a function prolog/epilog.
718 @item gen_opi(op)
719 must generate the binary integer operation @var{op} on the two top
720 entries of the stack which are guaranted to contain integer types.
722 The result value should be put on the stack.
724 @item gen_opf(op)
725 same as @code{gen_opi()} for floating point operations. The two top
726 entries of the stack are guaranted to contain floating point values of
727 same types.
729 @item gen_cvt_itof()
730 integer to floating point conversion.
732 @item gen_cvt_ftoi()
733 floating point to integer conversion.
735 @item gen_cvt_ftof()
736 floating point to floating point of different size conversion.
738 @item gen_bounded_ptr_add()
739 @item gen_bounded_ptr_deref()
740 are only used for bound checking.
742 @end table
744 @section Optimizations done
746 Constant propagation is done for all operations. Multiplications and
747 divisions are optimized to shifts when appropriate. Comparison
748 operators are optimized by maintaining a special cache for the
749 processor flags. &&, || and ! are optimized by maintaining a special
750 'jump target' value. No other jump optimization is currently performed
751 because it would require to store the code in a more abstract fashion.