2015-01-15 Richard Sandiford <richard.sandiford@arm.com>
[official-gcc.git] / gcc / jit / docs / _build / texinfo / libgccjit.texi
blobe45b0d526997a4814ecaced5090126dffc30ecb2
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename libgccjit.info
4 @documentencoding UTF-8
5 @ifinfo
6 @*Generated by Sphinx 1.1.3.@*
7 @end ifinfo
8 @settitle libgccjit Documentation
9 @defindex ge
10 @paragraphindent 2
11 @exampleindent 4
12 @afourlatex
13 @dircategory Miscellaneous
14 @direntry
15 * libgccjit: (libgccjit.info). One line description of project.
16 @end direntry
18 @c %**end of header
20 @copying
21 @quotation
22 libgccjit 5.0.0 (experimental 20150113), January 13, 2015
24 David Malcolm
26 Copyright @copyright{} 2014-2015 Free Software Foundation, Inc.
27 @end quotation
29 @end copying
31 @titlepage
32 @title libgccjit Documentation
33 @insertcopying
34 @end titlepage
35 @contents
37 @c %** start of user preamble
39 @c %** end of user preamble
41 @ifnottex
42 @node Top
43 @top libgccjit Documentation
44 @insertcopying
45 @end ifnottex
47 @c %**start of body
48 @anchor{index doc}@anchor{0}
49 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
50 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
51 @c 
52 @c This is free software: you can redistribute it and/or modify it
53 @c under the terms of the GNU General Public License as published by
54 @c the Free Software Foundation, either version 3 of the License, or
55 @c (at your option) any later version.
56 @c 
57 @c This program is distributed in the hope that it will be useful, but
58 @c WITHOUT ANY WARRANTY; without even the implied warranty of
59 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
60 @c General Public License for more details.
61 @c 
62 @c You should have received a copy of the GNU General Public License
63 @c along with this program.  If not, see
64 @c <http://www.gnu.org/licenses/>.
66 This document describes libgccjit@footnote{http://gcc.gnu.org/wiki/JIT}, an API
67 for embedding GCC inside programs and libraries.
69 Note that libgccjit is currently of "Alpha" quality;
70 the APIs are not yet set in stone, and they shouldn't be used in
71 production yet.
73 There are actually two APIs for the library:
76 @itemize *
78 @item 
79 a pure C API: @code{libgccjit.h}
81 @item 
82 a C++ wrapper API: @code{libgccjit++.h}.  This is a collection of "thin"
83 wrapper classes around the C API, to save typing.
84 @end itemize
86 Contents:
88 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
89 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
90 @c 
91 @c This is free software: you can redistribute it and/or modify it
92 @c under the terms of the GNU General Public License as published by
93 @c the Free Software Foundation, either version 3 of the License, or
94 @c (at your option) any later version.
95 @c 
96 @c This program is distributed in the hope that it will be useful, but
97 @c WITHOUT ANY WARRANTY; without even the implied warranty of
98 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
99 @c General Public License for more details.
100 @c 
101 @c You should have received a copy of the GNU General Public License
102 @c along with this program.  If not, see
103 @c <http://www.gnu.org/licenses/>.
105 @menu
106 * Tutorial:: 
107 * Topic Reference:: 
108 * C++ bindings for libgccjit:: 
109 * Internals:: 
110 * Indices and tables:: 
111 * Index:: 
113 @detailmenu
114  --- The Detailed Node Listing ---
116 Tutorial
118 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world". 
119 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function. 
120 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables. 
121 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter. 
123 Tutorial part 2: Creating a trivial machine code function
125 * Error-handling:: 
126 * Options:: 
127 * Full example:: 
129 Tutorial part 3: Loops and variables
131 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues. 
132 * Control flow:: 
133 * Visualizing the control flow graph:: 
134 * Full example: Full example<2>. 
136 Tutorial part 4: Adding JIT-compilation to a toy interpreter
138 * Our toy interpreter:: 
139 * Compiling to machine code:: 
140 * Setting things up:: 
141 * Populating the function:: 
142 * Verifying the control flow graph:: 
143 * Compiling the context:: 
144 * Single-stepping through the generated code:: 
145 * Examining the generated code:: 
146 * Putting it all together:: 
147 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?. 
149 Behind the curtain: How does our code get optimized?
151 * Optimizing away stack manipulation:: 
152 * Elimination of tail recursion:: 
154 Topic Reference
156 * Compilation contexts:: 
157 * Objects:: 
158 * Types:: 
159 * Expressions:: 
160 * Creating and using functions:: 
161 * Source Locations:: 
162 * Compilation results:: 
164 Compilation contexts
166 * Lifetime-management:: 
167 * Thread-safety:: 
168 * Error-handling: Error-handling<2>. 
169 * Debugging:: 
170 * Options: Options<2>. 
172 Options
174 * String Options:: 
175 * Boolean options:: 
176 * Integer options:: 
178 Types
180 * Standard types:: 
181 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile. 
182 * Structures and unions:: 
184 Expressions
186 * Rvalues:: 
187 * Lvalues:: 
188 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions. 
190 Rvalues
192 * Simple expressions:: 
193 * Unary Operations:: 
194 * Binary Operations:: 
195 * Comparisons:: 
196 * Function calls:: 
197 * Type-coercion:: 
199 Lvalues
201 * Global variables:: 
203 Creating and using functions
205 * Params:: 
206 * Functions:: 
207 * Blocks:: 
208 * Statements:: 
210 Source Locations
212 * Faking it:: 
214 C++ bindings for libgccjit
216 * Tutorial: Tutorial<2>. 
217 * Topic Reference: Topic Reference<2>. 
219 Tutorial
221 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world"<2>. 
222 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function<2>. 
223 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables<2>. 
224 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>. 
226 Tutorial part 2: Creating a trivial machine code function
228 * Options: Options<3>. 
229 * Full example: Full example<3>. 
231 Tutorial part 3: Loops and variables
233 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues<2>. 
234 * Control flow: Control flow<2>. 
235 * Visualizing the control flow graph: Visualizing the control flow graph<2>. 
236 * Full example: Full example<4>. 
238 Tutorial part 4: Adding JIT-compilation to a toy interpreter
240 * Our toy interpreter: Our toy interpreter<2>. 
241 * Compiling to machine code: Compiling to machine code<2>. 
242 * Setting things up: Setting things up<2>. 
243 * Populating the function: Populating the function<2>. 
244 * Verifying the control flow graph: Verifying the control flow graph<2>. 
245 * Compiling the context: Compiling the context<2>. 
246 * Single-stepping through the generated code: Single-stepping through the generated code<2>. 
247 * Examining the generated code: Examining the generated code<2>. 
248 * Putting it all together: Putting it all together<2>. 
249 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?<2>. 
251 Behind the curtain: How does our code get optimized?
253 * Optimizing away stack manipulation: Optimizing away stack manipulation<2>. 
254 * Elimination of tail recursion: Elimination of tail recursion<2>. 
256 Topic Reference
258 * Compilation contexts: Compilation contexts<2>. 
259 * Objects: Objects<2>. 
260 * Types: Types<2>. 
261 * Expressions: Expressions<2>. 
262 * Creating and using functions: Creating and using functions<2>. 
263 * Source Locations: Source Locations<2>. 
264 * Compilation results: Compilation results<2>. 
266 Compilation contexts
268 * Lifetime-management: Lifetime-management<2>. 
269 * Thread-safety: Thread-safety<2>. 
270 * Error-handling: Error-handling<3>. 
271 * Debugging: Debugging<2>. 
272 * Options: Options<4>. 
274 Options
276 * String Options: String Options<2>. 
277 * Boolean options: Boolean options<2>. 
278 * Integer options: Integer options<2>. 
280 Types
282 * Standard types: Standard types<2>. 
283 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile<2>. 
284 * Structures and unions: Structures and unions<2>. 
286 Expressions
288 * Rvalues: Rvalues<2>. 
289 * Lvalues: Lvalues<2>. 
290 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions<2>. 
292 Rvalues
294 * Simple expressions: Simple expressions<2>. 
295 * Unary Operations: Unary Operations<2>. 
296 * Binary Operations: Binary Operations<2>. 
297 * Comparisons: Comparisons<2>. 
298 * Function calls: Function calls<2>. 
299 * Type-coercion: Type-coercion<2>. 
301 Lvalues
303 * Global variables: Global variables<2>. 
305 Creating and using functions
307 * Params: Params<2>. 
308 * Functions: Functions<2>. 
309 * Blocks: Blocks<2>. 
310 * Statements: Statements<2>. 
312 Source Locations
314 * Faking it: Faking it<2>. 
316 Internals
318 * Working on the JIT library:: 
319 * Running the test suite:: 
320 * Environment variables:: 
321 * Overview of code structure:: 
322 * Design notes:: 
324 Running the test suite
326 * Running under valgrind:: 
328 @end detailmenu
329 @end menu
332 @node Tutorial,Topic Reference,Top,Top
333 @anchor{intro/index libgccjit}@anchor{1}@anchor{intro/index doc}@anchor{2}@anchor{intro/index tutorial}@anchor{3}
334 @chapter Tutorial
337 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
338 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
339 @c 
340 @c This is free software: you can redistribute it and/or modify it
341 @c under the terms of the GNU General Public License as published by
342 @c the Free Software Foundation, either version 3 of the License, or
343 @c (at your option) any later version.
344 @c 
345 @c This program is distributed in the hope that it will be useful, but
346 @c WITHOUT ANY WARRANTY; without even the implied warranty of
347 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
348 @c General Public License for more details.
349 @c 
350 @c You should have received a copy of the GNU General Public License
351 @c along with this program.  If not, see
352 @c <http://www.gnu.org/licenses/>.
354 @menu
355 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world". 
356 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function. 
357 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables. 
358 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter. 
360 @end menu
362 @node Tutorial part 1 "Hello world",Tutorial part 2 Creating a trivial machine code function,,Tutorial
363 @anchor{intro/tutorial01 doc}@anchor{4}@anchor{intro/tutorial01 tutorial-part-1-hello-world}@anchor{5}
364 @section Tutorial part 1: "Hello world"
367 Before we look at the details of the API, let's look at building and
368 running programs that use the library.
370 Here's a toy "hello world" program that uses the library to synthesize
371 a call to @cite{printf} and uses it to write a message to stdout.
373 Don't worry about the content of the program for now; we'll cover
374 the details in later parts of this tutorial.
376 @quotation
378 @example
379 /* Smoketest example for libgccjit.so
380    Copyright (C) 2014-2015 Free Software Foundation, Inc.
382 This file is part of GCC.
384 GCC is free software; you can redistribute it and/or modify it
385 under the terms of the GNU General Public License as published by
386 the Free Software Foundation; either version 3, or (at your option)
387 any later version.
389 GCC is distributed in the hope that it will be useful, but
390 WITHOUT ANY WARRANTY; without even the implied warranty of
391 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
392 General Public License for more details.
394 You should have received a copy of the GNU General Public License
395 along with GCC; see the file COPYING3.  If not see
396 <http://www.gnu.org/licenses/>.  */
398 #include <libgccjit.h>
400 #include <stdlib.h>
401 #include <stdio.h>
403 static void
404 create_code (gcc_jit_context *ctxt)
406   /* Let's try to inject the equivalent of:
407      void
408      greet (const char *name)
409      @{
410         printf ("hello %s\n", name);
411      @}
412   */
413   gcc_jit_type *void_type =
414     gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_VOID);
415   gcc_jit_type *const_char_ptr_type =
416     gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_CONST_CHAR_PTR);
417   gcc_jit_param *param_name =
418     gcc_jit_context_new_param (ctxt, NULL, const_char_ptr_type, "name");
419   gcc_jit_function *func =
420     gcc_jit_context_new_function (ctxt, NULL,
421                                   GCC_JIT_FUNCTION_EXPORTED,
422                                   void_type,
423                                   "greet",
424                                   1, &param_name,
425                                   0);
427   gcc_jit_param *param_format =
428     gcc_jit_context_new_param (ctxt, NULL, const_char_ptr_type, "format");
429   gcc_jit_function *printf_func =
430     gcc_jit_context_new_function (ctxt, NULL,
431                                   GCC_JIT_FUNCTION_IMPORTED,
432                                   gcc_jit_context_get_type (
433                                      ctxt, GCC_JIT_TYPE_INT),
434                                   "printf",
435                                   1, &param_format,
436                                   1);
437   gcc_jit_rvalue *args[2];
438   args[0] = gcc_jit_context_new_string_literal (ctxt, "hello %s\n");
439   args[1] = gcc_jit_param_as_rvalue (param_name);
441   gcc_jit_block *block = gcc_jit_function_new_block (func, NULL);
443   gcc_jit_block_add_eval (
444     block, NULL,
445     gcc_jit_context_new_call (ctxt,
446                               NULL,
447                               printf_func,
448                               2, args));
449   gcc_jit_block_end_with_void_return (block, NULL);
453 main (int argc, char **argv)
455   gcc_jit_context *ctxt;
456   gcc_jit_result *result;
458   /* Get a "context" object for working with the library.  */
459   ctxt = gcc_jit_context_acquire ();
460   if (!ctxt)
461     @{
462       fprintf (stderr, "NULL ctxt");
463       exit (1);
464     @}
466   /* Set some options on the context.
467      Let's see the code being generated, in assembler form.  */
468   gcc_jit_context_set_bool_option (
469     ctxt,
470     GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
471     0);
473   /* Populate the context.  */
474   create_code (ctxt);
476   /* Compile the code.  */
477   result = gcc_jit_context_compile (ctxt);
478   if (!result)
479     @{
480       fprintf (stderr, "NULL result");
481       exit (1);
482     @}
484   /* Extract the generated code from "result".  */
485   typedef void (*fn_type) (const char *);
486   fn_type greet =
487     (fn_type)gcc_jit_result_get_code (result, "greet");
488   if (!greet)
489     @{
490       fprintf (stderr, "NULL greet");
491       exit (1);
492     @}
494   /* Now call the generated function: */
495   greet ("world");
496   fflush (stdout);
498   gcc_jit_context_release (ctxt);
499   gcc_jit_result_release (result);
500   return 0;
503 @end example
505 @noindent
506 @end quotation
508 Copy the above to @cite{tut01-hello-world.c}.
510 Assuming you have the jit library installed, build the test program
511 using:
513 @example
514 $ gcc \
515     tut01-hello-world.c \
516     -o tut01-hello-world \
517     -lgccjit
518 @end example
520 @noindent
522 You should then be able to run the built program:
524 @example
525 $ ./tut01-hello-world
526 hello world
527 @end example
529 @noindent
531 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
532 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
533 @c 
534 @c This is free software: you can redistribute it and/or modify it
535 @c under the terms of the GNU General Public License as published by
536 @c the Free Software Foundation, either version 3 of the License, or
537 @c (at your option) any later version.
538 @c 
539 @c This program is distributed in the hope that it will be useful, but
540 @c WITHOUT ANY WARRANTY; without even the implied warranty of
541 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
542 @c General Public License for more details.
543 @c 
544 @c You should have received a copy of the GNU General Public License
545 @c along with this program.  If not, see
546 @c <http://www.gnu.org/licenses/>.
548 @node Tutorial part 2 Creating a trivial machine code function,Tutorial part 3 Loops and variables,Tutorial part 1 "Hello world",Tutorial
549 @anchor{intro/tutorial02 doc}@anchor{6}@anchor{intro/tutorial02 tutorial-part-2-creating-a-trivial-machine-code-function}@anchor{7}
550 @section Tutorial part 2: Creating a trivial machine code function
553 Consider this C function:
555 @example
556 int square (int i)
558   return i * i;
560 @end example
562 @noindent
564 How can we construct this at run-time using libgccjit?
566 First we need to include the relevant header:
568 @example
569 #include <libgccjit.h>
570 @end example
572 @noindent
574 All state associated with compilation is associated with a
575 @pxref{8,,gcc_jit_context *}.
577 Create one using @pxref{9,,gcc_jit_context_acquire()}:
579 @example
580 gcc_jit_context *ctxt;
581 ctxt = gcc_jit_context_acquire ();
582 @end example
584 @noindent
586 The JIT library has a system of types.  It is statically-typed: every
587 expression is of a specific type, fixed at compile-time.  In our example,
588 all of the expressions are of the C @cite{int} type, so let's obtain this from
589 the context, as a @pxref{a,,gcc_jit_type *}, using
590 @pxref{b,,gcc_jit_context_get_type()}:
592 @example
593 gcc_jit_type *int_type =
594   gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
595 @end example
597 @noindent
599 @pxref{a,,gcc_jit_type *} is an example of a "contextual" object: every
600 entity in the API is associated with a @pxref{8,,gcc_jit_context *}.
602 Memory management is easy: all such "contextual" objects are automatically
603 cleaned up for you when the context is released, using
604 @pxref{c,,gcc_jit_context_release()}:
606 @example
607 gcc_jit_context_release (ctxt);
608 @end example
610 @noindent
612 so you don't need to manually track and cleanup all objects, just the
613 contexts.
615 Although the API is C-based, there is a form of class hierarchy, which
616 looks like this:
618 @example
619 +- gcc_jit_object
620     +- gcc_jit_location
621     +- gcc_jit_type
622        +- gcc_jit_struct
623     +- gcc_jit_field
624     +- gcc_jit_function
625     +- gcc_jit_block
626     +- gcc_jit_rvalue
627         +- gcc_jit_lvalue
628            +- gcc_jit_param
629 @end example
631 @noindent
633 There are casting methods for upcasting from subclasses to parent classes.
634 For example, @pxref{d,,gcc_jit_type_as_object()}:
636 @example
637 gcc_jit_object *obj = gcc_jit_type_as_object (int_type);
638 @end example
640 @noindent
642 One thing you can do with a @pxref{e,,gcc_jit_object *} is
643 to ask it for a human-readable description, using
644 @pxref{f,,gcc_jit_object_get_debug_string()}:
646 @example
647 printf ("obj: %s\n", gcc_jit_object_get_debug_string (obj));
648 @end example
650 @noindent
652 giving this text on stdout:
654 @example
655 obj: int
656 @end example
658 @noindent
660 This is invaluable when debugging.
662 Let's create the function.  To do so, we first need to construct
663 its single parameter, specifying its type and giving it a name,
664 using @pxref{10,,gcc_jit_context_new_param()}:
666 @example
667 gcc_jit_param *param_i =
668   gcc_jit_context_new_param (ctxt, NULL, int_type, "i");
669 @end example
671 @noindent
673 Now we can create the function, using
674 @pxref{11,,gcc_jit_context_new_function()}:
676 @example
677 gcc_jit_function *func =
678   gcc_jit_context_new_function (ctxt, NULL,
679                                 GCC_JIT_FUNCTION_EXPORTED,
680                                 int_type,
681                                 "square",
682                                 1, &param_i,
683                                 0);
684 @end example
686 @noindent
688 To define the code within the function, we must create basic blocks
689 containing statements.
691 Every basic block contains a list of statements, eventually terminated
692 by a statement that either returns, or jumps to another basic block.
694 Our function has no control-flow, so we just need one basic block:
696 @example
697 gcc_jit_block *block = gcc_jit_function_new_block (func, NULL);
698 @end example
700 @noindent
702 Our basic block is relatively simple: it immediately terminates by
703 returning the value of an expression.
705 We can build the expression using @pxref{12,,gcc_jit_context_new_binary_op()}:
707 @example
708 gcc_jit_rvalue *expr =
709   gcc_jit_context_new_binary_op (
710     ctxt, NULL,
711     GCC_JIT_BINARY_OP_MULT, int_type,
712     gcc_jit_param_as_rvalue (param_i),
713     gcc_jit_param_as_rvalue (param_i));
714 @end example
716 @noindent
718 A @pxref{13,,gcc_jit_rvalue *} is another example of a
719 @pxref{e,,gcc_jit_object *} subclass.  We can upcast it using
720 @pxref{14,,gcc_jit_rvalue_as_object()} and as before print it with
721 @pxref{f,,gcc_jit_object_get_debug_string()}.
723 @example
724 printf ("expr: %s\n",
725         gcc_jit_object_get_debug_string (
726           gcc_jit_rvalue_as_object (expr)));
727 @end example
729 @noindent
731 giving this output:
733 @example
734 expr: i * i
735 @end example
737 @noindent
739 Creating the expression in itself doesn't do anything; we have to add
740 this expression to a statement within the block.  In this case, we use it
741 to build a return statement, which terminates the basic block:
743 @example
744 gcc_jit_block_end_with_return (block, NULL, expr);
745 @end example
747 @noindent
749 OK, we've populated the context.  We can now compile it using
750 @pxref{15,,gcc_jit_context_compile()}:
752 @example
753 gcc_jit_result *result;
754 result = gcc_jit_context_compile (ctxt);
755 @end example
757 @noindent
759 and get a @pxref{16,,gcc_jit_result *}.
761 At this point we're done with the context; we can release it:
763 @example
764 gcc_jit_context_release (ctxt);
765 @end example
767 @noindent
769 We can now use @pxref{17,,gcc_jit_result_get_code()} to look up a specific
770 machine code routine within the result, in this case, the function we
771 created above.
773 @example
774 void *fn_ptr = gcc_jit_result_get_code (result, "square");
775 if (!fn_ptr)
776   @{
777     fprintf (stderr, "NULL fn_ptr");
778     goto error;
779   @}
780 @end example
782 @noindent
784 We can now cast the pointer to an appropriate function pointer type, and
785 then call it:
787 @example
788 typedef int (*fn_type) (int);
789 fn_type square = (fn_type)fn_ptr;
790 printf ("result: %d", square (5));
791 @end example
793 @noindent
795 @example
796 result: 25
797 @end example
799 @noindent
801 Once we're done with the code, we can release the result:
803 @example
804 gcc_jit_result_release (result);
805 @end example
807 @noindent
809 We can't call @code{square} anymore once we've released @code{result}.
811 @menu
812 * Error-handling:: 
813 * Options:: 
814 * Full example:: 
816 @end menu
818 @node Error-handling,Options,,Tutorial part 2 Creating a trivial machine code function
819 @anchor{intro/tutorial02 error-handling}@anchor{18}
820 @subsection Error-handling
823 Various kinds of errors are possible when using the API, such as
824 mismatched types in an assignment.  You can only compile and get code
825 from a context if no errors occur.
827 Errors are printed on stderr; they typically contain the name of the API
828 entrypoint where the error occurred, and pertinent information on the
829 problem:
831 @example
832 ./buggy-program: error: gcc_jit_block_add_assignment: mismatching types: assignment to i (type: int) from "hello world" (type: const char *)
833 @end example
835 @noindent
837 The API is designed to cope with errors without crashing, so you can get
838 away with having a single error-handling check in your code:
840 @example
841 void *fn_ptr = gcc_jit_result_get_code (result, "square");
842 if (!fn_ptr)
843   @{
844     fprintf (stderr, "NULL fn_ptr");
845     goto error;
846   @}
847 @end example
849 @noindent
851 For more information, see the @pxref{19,,error-handling guide}
852 within the Topic eference.
854 @node Options,Full example,Error-handling,Tutorial part 2 Creating a trivial machine code function
855 @anchor{intro/tutorial02 options}@anchor{1a}
856 @subsection Options
859 To get more information on what's going on, you can set debugging flags
860 on the context using @pxref{1b,,gcc_jit_context_set_bool_option()}.
862 @c (I'm deliberately not mentioning
863 @c :c:macro:`GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE` here since I think
864 @c it's probably more of use to implementors than to users)
866 Setting @pxref{1c,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE} will dump a
867 C-like representation to stderr when you compile (GCC's "GIMPLE"
868 representation):
870 @example
871 gcc_jit_context_set_bool_option (
872   ctxt,
873   GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE,
874   1);
875 result = gcc_jit_context_compile (ctxt);
876 @end example
878 @noindent
880 @example
881 square (signed int i)
883   signed int D.260;
885   entry:
886   D.260 = i * i;
887   return D.260;
889 @end example
891 @noindent
893 We can see the generated machine code in assembler form (on stderr) by
894 setting @pxref{1d,,GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE} on the context
895 before compiling:
897 @example
898 gcc_jit_context_set_bool_option (
899   ctxt,
900   GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
901   1);
902 result = gcc_jit_context_compile (ctxt);
903 @end example
905 @noindent
907 @example
908       .file   "fake.c"
909       .text
910       .globl  square
911       .type   square, @@function
912 square:
913 .LFB6:
914       .cfi_startproc
915       pushq   %rbp
916       .cfi_def_cfa_offset 16
917       .cfi_offset 6, -16
918       movq    %rsp, %rbp
919       .cfi_def_cfa_register 6
920       movl    %edi, -4(%rbp)
921 .L14:
922       movl    -4(%rbp), %eax
923       imull   -4(%rbp), %eax
924       popq    %rbp
925       .cfi_def_cfa 7, 8
926       ret
927       .cfi_endproc
928 .LFE6:
929       .size   square, .-square
930       .ident  "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)"
931       .section       .note.GNU-stack,"",@@progbits
932 @end example
934 @noindent
936 By default, no optimizations are performed, the equivalent of GCC's
937 @cite{-O0} option.  We can turn things up to e.g. @cite{-O3} by calling
938 @pxref{1e,,gcc_jit_context_set_int_option()} with
939 @pxref{1f,,GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}:
941 @example
942 gcc_jit_context_set_int_option (
943   ctxt,
944   GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL,
945   3);
946 @end example
948 @noindent
950 @example
951       .file   "fake.c"
952       .text
953       .p2align 4,,15
954       .globl  square
955       .type   square, @@function
956 square:
957 .LFB7:
958       .cfi_startproc
959 .L16:
960       movl    %edi, %eax
961       imull   %edi, %eax
962       ret
963       .cfi_endproc
964 .LFE7:
965       .size   square, .-square
966       .ident  "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)"
967       .section        .note.GNU-stack,"",@@progbits
968 @end example
970 @noindent
972 Naturally this has only a small effect on such a trivial function.
974 @node Full example,,Options,Tutorial part 2 Creating a trivial machine code function
975 @anchor{intro/tutorial02 full-example}@anchor{20}
976 @subsection Full example
979 Here's what the above looks like as a complete program:
981 @quotation
983 @example
984 /* Usage example for libgccjit.so
985    Copyright (C) 2014-2015 Free Software Foundation, Inc.
987 This file is part of GCC.
989 GCC is free software; you can redistribute it and/or modify it
990 under the terms of the GNU General Public License as published by
991 the Free Software Foundation; either version 3, or (at your option)
992 any later version.
994 GCC is distributed in the hope that it will be useful, but
995 WITHOUT ANY WARRANTY; without even the implied warranty of
996 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
997 General Public License for more details.
999 You should have received a copy of the GNU General Public License
1000 along with GCC; see the file COPYING3.  If not see
1001 <http://www.gnu.org/licenses/>.  */
1003 #include <libgccjit.h>
1005 #include <stdlib.h>
1006 #include <stdio.h>
1008 void
1009 create_code (gcc_jit_context *ctxt)
1011   /* Let's try to inject the equivalent of:
1013       int square (int i)
1014       @{
1015         return i * i;
1016       @}
1017   */
1018   gcc_jit_type *int_type =
1019     gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
1020   gcc_jit_param *param_i =
1021     gcc_jit_context_new_param (ctxt, NULL, int_type, "i");
1022   gcc_jit_function *func =
1023     gcc_jit_context_new_function (ctxt, NULL,
1024                                   GCC_JIT_FUNCTION_EXPORTED,
1025                                   int_type,
1026                                   "square",
1027                                   1, &param_i,
1028                                   0);
1030   gcc_jit_block *block = gcc_jit_function_new_block (func, NULL);
1032   gcc_jit_rvalue *expr =
1033     gcc_jit_context_new_binary_op (
1034       ctxt, NULL,
1035       GCC_JIT_BINARY_OP_MULT, int_type,
1036       gcc_jit_param_as_rvalue (param_i),
1037       gcc_jit_param_as_rvalue (param_i));
1039    gcc_jit_block_end_with_return (block, NULL, expr);
1043 main (int argc, char **argv)
1045   gcc_jit_context *ctxt = NULL;
1046   gcc_jit_result *result = NULL;
1048   /* Get a "context" object for working with the library.  */
1049   ctxt = gcc_jit_context_acquire ();
1050   if (!ctxt)
1051     @{
1052       fprintf (stderr, "NULL ctxt");
1053       goto error;
1054     @}
1056   /* Set some options on the context.
1057      Let's see the code being generated, in assembler form.  */
1058   gcc_jit_context_set_bool_option (
1059     ctxt,
1060     GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
1061     0);
1063   /* Populate the context.  */
1064   create_code (ctxt);
1066   /* Compile the code.  */
1067   result = gcc_jit_context_compile (ctxt);
1068   if (!result)
1069     @{
1070       fprintf (stderr, "NULL result");
1071       goto error;
1072     @}
1074   /* We're done with the context; we can release it: */
1075   gcc_jit_context_release (ctxt);
1076   ctxt = NULL;
1078   /* Extract the generated code from "result".  */
1079   void *fn_ptr = gcc_jit_result_get_code (result, "square");
1080   if (!fn_ptr)
1081      @{
1082        fprintf (stderr, "NULL fn_ptr");
1083        goto error;
1084      @}
1086   typedef int (*fn_type) (int);
1087   fn_type square = (fn_type)fn_ptr;
1088   printf ("result: %d\n", square (5));
1090  error:
1091   if (ctxt)
1092     gcc_jit_context_release (ctxt);
1093   if (result)
1094     gcc_jit_result_release (result);
1095   return 0;
1098 @end example
1100 @noindent
1101 @end quotation
1103 Building and running it:
1105 @example
1106 $ gcc \
1107     tut02-square.c \
1108     -o tut02-square \
1109     -lgccjit
1111 # Run the built program:
1112 $ ./tut02-square
1113 result: 25
1114 @end example
1116 @noindent
1118 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
1119 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
1120 @c 
1121 @c This is free software: you can redistribute it and/or modify it
1122 @c under the terms of the GNU General Public License as published by
1123 @c the Free Software Foundation, either version 3 of the License, or
1124 @c (at your option) any later version.
1125 @c 
1126 @c This program is distributed in the hope that it will be useful, but
1127 @c WITHOUT ANY WARRANTY; without even the implied warranty of
1128 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
1129 @c General Public License for more details.
1130 @c 
1131 @c You should have received a copy of the GNU General Public License
1132 @c along with this program.  If not, see
1133 @c <http://www.gnu.org/licenses/>.
1135 @node Tutorial part 3 Loops and variables,Tutorial part 4 Adding JIT-compilation to a toy interpreter,Tutorial part 2 Creating a trivial machine code function,Tutorial
1136 @anchor{intro/tutorial03 tutorial-part-3-loops-and-variables}@anchor{21}@anchor{intro/tutorial03 doc}@anchor{22}
1137 @section Tutorial part 3: Loops and variables
1140 Consider this C function:
1142 @quotation
1144 @example
1145 int loop_test (int n)
1147   int sum = 0;
1148   for (int i = 0; i < n; i++)
1149     sum += i * i;
1150   return sum;
1152 @end example
1154 @noindent
1155 @end quotation
1157 This example demonstrates some more features of libgccjit, with local
1158 variables and a loop.
1160 To break this down into libgccjit terms, it's usually easier to reword
1161 the @cite{for} loop as a @cite{while} loop, giving:
1163 @quotation
1165 @example
1166 int loop_test (int n)
1168   int sum = 0;
1169   int i = 0;
1170   while (i < n)
1171   @{
1172     sum += i * i;
1173     i++;
1174   @}
1175   return sum;
1177 @end example
1179 @noindent
1180 @end quotation
1182 Here's what the final control flow graph will look like:
1184 @quotation
1187 @float Figure
1189 @image{sum-of-squares1,,,image of a control flow graph,png}
1191 @end float
1193 @end quotation
1195 As before, we include the libgccjit header and make a
1196 @pxref{8,,gcc_jit_context *}.
1198 @example
1199 #include <libgccjit.h>
1201 void test (void)
1203   gcc_jit_context *ctxt;
1204   ctxt = gcc_jit_context_acquire ();
1205 @end example
1207 @noindent
1209 The function works with the C @cite{int} type:
1211 @example
1212 gcc_jit_type *the_type =
1213   gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
1214 gcc_jit_type *return_type = the_type;
1215 @end example
1217 @noindent
1219 though we could equally well make it work on, say, @cite{double}:
1221 @example
1222 gcc_jit_type *the_type =
1223   gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_DOUBLE);
1224 @end example
1226 @noindent
1228 Let's build the function:
1230 @example
1231 gcc_jit_param *n =
1232   gcc_jit_context_new_param (ctxt, NULL, the_type, "n");
1233 gcc_jit_param *params[1] = @{n@};
1234 gcc_jit_function *func =
1235   gcc_jit_context_new_function (ctxt, NULL,
1236                                 GCC_JIT_FUNCTION_EXPORTED,
1237                                 return_type,
1238                                 "loop_test",
1239                                 1, params, 0);
1240 @end example
1242 @noindent
1244 @menu
1245 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues. 
1246 * Control flow:: 
1247 * Visualizing the control flow graph:: 
1248 * Full example: Full example<2>. 
1250 @end menu
1252 @node Expressions lvalues and rvalues,Control flow,,Tutorial part 3 Loops and variables
1253 @anchor{intro/tutorial03 expressions-lvalues-and-rvalues}@anchor{23}
1254 @subsection Expressions: lvalues and rvalues
1257 The base class of expression is the @pxref{13,,gcc_jit_rvalue *},
1258 representing an expression that can be on the @emph{right}-hand side of
1259 an assignment: a value that can be computed somehow, and assigned
1260 @emph{to} a storage area (such as a variable).  It has a specific
1261 @pxref{a,,gcc_jit_type *}.
1263 Anothe important class is @pxref{24,,gcc_jit_lvalue *}.
1264 A @pxref{24,,gcc_jit_lvalue *}. is something that can of the @emph{left}-hand
1265 side of an assignment: a storage area (such as a variable).
1267 In other words, every assignment can be thought of as:
1269 @example
1270 LVALUE = RVALUE;
1271 @end example
1273 @noindent
1275 Note that @pxref{24,,gcc_jit_lvalue *} is a subclass of
1276 @pxref{13,,gcc_jit_rvalue *}, where in an assignment of the form:
1278 @example
1279 LVALUE_A = LVALUE_B;
1280 @end example
1282 @noindent
1284 the @cite{LVALUE_B} implies reading the current value of that storage
1285 area, assigning it into the @cite{LVALUE_A}.
1287 So far the only expressions we've seen are @cite{i * i}:
1289 @example
1290 gcc_jit_rvalue *expr =
1291   gcc_jit_context_new_binary_op (
1292     ctxt, NULL,
1293     GCC_JIT_BINARY_OP_MULT, int_type,
1294     gcc_jit_param_as_rvalue (param_i),
1295     gcc_jit_param_as_rvalue (param_i));
1296 @end example
1298 @noindent
1300 which is a @pxref{13,,gcc_jit_rvalue *}, and the various function
1301 parameters: @cite{param_i} and @cite{param_n}, instances of
1302 @pxref{25,,gcc_jit_param *}, which is a subclass of
1303 @pxref{24,,gcc_jit_lvalue *} (and, in turn, of @pxref{13,,gcc_jit_rvalue *}):
1304 we can both read from and write to function parameters within the
1305 body of a function.
1307 Our new example has a couple of local variables.  We create them by
1308 calling @pxref{26,,gcc_jit_function_new_local()}, supplying a type and a
1309 name:
1311 @example
1312 /* Build locals:  */
1313 gcc_jit_lvalue *i =
1314   gcc_jit_function_new_local (func, NULL, the_type, "i");
1315 gcc_jit_lvalue *sum =
1316   gcc_jit_function_new_local (func, NULL, the_type, "sum");
1317 @end example
1319 @noindent
1321 These are instances of @pxref{24,,gcc_jit_lvalue *} - they can be read from
1322 and written to.
1324 Note that there is no precanned way to create @emph{and} initialize a variable
1325 like in C:
1327 @example
1328 int i = 0;
1329 @end example
1331 @noindent
1333 Instead, having added the local to the function, we have to separately add
1334 an assignment of @cite{0} to @cite{local_i} at the beginning of the function.
1336 @node Control flow,Visualizing the control flow graph,Expressions lvalues and rvalues,Tutorial part 3 Loops and variables
1337 @anchor{intro/tutorial03 control-flow}@anchor{27}
1338 @subsection Control flow
1341 This function has a loop, so we need to build some basic blocks to
1342 handle the control flow.  In this case, we need 4 blocks:
1345 @enumerate 
1347 @item 
1348 before the loop (initializing the locals)
1350 @item 
1351 the conditional at the top of the loop (comparing @cite{i < n})
1353 @item 
1354 the body of the loop
1356 @item 
1357 after the loop terminates (@cite{return sum})
1358 @end enumerate
1360 so we create these as @pxref{28,,gcc_jit_block *} instances within the
1361 @pxref{29,,gcc_jit_function *}:
1363 @example
1364 gcc_jit_block *b_initial =
1365   gcc_jit_function_new_block (func, "initial");
1366 gcc_jit_block *b_loop_cond =
1367   gcc_jit_function_new_block (func, "loop_cond");
1368 gcc_jit_block *b_loop_body =
1369   gcc_jit_function_new_block (func, "loop_body");
1370 gcc_jit_block *b_after_loop =
1371   gcc_jit_function_new_block (func, "after_loop");
1372 @end example
1374 @noindent
1376 We now populate each block with statements.
1378 The entry block @cite{b_initial} consists of initializations followed by a jump
1379 to the conditional.  We assign @cite{0} to @cite{i} and to @cite{sum}, using
1380 @pxref{2a,,gcc_jit_block_add_assignment()} to add
1381 an assignment statement, and using @pxref{2b,,gcc_jit_context_zero()} to get
1382 the constant value @cite{0} for the relevant type for the right-hand side of
1383 the assignment:
1385 @example
1386 /* sum = 0; */
1387 gcc_jit_block_add_assignment (
1388   b_initial, NULL,
1389   sum,
1390   gcc_jit_context_zero (ctxt, the_type));
1392 /* i = 0; */
1393 gcc_jit_block_add_assignment (
1394   b_initial, NULL,
1395   i,
1396   gcc_jit_context_zero (ctxt, the_type));
1397 @end example
1399 @noindent
1401 We can then terminate the entry block by jumping to the conditional:
1403 @example
1404 gcc_jit_block_end_with_jump (b_initial, NULL, b_loop_cond);
1405 @end example
1407 @noindent
1409 The conditional block is equivalent to the line @cite{while (i < n)} from our
1410 C example. It contains a single statement: a conditional, which jumps to
1411 one of two destination blocks depending on a boolean
1412 @pxref{13,,gcc_jit_rvalue *}, in this case the comparison of @cite{i} and @cite{n}.
1413 We build the comparison using @pxref{2c,,gcc_jit_context_new_comparison()}:
1415 @example
1416 gcc_jit_rvalue *guard =
1417   gcc_jit_context_new_comparison (
1418     ctxt, NULL,
1419     GCC_JIT_COMPARISON_GE,
1420     gcc_jit_lvalue_as_rvalue (i),
1421     gcc_jit_param_as_rvalue (n));
1422 @end example
1424 @noindent
1426 and can then use this to add @cite{b_loop_cond}'s sole statement, via
1427 @pxref{2d,,gcc_jit_block_end_with_conditional()}:
1429 @example
1430 gcc_jit_block_end_with_conditional (b_loop_cond, NULL, guard);
1431 @end example
1433 @noindent
1435 Next, we populate the body of the loop.
1437 The C statement @cite{sum += i * i;} is an assignment operation, where an
1438 lvalue is modified "in-place".  We use
1439 @pxref{2e,,gcc_jit_block_add_assignment_op()} to handle these operations:
1441 @example
1442 /* sum += i * i */
1443 gcc_jit_block_add_assignment_op (
1444   b_loop_body, NULL,
1445   sum,
1446   GCC_JIT_BINARY_OP_PLUS,
1447   gcc_jit_context_new_binary_op (
1448     ctxt, NULL,
1449     GCC_JIT_BINARY_OP_MULT, the_type,
1450     gcc_jit_lvalue_as_rvalue (i),
1451     gcc_jit_lvalue_as_rvalue (i)));
1452 @end example
1454 @noindent
1456 The @cite{i++} can be thought of as @cite{i += 1}, and can thus be handled in
1457 a similar way.  We use @pxref{2f,,gcc_jit_context_one()} to get the constant
1458 value @cite{1} (for the relevant type) for the right-hand side
1459 of the assignment.
1461 @example
1462 /* i++ */
1463 gcc_jit_block_add_assignment_op (
1464   b_loop_body, NULL,
1465   i,
1466   GCC_JIT_BINARY_OP_PLUS,
1467   gcc_jit_context_one (ctxt, the_type));
1468 @end example
1470 @noindent
1472 @cartouche
1473 @quotation Note 
1474 For numeric constants other than 0 or 1, we could use
1475 @pxref{30,,gcc_jit_context_new_rvalue_from_int()} and
1476 @pxref{31,,gcc_jit_context_new_rvalue_from_double()}.
1477 @end quotation
1478 @end cartouche
1480 The loop body completes by jumping back to the conditional:
1482 @example
1483 gcc_jit_block_end_with_jump (b_loop_body, NULL, b_loop_cond);
1484 @end example
1486 @noindent
1488 Finally, we populate the @cite{b_after_loop} block, reached when the loop
1489 conditional is false.  We want to generate the equivalent of:
1491 @example
1492 return sum;
1493 @end example
1495 @noindent
1497 so the block is just one statement:
1499 @example
1500 /* return sum */
1501 gcc_jit_block_end_with_return (
1502   b_after_loop,
1503   NULL,
1504   gcc_jit_lvalue_as_rvalue (sum));
1505 @end example
1507 @noindent
1509 @cartouche
1510 @quotation Note 
1511 You can intermingle block creation with statement creation,
1512 but given that the terminator statements generally include references
1513 to other blocks, I find it's clearer to create all the blocks,
1514 @emph{then} all the statements.
1515 @end quotation
1516 @end cartouche
1518 We've finished populating the function.  As before, we can now compile it
1519 to machine code:
1521 @example
1522 gcc_jit_result *result;
1523 result = gcc_jit_context_compile (ctxt);
1525 typedef int (*loop_test_fn_type) (int);
1526 loop_test_fn_type loop_test =
1527  (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
1528 if (!loop_test)
1529   goto error;
1530 printf ("result: %d", loop_test (10));
1531 @end example
1533 @noindent
1535 @example
1536 result: 285
1537 @end example
1539 @noindent
1541 @node Visualizing the control flow graph,Full example<2>,Control flow,Tutorial part 3 Loops and variables
1542 @anchor{intro/tutorial03 visualizing-the-control-flow-graph}@anchor{32}
1543 @subsection Visualizing the control flow graph
1546 You can see the control flow graph of a function using
1547 @pxref{33,,gcc_jit_function_dump_to_dot()}:
1549 @example
1550 gcc_jit_function_dump_to_dot (func, "/tmp/sum-of-squares.dot");
1551 @end example
1553 @noindent
1555 giving a .dot file in GraphViz format.
1557 You can convert this to an image using @cite{dot}:
1559 @example
1560 $ dot -Tpng /tmp/sum-of-squares.dot -o /tmp/sum-of-squares.png
1561 @end example
1563 @noindent
1565 or use a viewer (my preferred one is xdot.py; see
1566 @indicateurl{https://github.com/jrfonseca/xdot.py}; on Fedora you can
1567 install it with @cite{yum install python-xdot}):
1569 @quotation
1572 @float Figure
1574 @image{sum-of-squares1,,,image of a control flow graph,png}
1576 @end float
1578 @end quotation
1580 @node Full example<2>,,Visualizing the control flow graph,Tutorial part 3 Loops and variables
1581 @anchor{intro/tutorial03 full-example}@anchor{34}
1582 @subsection Full example
1585 @quotation
1587 @example
1588 /* Usage example for libgccjit.so
1589    Copyright (C) 2014-2015 Free Software Foundation, Inc.
1591 This file is part of GCC.
1593 GCC is free software; you can redistribute it and/or modify it
1594 under the terms of the GNU General Public License as published by
1595 the Free Software Foundation; either version 3, or (at your option)
1596 any later version.
1598 GCC is distributed in the hope that it will be useful, but
1599 WITHOUT ANY WARRANTY; without even the implied warranty of
1600 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
1601 General Public License for more details.
1603 You should have received a copy of the GNU General Public License
1604 along with GCC; see the file COPYING3.  If not see
1605 <http://www.gnu.org/licenses/>.  */
1607 #include <libgccjit.h>
1609 #include <stdlib.h>
1610 #include <stdio.h>
1612 void
1613 create_code (gcc_jit_context *ctxt)
1615   /*
1616     Simple sum-of-squares, to test conditionals and looping
1618     int loop_test (int n)
1619     @{
1620       int i;
1621       int sum = 0;
1622       for (i = 0; i < n ; i ++)
1623       @{
1624         sum += i * i;
1625       @}
1626       return sum;
1627    */
1628   gcc_jit_type *the_type =
1629     gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
1630   gcc_jit_type *return_type = the_type;
1632   gcc_jit_param *n =
1633     gcc_jit_context_new_param (ctxt, NULL, the_type, "n");
1634   gcc_jit_param *params[1] = @{n@};
1635   gcc_jit_function *func =
1636     gcc_jit_context_new_function (ctxt, NULL,
1637                                   GCC_JIT_FUNCTION_EXPORTED,
1638                                   return_type,
1639                                   "loop_test",
1640                                   1, params, 0);
1642   /* Build locals:  */
1643   gcc_jit_lvalue *i =
1644     gcc_jit_function_new_local (func, NULL, the_type, "i");
1645   gcc_jit_lvalue *sum =
1646     gcc_jit_function_new_local (func, NULL, the_type, "sum");
1648   gcc_jit_block *b_initial =
1649     gcc_jit_function_new_block (func, "initial");
1650   gcc_jit_block *b_loop_cond =
1651     gcc_jit_function_new_block (func, "loop_cond");
1652   gcc_jit_block *b_loop_body =
1653     gcc_jit_function_new_block (func, "loop_body");
1654   gcc_jit_block *b_after_loop =
1655     gcc_jit_function_new_block (func, "after_loop");
1657   /* sum = 0; */
1658   gcc_jit_block_add_assignment (
1659     b_initial, NULL,
1660     sum,
1661     gcc_jit_context_zero (ctxt, the_type));
1663   /* i = 0; */
1664   gcc_jit_block_add_assignment (
1665     b_initial, NULL,
1666     i,
1667     gcc_jit_context_zero (ctxt, the_type));
1669   gcc_jit_block_end_with_jump (b_initial, NULL, b_loop_cond);
1671   /* if (i >= n) */
1672   gcc_jit_block_end_with_conditional (
1673     b_loop_cond, NULL,
1674     gcc_jit_context_new_comparison (
1675        ctxt, NULL,
1676        GCC_JIT_COMPARISON_GE,
1677        gcc_jit_lvalue_as_rvalue (i),
1678        gcc_jit_param_as_rvalue (n)),
1679     b_after_loop,
1680     b_loop_body);
1682   /* sum += i * i */
1683   gcc_jit_block_add_assignment_op (
1684     b_loop_body, NULL,
1685     sum,
1686     GCC_JIT_BINARY_OP_PLUS,
1687     gcc_jit_context_new_binary_op (
1688       ctxt, NULL,
1689       GCC_JIT_BINARY_OP_MULT, the_type,
1690       gcc_jit_lvalue_as_rvalue (i),
1691       gcc_jit_lvalue_as_rvalue (i)));
1693   /* i++ */
1694   gcc_jit_block_add_assignment_op (
1695     b_loop_body, NULL,
1696     i,
1697     GCC_JIT_BINARY_OP_PLUS,
1698     gcc_jit_context_one (ctxt, the_type));
1700   gcc_jit_block_end_with_jump (b_loop_body, NULL, b_loop_cond);
1702   /* return sum */
1703   gcc_jit_block_end_with_return (
1704     b_after_loop,
1705     NULL,
1706     gcc_jit_lvalue_as_rvalue (sum));
1710 main (int argc, char **argv)
1712   gcc_jit_context *ctxt = NULL;
1713   gcc_jit_result *result = NULL;
1715   /* Get a "context" object for working with the library.  */
1716   ctxt = gcc_jit_context_acquire ();
1717   if (!ctxt)
1718     @{
1719       fprintf (stderr, "NULL ctxt");
1720       goto error;
1721     @}
1723   /* Set some options on the context.
1724      Let's see the code being generated, in assembler form.  */
1725   gcc_jit_context_set_bool_option (
1726     ctxt,
1727     GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
1728     0);
1730   /* Populate the context.  */
1731   create_code (ctxt);
1733   /* Compile the code.  */
1734   result = gcc_jit_context_compile (ctxt);
1735   if (!result)
1736     @{
1737       fprintf (stderr, "NULL result");
1738       goto error;
1739     @}
1741   /* Extract the generated code from "result".  */
1742   typedef int (*loop_test_fn_type) (int);
1743   loop_test_fn_type loop_test =
1744     (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
1745   if (!loop_test)
1746     @{
1747       fprintf (stderr, "NULL loop_test");
1748       goto error;
1749     @}
1751   /* Run the generated code.  */
1752   int val = loop_test (10);
1753   printf("loop_test returned: %d\n", val);
1755  error:
1756   gcc_jit_context_release (ctxt);
1757   gcc_jit_result_release (result);
1758   return 0;
1761 @end example
1763 @noindent
1764 @end quotation
1766 Building and running it:
1768 @example
1769 $ gcc \
1770     tut03-sum-of-squares.c \
1771     -o tut03-sum-of-squares \
1772     -lgccjit
1774 # Run the built program:
1775 $ ./tut03-sum-of-squares
1776 loop_test returned: 285
1777 @end example
1779 @noindent
1781 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
1782 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
1783 @c 
1784 @c This is free software: you can redistribute it and/or modify it
1785 @c under the terms of the GNU General Public License as published by
1786 @c the Free Software Foundation, either version 3 of the License, or
1787 @c (at your option) any later version.
1788 @c 
1789 @c This program is distributed in the hope that it will be useful, but
1790 @c WITHOUT ANY WARRANTY; without even the implied warranty of
1791 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
1792 @c General Public License for more details.
1793 @c 
1794 @c You should have received a copy of the GNU General Public License
1795 @c along with this program.  If not, see
1796 @c <http://www.gnu.org/licenses/>.
1798 @node Tutorial part 4 Adding JIT-compilation to a toy interpreter,,Tutorial part 3 Loops and variables,Tutorial
1799 @anchor{intro/tutorial04 tutorial-part-4-adding-jit-compilation-to-a-toy-interpreter}@anchor{35}@anchor{intro/tutorial04 doc}@anchor{36}
1800 @section Tutorial part 4: Adding JIT-compilation to a toy interpreter
1803 In this example we construct a "toy" interpreter, and add JIT-compilation
1804 to it.
1806 @menu
1807 * Our toy interpreter:: 
1808 * Compiling to machine code:: 
1809 * Setting things up:: 
1810 * Populating the function:: 
1811 * Verifying the control flow graph:: 
1812 * Compiling the context:: 
1813 * Single-stepping through the generated code:: 
1814 * Examining the generated code:: 
1815 * Putting it all together:: 
1816 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?. 
1818 @end menu
1820 @node Our toy interpreter,Compiling to machine code,,Tutorial part 4 Adding JIT-compilation to a toy interpreter
1821 @anchor{intro/tutorial04 our-toy-interpreter}@anchor{37}
1822 @subsection Our toy interpreter
1825 It's a stack-based interpreter, and is intended as a (very simple) example
1826 of the kind of bytecode interpreter seen in dynamic languages such as
1827 Python, Ruby etc.
1829 For the sake of simplicity, our toy virtual machine is very limited:
1831 @quotation
1834 @itemize *
1836 @item 
1837 The only data type is @cite{int}
1839 @item 
1840 It can only work on one function at a time (so that the only
1841 function call that can be made is to recurse).
1843 @item 
1844 Functions can only take one parameter.
1846 @item 
1847 Functions have a stack of @cite{int} values.
1849 @item 
1850 We'll implement function call within the interpreter by calling a
1851 function in our implementation, rather than implementing our own
1852 frame stack.
1854 @item 
1855 The parser is only good enough to get the examples to work.
1856 @end itemize
1857 @end quotation
1859 Naturally, a real interpreter would be much more complicated that this.
1861 The following operations are supported:
1864 @multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxx} 
1865 @headitem
1867 Operation
1869 @tab
1871 Meaning
1873 @tab
1875 Old Stack
1877 @tab
1879 New Stack
1881 @item
1885 @tab
1887 Duplicate top of stack.
1889 @tab
1891 @code{[..., x]}
1893 @tab
1895 @code{[..., x, x]}
1897 @item
1901 @tab
1903 Swap top two elements
1904 of stack.
1906 @tab
1908 @code{[..., x, y]}
1910 @tab
1912 @code{[..., y, x]}
1914 @item
1916 BINARY_ADD
1918 @tab
1920 Add the top two elements
1921 on the stack.
1923 @tab
1925 @code{[..., x, y]}
1927 @tab
1929 @code{[..., (x+y)]}
1931 @item
1933 BINARY_SUBTRACT
1935 @tab
1937 Likewise, but subtract.
1939 @tab
1941 @code{[..., x, y]}
1943 @tab
1945 @code{[..., (x-y)]}
1947 @item
1949 BINARY_MULT
1951 @tab
1953 Likewise, but multiply.
1955 @tab
1957 @code{[..., x, y]}
1959 @tab
1961 @code{[..., (x*y)]}
1963 @item
1965 BINARY_COMPARE_LT
1967 @tab
1969 Compare the top two
1970 elements on the stack
1971 and push a nonzero/zero
1972 if (x<y).
1974 @tab
1976 @code{[..., x, y]}
1978 @tab
1980 @code{[..., (x<y)]}
1982 @item
1984 RECURSE
1986 @tab
1988 Recurse, passing the top
1989 of the stack, and
1990 popping the result.
1992 @tab
1994 @code{[..., x]}
1996 @tab
1998 @code{[..., fn(x)]}
2000 @item
2002 RETURN
2004 @tab
2006 Return the top of the
2007 stack.
2009 @tab
2011 @code{[x]}
2013 @tab
2015 @code{[]}
2017 @item
2019 PUSH_CONST @cite{arg}
2021 @tab
2023 Push an int const.
2025 @tab
2027 @code{[...]}
2029 @tab
2031 @code{[..., arg]}
2033 @item
2035 JUMP_ABS_IF_TRUE @cite{arg}
2037 @tab
2039 Pop; if top of stack was
2040 nonzero, jump to
2041 @code{arg}.
2043 @tab
2045 @code{[..., x]}
2047 @tab
2049 @code{[...]}
2051 @end multitable
2054 Programs can be interpreted, disassembled, and compiled to machine code.
2056 The interpreter reads @code{.toy} scripts.  Here's what a simple recursive
2057 factorial program looks like, the script @code{factorial.toy}.
2058 The parser ignores lines beginning with a @cite{#}.
2060 @quotation
2062 @example
2063 # Simple recursive factorial implementation, roughly equivalent to:
2065 #  int factorial (int arg)
2066 #  @{
2067 #     if (arg < 2)
2068 #       return arg
2069 #     return arg * factorial (arg - 1)
2070 #  @}
2072 # Initial state:
2073 # stack: [arg]
2075 # 0:
2077 # stack: [arg, arg]
2079 # 1:
2080 PUSH_CONST 2
2081 # stack: [arg, arg, 2]
2083 # 2:
2084 BINARY_COMPARE_LT
2085 # stack: [arg, (arg < 2)]
2087 # 3:
2088 JUMP_ABS_IF_TRUE 9
2089 # stack: [arg]
2091 # 4:
2093 # stack: [arg, arg]
2095 # 5:
2096 PUSH_CONST 1
2097 # stack: [arg, arg, 1]
2099 # 6:
2100 BINARY_SUBTRACT
2101 # stack: [arg,  (arg - 1)
2103 # 7:
2104 RECURSE
2105 # stack: [arg, factorial(arg - 1)]
2107 # 8:
2108 BINARY_MULT
2109 # stack: [arg * factorial(arg - 1)]
2111 # 9:
2112 RETURN
2114 @end example
2116 @noindent
2117 @end quotation
2119 The interpreter is a simple infinite loop with a big @code{switch} statement
2120 based on what the next opcode is:
2122 @quotation
2124 @example
2126 static int
2127 toyvm_function_interpret (toyvm_function *fn, int arg, FILE *trace)
2129   toyvm_frame frame;
2130 #define PUSH(ARG) (toyvm_frame_push (&frame, (ARG)))
2131 #define POP(ARG) (toyvm_frame_pop (&frame))
2133   frame.frm_function = fn;
2134   frame.frm_pc = 0;
2135   frame.frm_cur_depth = 0;
2137   PUSH (arg);
2139   while (1)
2140     @{
2141       toyvm_op *op;
2142       int x, y;
2143       assert (frame.frm_pc < fn->fn_num_ops);
2144       op = &fn->fn_ops[frame.frm_pc++];
2146       if (trace)
2147         @{
2148           toyvm_frame_dump_stack (&frame, trace);
2149           toyvm_function_disassemble_op (fn, op, frame.frm_pc, trace);
2150         @}
2152       switch (op->op_opcode)
2153         @{
2154           /* Ops taking no operand.  */
2155         case DUP:
2156           x = POP ();
2157           PUSH (x);
2158           PUSH (x);
2159           break;
2161         case ROT:
2162           y = POP ();
2163           x = POP ();
2164           PUSH (y);
2165           PUSH (x);
2166           break;
2168         case BINARY_ADD:
2169           y = POP ();
2170           x = POP ();
2171           PUSH (x + y);
2172           break;
2174         case BINARY_SUBTRACT:
2175           y = POP ();
2176           x = POP ();
2177           PUSH (x - y);
2178           break;
2180         case BINARY_MULT:
2181           y = POP ();
2182           x = POP ();
2183           PUSH (x * y);
2184           break;
2186         case BINARY_COMPARE_LT:
2187           y = POP ();
2188           x = POP ();
2189           PUSH (x < y);
2190           break;
2192         case RECURSE:
2193           x = POP ();
2194           x = toyvm_function_interpret (fn, x, trace);
2195           PUSH (x);
2196           break;
2198         case RETURN:
2199           return POP ();
2201           /* Ops taking an operand.  */
2202         case PUSH_CONST:
2203           PUSH (op->op_operand);
2204           break;
2206         case JUMP_ABS_IF_TRUE:
2207           x = POP ();
2208           if (x)
2209             frame.frm_pc = op->op_operand;
2210           break;
2212         default:
2213           assert (0); /* unknown opcode */
2215         @} /* end of switch on opcode */
2216     @} /* end of while loop */
2218 #undef PUSH
2219 #undef POP
2223 @end example
2225 @noindent
2226 @end quotation
2228 @node Compiling to machine code,Setting things up,Our toy interpreter,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2229 @anchor{intro/tutorial04 compiling-to-machine-code}@anchor{38}
2230 @subsection Compiling to machine code
2233 We want to generate machine code that can be cast to this type and
2234 then directly executed in-process:
2236 @quotation
2238 @example
2239 typedef int (*toyvm_compiled_code) (int);
2242 @end example
2244 @noindent
2245 @end quotation
2247 The lifetime of the code is tied to that of a @pxref{16,,gcc_jit_result *}.
2248 We'll handle this by bundling them up in a structure, so that we can
2249 clean them up together by calling @pxref{39,,gcc_jit_result_release()}:
2251 @quotation
2253 @example
2255 struct toyvm_compiled_function
2257   gcc_jit_result *cf_jit_result;
2258   toyvm_compiled_code cf_code;
2262 @end example
2264 @noindent
2265 @end quotation
2267 Our compiler isn't very sophisticated; it takes the implementation of
2268 each opcode above, and maps it directly to the operations supported by
2269 the libgccjit API.
2271 How should we handle the stack?  In theory we could calculate what the
2272 stack depth will be at each opcode, and optimize away the stack
2273 manipulation "by hand".  We'll see below that libgccjit is able to do
2274 this for us, so we'll implement stack manipulation
2275 in a direct way, by creating a @code{stack} array and @code{stack_depth}
2276 variables, local within the generated function, equivalent to this C code:
2278 @example
2279 int stack_depth;
2280 int stack[MAX_STACK_DEPTH];
2281 @end example
2283 @noindent
2285 We'll also have local variables @code{x} and @code{y} for use when implementing
2286 the opcodes, equivalent to this:
2288 @example
2289 int x;
2290 int y;
2291 @end example
2293 @noindent
2295 This means our compiler has the following state:
2297 @quotation
2299 @example
2301 struct compilation_state
2303   gcc_jit_context *ctxt;
2305   gcc_jit_type *int_type;
2306   gcc_jit_type *bool_type;
2307   gcc_jit_type *stack_type; /* int[MAX_STACK_DEPTH] */
2309   gcc_jit_rvalue *const_one;
2311   gcc_jit_function *fn;
2312   gcc_jit_param *param_arg;
2313   gcc_jit_lvalue *stack;
2314   gcc_jit_lvalue *stack_depth;
2315   gcc_jit_lvalue *x;
2316   gcc_jit_lvalue *y;
2318   gcc_jit_location *op_locs[MAX_OPS];
2319   gcc_jit_block *initial_block;
2320   gcc_jit_block *op_blocks[MAX_OPS];
2325 @end example
2327 @noindent
2328 @end quotation
2330 @node Setting things up,Populating the function,Compiling to machine code,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2331 @anchor{intro/tutorial04 setting-things-up}@anchor{3a}
2332 @subsection Setting things up
2335 First we create our types:
2337 @quotation
2339 @example
2340   state.int_type =
2341     gcc_jit_context_get_type (state.ctxt, GCC_JIT_TYPE_INT);
2342   state.bool_type =
2343     gcc_jit_context_get_type (state.ctxt, GCC_JIT_TYPE_BOOL);
2344   state.stack_type =
2345     gcc_jit_context_new_array_type (state.ctxt, NULL,
2346                                     state.int_type, MAX_STACK_DEPTH);
2349 @end example
2351 @noindent
2352 @end quotation
2354 along with extracting a useful @cite{int} constant:
2356 @quotation
2358 @example
2359   state.const_one = gcc_jit_context_one (state.ctxt, state.int_type);
2362 @end example
2364 @noindent
2365 @end quotation
2367 We'll implement push and pop in terms of the @code{stack} array and
2368 @code{stack_depth}.  Here are helper functions for adding statements to
2369 a block, implementing pushing and popping values:
2371 @quotation
2373 @example
2375 static void
2376 add_push (compilation_state *state,
2377           gcc_jit_block *block,
2378           gcc_jit_rvalue *rvalue,
2379           gcc_jit_location *loc)
2381   /* stack[stack_depth] = RVALUE */
2382   gcc_jit_block_add_assignment (
2383     block,
2384     loc,
2385     /* stack[stack_depth] */
2386     gcc_jit_context_new_array_access (
2387       state->ctxt,
2388       loc,
2389       gcc_jit_lvalue_as_rvalue (state->stack),
2390       gcc_jit_lvalue_as_rvalue (state->stack_depth)),
2391     rvalue);
2393   /* "stack_depth++;".  */
2394   gcc_jit_block_add_assignment_op (
2395     block,
2396     loc,
2397     state->stack_depth,
2398     GCC_JIT_BINARY_OP_PLUS,
2399     state->const_one);
2402 static void
2403 add_pop (compilation_state *state,
2404          gcc_jit_block *block,
2405          gcc_jit_lvalue *lvalue,
2406          gcc_jit_location *loc)
2408   /* "--stack_depth;".  */
2409   gcc_jit_block_add_assignment_op (
2410     block,
2411     loc,
2412     state->stack_depth,
2413     GCC_JIT_BINARY_OP_MINUS,
2414     state->const_one);
2416   /* "LVALUE = stack[stack_depth];".  */
2417   gcc_jit_block_add_assignment (
2418     block,
2419     loc,
2420     lvalue,
2421     /* stack[stack_depth] */
2422     gcc_jit_lvalue_as_rvalue (
2423       gcc_jit_context_new_array_access (
2424         state->ctxt,
2425         loc,
2426         gcc_jit_lvalue_as_rvalue (state->stack),
2427         gcc_jit_lvalue_as_rvalue (state->stack_depth))));
2431 @end example
2433 @noindent
2434 @end quotation
2436 We will support single-stepping through the generated code in the
2437 debugger, so we need to create @pxref{3b,,gcc_jit_location} instances, one
2438 per operation in the source code.  These will reference the lines of
2439 e.g. @code{factorial.toy}.
2441 @quotation
2443 @example
2444   for (pc = 0; pc < fn->fn_num_ops; pc++)
2445     @{
2446       toyvm_op *op = &fn->fn_ops[pc];
2448       state.op_locs[pc] = gcc_jit_context_new_location (state.ctxt,
2449                                                         fn->fn_filename,
2450                                                         op->op_linenum,
2451                                                         0); /* column */
2452     @}
2455 @end example
2457 @noindent
2458 @end quotation
2460 Let's create the function itself.  As usual, we create its parameter
2461 first, then use the parameter to create the function:
2463 @quotation
2465 @example
2466   state.param_arg =
2467     gcc_jit_context_new_param (state.ctxt, state.op_locs[0],
2468                                state.int_type, "arg");
2469   state.fn =
2470     gcc_jit_context_new_function (state.ctxt,
2471                                   state.op_locs[0],
2472                                   GCC_JIT_FUNCTION_EXPORTED,
2473                                   state.int_type,
2474                                   funcname,
2475                                   1, &state.param_arg, 0);
2478 @end example
2480 @noindent
2481 @end quotation
2483 We create the locals within the function.
2485 @quotation
2487 @example
2488   state.stack =
2489     gcc_jit_function_new_local (state.fn, NULL,
2490                                 state.stack_type, "stack");
2491   state.stack_depth =
2492     gcc_jit_function_new_local (state.fn, NULL,
2493                                 state.int_type, "stack_depth");
2494   state.x =
2495     gcc_jit_function_new_local (state.fn, NULL,
2496                                 state.int_type, "x");
2497   state.y =
2498     gcc_jit_function_new_local (state.fn, NULL,
2499                                 state.int_type, "y");
2502 @end example
2504 @noindent
2505 @end quotation
2507 @node Populating the function,Verifying the control flow graph,Setting things up,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2508 @anchor{intro/tutorial04 populating-the-function}@anchor{3c}
2509 @subsection Populating the function
2512 There's some one-time initialization, and the API treats the first block
2513 you create as the entrypoint of the function, so we need to create that
2514 block first:
2516 @quotation
2518 @example
2519   state.initial_block = gcc_jit_function_new_block (state.fn, "initial");
2522 @end example
2524 @noindent
2525 @end quotation
2527 We can now create blocks for each of the operations.  Most of these will
2528 be consolidated into larger blocks when the optimizer runs.
2530 @quotation
2532 @example
2533   for (pc = 0; pc < fn->fn_num_ops; pc++)
2534     @{
2535       char buf[16];
2536       sprintf (buf, "instr%i", pc);
2537       state.op_blocks[pc] = gcc_jit_function_new_block (state.fn, buf);
2538     @}
2541 @end example
2543 @noindent
2544 @end quotation
2546 Now that we have a block it can jump to when it's done, we can populate
2547 the initial block:
2549 @quotation
2551 @example
2553   /* "stack_depth = 0;".  */
2554   gcc_jit_block_add_assignment (
2555     state.initial_block,
2556     state.op_locs[0],
2557     state.stack_depth,
2558     gcc_jit_context_zero (state.ctxt, state.int_type));
2560   /* "PUSH (arg);".  */
2561   add_push (&state,
2562             state.initial_block,
2563             gcc_jit_param_as_rvalue (state.param_arg),
2564             state.op_locs[0]);
2566   /* ...and jump to insn 0.  */
2567   gcc_jit_block_end_with_jump (state.initial_block,
2568                                state.op_locs[0],
2569                                state.op_blocks[0]);
2572 @end example
2574 @noindent
2575 @end quotation
2577 We can now populate the blocks for the individual operations.  We loop
2578 through them, adding instructions to their blocks:
2580 @quotation
2582 @example
2583   for (pc = 0; pc < fn->fn_num_ops; pc++)
2584     @{
2585       gcc_jit_location *loc = state.op_locs[pc];
2587       gcc_jit_block *block = state.op_blocks[pc];
2588       gcc_jit_block *next_block = (pc < fn->fn_num_ops
2589                                    ? state.op_blocks[pc + 1]
2590                                    : NULL);
2592       toyvm_op *op;
2593       op = &fn->fn_ops[pc];
2596 @end example
2598 @noindent
2599 @end quotation
2601 We're going to have another big @code{switch} statement for implementing
2602 the opcodes, this time for compiling them, rather than interpreting
2603 them.  It's helpful to have macros for implementing push and pop, so that
2604 we can make the @code{switch} statement that's coming up look as much as
2605 possible like the one above within the interpreter:
2607 @example
2609 #define X_EQUALS_POP()\
2610       add_pop (&state, block, state.x, loc)
2611 #define Y_EQUALS_POP()\
2612       add_pop (&state, block, state.y, loc)
2613 #define PUSH_RVALUE(RVALUE)\
2614       add_push (&state, block, (RVALUE), loc)
2615 #define PUSH_X()\
2616       PUSH_RVALUE (gcc_jit_lvalue_as_rvalue (state.x))
2617 #define PUSH_Y() \
2618       PUSH_RVALUE (gcc_jit_lvalue_as_rvalue (state.y))
2621 @end example
2623 @noindent
2625 @cartouche
2626 @quotation Note 
2627 A particularly clever implementation would have an @emph{identical}
2628 @code{switch} statement shared by the interpreter and the compiler, with
2629 some preprocessor "magic".  We're not doing that here, for the sake
2630 of simplicity.
2631 @end quotation
2632 @end cartouche
2634 When I first implemented this compiler, I accidentally missed an edit
2635 when copying and pasting the @code{Y_EQUALS_POP} macro, so that popping the
2636 stack into @code{y} instead erroneously assigned it to @code{x}, leaving @code{y}
2637 uninitialized.
2639 To track this kind of thing down, we can use
2640 @pxref{3d,,gcc_jit_block_add_comment()} to add descriptive comments
2641 to the internal representation.  This is invaluable when looking through
2642 the generated IR for, say @code{factorial}:
2644 @quotation
2646 @example
2648       gcc_jit_block_add_comment (block, loc, opcode_names[op->op_opcode]);
2651 @end example
2653 @noindent
2654 @end quotation
2656 We can now write the big @code{switch} statement that implements the
2657 individual opcodes, populating the relevant block with statements:
2659 @quotation
2661 @example
2663       switch (op->op_opcode)
2664         @{
2665         case DUP:
2666           X_EQUALS_POP ();
2667           PUSH_X ();
2668           PUSH_X ();
2669           break;
2671         case ROT:
2672           Y_EQUALS_POP ();
2673           X_EQUALS_POP ();
2674           PUSH_Y ();
2675           PUSH_X ();
2676           break;
2678         case BINARY_ADD:
2679           Y_EQUALS_POP ();
2680           X_EQUALS_POP ();
2681           PUSH_RVALUE (
2682            gcc_jit_context_new_binary_op (
2683              state.ctxt,
2684              loc,
2685              GCC_JIT_BINARY_OP_PLUS,
2686              state.int_type,
2687              gcc_jit_lvalue_as_rvalue (state.x),
2688              gcc_jit_lvalue_as_rvalue (state.y)));
2689           break;
2691         case BINARY_SUBTRACT:
2692           Y_EQUALS_POP ();
2693           X_EQUALS_POP ();
2694           PUSH_RVALUE (
2695            gcc_jit_context_new_binary_op (
2696              state.ctxt,
2697              loc,
2698              GCC_JIT_BINARY_OP_MINUS,
2699              state.int_type,
2700              gcc_jit_lvalue_as_rvalue (state.x),
2701              gcc_jit_lvalue_as_rvalue (state.y)));
2702           break;
2704         case BINARY_MULT:
2705           Y_EQUALS_POP ();
2706           X_EQUALS_POP ();
2707           PUSH_RVALUE (
2708            gcc_jit_context_new_binary_op (
2709              state.ctxt,
2710              loc,
2711              GCC_JIT_BINARY_OP_MULT,
2712              state.int_type,
2713              gcc_jit_lvalue_as_rvalue (state.x),
2714              gcc_jit_lvalue_as_rvalue (state.y)));
2715           break;
2717         case BINARY_COMPARE_LT:
2718           Y_EQUALS_POP ();
2719           X_EQUALS_POP ();
2720           PUSH_RVALUE (
2721              /* cast of bool to int */
2722              gcc_jit_context_new_cast (
2723                state.ctxt,
2724                loc,
2725                /* (x < y) as a bool */
2726                gcc_jit_context_new_comparison (
2727                  state.ctxt,
2728                  loc,
2729                  GCC_JIT_COMPARISON_LT,
2730                  gcc_jit_lvalue_as_rvalue (state.x),
2731                  gcc_jit_lvalue_as_rvalue (state.y)),
2732                state.int_type));
2733           break;
2735         case RECURSE:
2736           @{
2737             X_EQUALS_POP ();
2738             gcc_jit_rvalue *arg = gcc_jit_lvalue_as_rvalue (state.x);
2739             PUSH_RVALUE (
2740               gcc_jit_context_new_call (
2741                 state.ctxt,
2742                 loc,
2743                 state.fn,
2744                 1, &arg));
2745             break;
2746           @}
2748         case RETURN:
2749           X_EQUALS_POP ();
2750           gcc_jit_block_end_with_return (
2751             block,
2752             loc,
2753             gcc_jit_lvalue_as_rvalue (state.x));
2754           break;
2756           /* Ops taking an operand.  */
2757         case PUSH_CONST:
2758           PUSH_RVALUE (
2759             gcc_jit_context_new_rvalue_from_int (
2760               state.ctxt,
2761               state.int_type,
2762               op->op_operand));
2763           break;
2765         case JUMP_ABS_IF_TRUE:
2766           X_EQUALS_POP ();
2767           gcc_jit_block_end_with_conditional (
2768             block,
2769             loc,
2770             /* "(bool)x".  */
2771             gcc_jit_context_new_cast (
2772               state.ctxt,
2773               loc,
2774               gcc_jit_lvalue_as_rvalue (state.x),
2775               state.bool_type),
2776             state.op_blocks[op->op_operand], /* on_true */
2777             next_block); /* on_false */
2778           break;
2780         default:
2781           assert(0);
2782         @} /* end of switch on opcode */
2785 @end example
2787 @noindent
2788 @end quotation
2790 Every block must be terminated, via a call to one of the
2791 @code{gcc_jit_block_end_with_} entrypoints.  This has been done for two
2792 of the opcodes, but we need to do it for the other ones, by jumping
2793 to the next block.
2795 @quotation
2797 @example
2798       if (op->op_opcode != JUMP_ABS_IF_TRUE
2799           && op->op_opcode != RETURN)
2800         gcc_jit_block_end_with_jump (
2801           block,
2802           loc,
2803           next_block);
2806 @end example
2808 @noindent
2809 @end quotation
2811 This is analogous to simply incrementing the program counter.
2813 @node Verifying the control flow graph,Compiling the context,Populating the function,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2814 @anchor{intro/tutorial04 verifying-the-control-flow-graph}@anchor{3e}
2815 @subsection Verifying the control flow graph
2818 Having finished looping over the blocks, the context is complete.
2820 As before, we can verify that the control flow and statements are sane by
2821 using @pxref{33,,gcc_jit_function_dump_to_dot()}:
2823 @example
2824 gcc_jit_function_dump_to_dot (state.fn, "/tmp/factorial.dot");
2825 @end example
2827 @noindent
2829 and viewing the result.  Note how the label names, comments, and
2830 variable names show up in the dump, to make it easier to spot
2831 errors in our compiler.
2833 @quotation
2836 @float Figure
2838 @image{factorial1,,,image of a control flow graph,png}
2840 @end float
2842 @end quotation
2844 @node Compiling the context,Single-stepping through the generated code,Verifying the control flow graph,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2845 @anchor{intro/tutorial04 compiling-the-context}@anchor{3f}
2846 @subsection Compiling the context
2849 Having finished looping over the blocks and populating them with
2850 statements, the context is complete.
2852 We can now compile it, and extract machine code from the result:
2854 @quotation
2856 @example
2857   gcc_jit_result *jit_result = gcc_jit_context_compile (state.ctxt);
2858   gcc_jit_context_release (state.ctxt);
2860   toyvm_compiled_function *toyvm_result =
2861     (toyvm_compiled_function *)calloc (1, sizeof (toyvm_compiled_function));
2862   if (!toyvm_result)
2863     @{
2864       fprintf (stderr, "out of memory allocating toyvm_compiled_function\n");
2865       gcc_jit_result_release (jit_result);
2866       return NULL;
2867     @}
2869   toyvm_result->cf_jit_result = jit_result;
2870   toyvm_result->cf_code =
2871     (toyvm_compiled_code)gcc_jit_result_get_code (jit_result,
2872                                                   funcname);
2874   free (funcname);
2876   return toyvm_result;
2879 char test[1024];
2881 #define CHECK_NON_NULL(PTR) \
2882   do @{                                       \
2883     if ((PTR) != NULL)                       \
2884       @{                                      \
2885         pass ("%s: %s is non-null", test, #PTR); \
2886       @}                                      \
2887     else                                     \
2888       @{                                      \
2889         fail ("%s: %s is NULL", test, #PTR); \
2890         abort ();                            \
2891     @}                                        \
2892   @} while (0)
2894 #define CHECK_VALUE(ACTUAL, EXPECTED) \
2895   do @{                                       \
2896     if ((ACTUAL) == (EXPECTED))              \
2897       @{                                      \
2898         pass ("%s: actual: %s == expected: %s", test, #ACTUAL, #EXPECTED); \
2899       @}                                      \
2900     else                                     \
2901       @{                                        \
2902         fail ("%s: actual: %s != expected: %s", test, #ACTUAL, #EXPECTED); \
2903         fprintf (stderr, "incorrect value\n"); \
2904         abort ();                              \
2905     @}                                        \
2906   @} while (0)
2908 static void
2909 test_script (const char *scripts_dir, const char *script_name, int input,
2910              int expected_result)
2912   char *script_path;
2913   toyvm_function *fn;
2914   int interpreted_result;
2915   toyvm_compiled_function *compiled_fn;
2916   toyvm_compiled_code code;
2917   int compiled_result;
2919   snprintf (test, sizeof (test), "toyvm.c: %s", script_name);
2921   script_path = (char *)malloc (strlen (scripts_dir)
2922                                 + strlen (script_name) + 1);
2923   CHECK_NON_NULL (script_path);
2924   sprintf (script_path, "%s%s", scripts_dir, script_name);
2926   fn = toyvm_function_parse (script_path, script_name);
2927   CHECK_NON_NULL (fn);
2929   interpreted_result = toyvm_function_interpret (fn, input, NULL);
2930   CHECK_VALUE (interpreted_result, expected_result);
2932   compiled_fn = toyvm_function_compile (fn);
2933   CHECK_NON_NULL (compiled_fn);
2935   code = (toyvm_compiled_code)compiled_fn->cf_code;
2936   CHECK_NON_NULL (code);
2938   compiled_result = code (input);
2939   CHECK_VALUE (compiled_result, expected_result);
2941   gcc_jit_result_release (compiled_fn->cf_jit_result);
2942   free (compiled_fn);
2943   free (fn);
2944   free (script_path);
2947 #define PATH_TO_SCRIPTS  ("/jit/docs/examples/tut04-toyvm/")
2949 static void
2950 test_suite (void)
2952   const char *srcdir;
2953   char *scripts_dir;
2955   snprintf (test, sizeof (test), "toyvm.c");
2957   /* We need to locate the test scripts.
2958      Rely on "srcdir" being set in the environment.  */
2960   srcdir = getenv ("srcdir");
2961   CHECK_NON_NULL (srcdir);
2963   scripts_dir = (char *)malloc (strlen (srcdir) + strlen(PATH_TO_SCRIPTS)
2964                                 + 1);
2965   CHECK_NON_NULL (scripts_dir);
2966   sprintf (scripts_dir, "%s%s", srcdir, PATH_TO_SCRIPTS);
2968   test_script (scripts_dir, "factorial.toy", 10, 3628800);
2969   test_script (scripts_dir, "fibonacci.toy", 10, 55);
2971   free (scripts_dir);
2975 main (int argc, char **argv)
2977   const char *filename = NULL;
2978   toyvm_function *fn = NULL;
2980   /* If called with no args, assume we're being run by the test suite.  */
2981   if (argc < 3)
2982     @{
2983       test_suite ();
2984       return 0;
2985     @}
2987   if (argc != 3)
2988     @{
2989       fprintf (stdout,
2990         "%s FILENAME INPUT: Parse and run a .toy file\n",
2991         argv[0]);
2992       exit (1);
2993     @}
2995   filename = argv[1];
2996   fn = toyvm_function_parse (filename, filename);
2997   if (!fn)
2998     exit (1);
3000   if (0)
3001     toyvm_function_disassemble (fn, stdout);
3003   printf ("interpreter result: %d\n",
3004           toyvm_function_interpret (fn, atoi (argv[2]), NULL));
3006   /* JIT-compilation.  */
3007   toyvm_compiled_function *compiled_fn
3008     = toyvm_function_compile (fn);
3010   toyvm_compiled_code code = compiled_fn->cf_code;
3011   printf ("compiler result: %d\n",
3012           code (atoi (argv[2])));
3014   gcc_jit_result_release (compiled_fn->cf_jit_result);
3015   free (compiled_fn);
3017  return 0;
3020 @end example
3022 @noindent
3023 @end quotation
3025 We can now run the result:
3027 @quotation
3029 @example
3030   toyvm_compiled_function *compiled_fn
3031     = toyvm_function_compile (fn);
3033   toyvm_compiled_code code = compiled_fn->cf_code;
3034   printf ("compiler result: %d\n",
3035           code (atoi (argv[2])));
3037   gcc_jit_result_release (compiled_fn->cf_jit_result);
3038   free (compiled_fn);
3041 @end example
3043 @noindent
3044 @end quotation
3046 @node Single-stepping through the generated code,Examining the generated code,Compiling the context,Tutorial part 4 Adding JIT-compilation to a toy interpreter
3047 @anchor{intro/tutorial04 single-stepping-through-the-generated-code}@anchor{40}
3048 @subsection Single-stepping through the generated code
3051 It's possible to debug the generated code.  To do this we need to both:
3053 @quotation
3056 @itemize *
3058 @item 
3059 Set up source code locations for our statements, so that we can
3060 meaningfully step through the code.  We did this above by
3061 calling @pxref{41,,gcc_jit_context_new_location()} and using the
3062 results.
3064 @item 
3065 Enable the generation of debugging information, by setting
3066 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} on the
3067 @pxref{8,,gcc_jit_context} via
3068 @pxref{1b,,gcc_jit_context_set_bool_option()}:
3070 @example
3071 gcc_jit_context_set_bool_option (
3072   ctxt,
3073   GCC_JIT_BOOL_OPTION_DEBUGINFO,
3074   1);
3075 @end example
3077 @noindent
3078 @end itemize
3079 @end quotation
3081 Having done this, we can put a breakpoint on the generated function:
3083 @example
3084 $ gdb --args ./toyvm factorial.toy 10
3085 (gdb) break factorial
3086 Function "factorial" not defined.
3087 Make breakpoint pending on future shared library load? (y or [n]) y
3088 Breakpoint 1 (factorial) pending.
3089 (gdb) run
3090 Breakpoint 1, factorial (arg=10) at factorial.toy:14
3091 14    DUP
3092 @end example
3094 @noindent
3096 We've set up location information, which references @code{factorial.toy}.
3097 This allows us to use e.g. @code{list} to see where we are in the script:
3099 @example
3100 (gdb) list
3102 10    # Initial state:
3103 11    # stack: [arg]
3105 13    # 0:
3106 14    DUP
3107 15    # stack: [arg, arg]
3109 17    # 1:
3110 18    PUSH_CONST 2
3111 @end example
3113 @noindent
3115 and to step through the function, examining the data:
3117 @example
3118 (gdb) n
3119 18    PUSH_CONST 2
3120 (gdb) n
3121 22    BINARY_COMPARE_LT
3122 (gdb) print stack
3123 $5 = @{10, 10, 2, 0, -7152, 32767, 0, 0@}
3124 (gdb) print stack_depth
3125 $6 = 3
3126 @end example
3128 @noindent
3130 You'll see that the parts of the @code{stack} array that haven't been
3131 touched yet are uninitialized.
3133 @cartouche
3134 @quotation Note 
3135 Turning on optimizations may lead to unpredictable results when
3136 stepping through the generated code: the execution may appear to
3137 "jump around" the source code.  This is analogous to turning up the
3138 optimization level in a regular compiler.
3139 @end quotation
3140 @end cartouche
3142 @node Examining the generated code,Putting it all together,Single-stepping through the generated code,Tutorial part 4 Adding JIT-compilation to a toy interpreter
3143 @anchor{intro/tutorial04 examining-the-generated-code}@anchor{43}
3144 @subsection Examining the generated code
3147 How good is the optimized code?
3149 We can turn up optimizations, by calling
3150 @pxref{1e,,gcc_jit_context_set_int_option()} with
3151 @pxref{1f,,GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}:
3153 @example
3154 gcc_jit_context_set_int_option (
3155   ctxt,
3156   GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL,
3157   3);
3158 @end example
3160 @noindent
3162 One of GCC's internal representations is called "gimple".  A dump of the
3163 initial gimple representation of the code can be seen by setting:
3165 @example
3166 gcc_jit_context_set_bool_option (ctxt,
3167                                  GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE,
3168                                  1);
3169 @end example
3171 @noindent
3173 With optimization on and source locations displayed, this gives:
3175 @c We'll use "c" for gimple dumps
3177 @example
3178 factorial (signed int arg)
3180   <unnamed type> D.80;
3181   signed int D.81;
3182   signed int D.82;
3183   signed int D.83;
3184   signed int D.84;
3185   signed int D.85;
3186   signed int y;
3187   signed int x;
3188   signed int stack_depth;
3189   signed int stack[8];
3191   try
3192     @{
3193       initial:
3194       stack_depth = 0;
3195       stack[stack_depth] = arg;
3196       stack_depth = stack_depth + 1;
3197       goto instr0;
3198       instr0:
3199       /* DUP */:
3200       stack_depth = stack_depth + -1;
3201       x = stack[stack_depth];
3202       stack[stack_depth] = x;
3203       stack_depth = stack_depth + 1;
3204       stack[stack_depth] = x;
3205       stack_depth = stack_depth + 1;
3206       goto instr1;
3207       instr1:
3208       /* PUSH_CONST */:
3209       stack[stack_depth] = 2;
3210       stack_depth = stack_depth + 1;
3211       goto instr2;
3213       /* etc */
3214 @end example
3216 @noindent
3218 You can see the generated machine code in assembly form via:
3220 @example
3221 gcc_jit_context_set_bool_option (
3222   ctxt,
3223   GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
3224   1);
3225 result = gcc_jit_context_compile (ctxt);
3226 @end example
3228 @noindent
3230 which shows that (on this x86_64 box) the compiler has unrolled the loop
3231 and is using MMX instructions to perform several multiplications
3232 simultaneously:
3234 @example
3235         .file   "fake.c"
3236         .text
3237 .Ltext0:
3238         .p2align 4,,15
3239         .globl  factorial
3240         .type   factorial, @@function
3241 factorial:
3242 .LFB0:
3243         .file 1 "factorial.toy"
3244         .loc 1 14 0
3245         .cfi_startproc
3246 .LVL0:
3247 .L2:
3248         .loc 1 26 0
3249         cmpl    $1, %edi
3250         jle     .L13
3251         leal    -1(%rdi), %edx
3252         movl    %edx, %ecx
3253         shrl    $2, %ecx
3254         leal    0(,%rcx,4), %esi
3255         testl   %esi, %esi
3256         je      .L14
3257         cmpl    $9, %edx
3258         jbe     .L14
3259         leal    -2(%rdi), %eax
3260         movl    %eax, -16(%rsp)
3261         leal    -3(%rdi), %eax
3262         movd    -16(%rsp), %xmm0
3263         movl    %edi, -16(%rsp)
3264         movl    %eax, -12(%rsp)
3265         movd    -16(%rsp), %xmm1
3266         xorl    %eax, %eax
3267         movl    %edx, -16(%rsp)
3268         movd    -12(%rsp), %xmm4
3269         movd    -16(%rsp), %xmm6
3270         punpckldq       %xmm4, %xmm0
3271         movdqa  .LC1(%rip), %xmm4
3272         punpckldq       %xmm6, %xmm1
3273         punpcklqdq      %xmm0, %xmm1
3274         movdqa  .LC0(%rip), %xmm0
3275         jmp     .L5
3276         # etc - edited for brevity
3277 @end example
3279 @noindent
3281 This is clearly overkill for a function that will likely overflow the
3282 @code{int} type before the vectorization is worthwhile - but then again, this
3283 is a toy example.
3285 Turning down the optimization level to 2:
3287 @example
3288 gcc_jit_context_set_int_option (
3289   ctxt,
3290   GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL,
3291   3);
3292 @end example
3294 @noindent
3296 yields this code, which is simple enough to quote in its entirety:
3298 @example
3299         .file   "fake.c"
3300         .text
3301         .p2align 4,,15
3302         .globl  factorial
3303         .type   factorial, @@function
3304 factorial:
3305 .LFB0:
3306         .cfi_startproc
3307 .L2:
3308         cmpl    $1, %edi
3309         jle     .L8
3310         movl    $1, %edx
3311         jmp     .L4
3312         .p2align 4,,10
3313         .p2align 3
3314 .L6:
3315         movl    %eax, %edi
3316 .L4:
3317 .L5:
3318         leal    -1(%rdi), %eax
3319         imull   %edi, %edx
3320         cmpl    $1, %eax
3321         jne     .L6
3322 .L3:
3323 .L7:
3324         imull   %edx, %eax
3325         ret
3326 .L8:
3327         movl    %edi, %eax
3328         movl    $1, %edx
3329         jmp     .L7
3330         .cfi_endproc
3331 .LFE0:
3332         .size   factorial, .-factorial
3333         .ident  "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-%@{gcc_release@})"
3334         .section        .note.GNU-stack,"",@@progbits
3335 @end example
3337 @noindent
3339 Note that the stack pushing and popping have been eliminated, as has the
3340 recursive call (in favor of an iteration).
3342 @node Putting it all together,Behind the curtain How does our code get optimized?,Examining the generated code,Tutorial part 4 Adding JIT-compilation to a toy interpreter
3343 @anchor{intro/tutorial04 putting-it-all-together}@anchor{44}
3344 @subsection Putting it all together
3347 The complete example can be seen in the source tree at
3348 @code{gcc/jit/docs/examples/tut04-toyvm/toyvm.c}
3350 along with a Makefile and a couple of sample .toy scripts:
3352 @example
3353 $ ls -al
3354 drwxrwxr-x. 2 david david   4096 Sep 19 17:46 .
3355 drwxrwxr-x. 3 david david   4096 Sep 19 15:26 ..
3356 -rw-rw-r--. 1 david david    615 Sep 19 12:43 factorial.toy
3357 -rw-rw-r--. 1 david david    834 Sep 19 13:08 fibonacci.toy
3358 -rw-rw-r--. 1 david david    238 Sep 19 14:22 Makefile
3359 -rw-rw-r--. 1 david david  16457 Sep 19 17:07 toyvm.c
3361 $ make toyvm
3362 g++ -Wall -g -o toyvm toyvm.c -lgccjit
3364 $ ./toyvm factorial.toy 10
3365 interpreter result: 3628800
3366 compiler result: 3628800
3368 $ ./toyvm fibonacci.toy 10
3369 interpreter result: 55
3370 compiler result: 55
3371 @end example
3373 @noindent
3375 @node Behind the curtain How does our code get optimized?,,Putting it all together,Tutorial part 4 Adding JIT-compilation to a toy interpreter
3376 @anchor{intro/tutorial04 behind-the-curtain-how-does-our-code-get-optimized}@anchor{45}
3377 @subsection Behind the curtain: How does our code get optimized?
3380 Our example is done, but you may be wondering about exactly how the
3381 compiler turned what we gave it into the machine code seen above.
3383 We can examine what the compiler is doing in detail by setting:
3385 @example
3386 gcc_jit_context_set_bool_option (state.ctxt,
3387                                  GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING,
3388                                  1);
3389 gcc_jit_context_set_bool_option (state.ctxt,
3390                                  GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES,
3391                                  1);
3392 @end example
3394 @noindent
3396 This will dump detailed information about the compiler's state to a
3397 directory under @code{/tmp}, and keep it from being cleaned up.
3399 The precise names and their formats of these files is subject to change.
3400 Higher optimization levels lead to more files.
3401 Here's what I saw (edited for brevity; there were almost 200 files):
3403 @example
3404 intermediate files written to /tmp/libgccjit-KPQbGw
3405 $ ls /tmp/libgccjit-KPQbGw/
3406 fake.c.000i.cgraph
3407 fake.c.000i.type-inheritance
3408 fake.c.004t.gimple
3409 fake.c.007t.omplower
3410 fake.c.008t.lower
3411 fake.c.011t.eh
3412 fake.c.012t.cfg
3413 fake.c.014i.visibility
3414 fake.c.015i.early_local_cleanups
3415 fake.c.016t.ssa
3416 # etc
3417 @end example
3419 @noindent
3421 The gimple code is converted into Static Single Assignment form,
3422 with annotations for use when generating the debuginfo:
3424 @example
3425 $ less /tmp/libgccjit-KPQbGw/fake.c.016t.ssa
3426 @end example
3428 @noindent
3430 @example
3431 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3433 factorial (signed int arg)
3435   signed int stack[8];
3436   signed int stack_depth;
3437   signed int x;
3438   signed int y;
3439   <unnamed type> _20;
3440   signed int _21;
3441   signed int _38;
3442   signed int _44;
3443   signed int _51;
3444   signed int _56;
3446 initial:
3447   stack_depth_3 = 0;
3448   # DEBUG stack_depth => stack_depth_3
3449   stack[stack_depth_3] = arg_5(D);
3450   stack_depth_7 = stack_depth_3 + 1;
3451   # DEBUG stack_depth => stack_depth_7
3452   # DEBUG instr0 => NULL
3453   # DEBUG /* DUP */ => NULL
3454   stack_depth_8 = stack_depth_7 + -1;
3455   # DEBUG stack_depth => stack_depth_8
3456   x_9 = stack[stack_depth_8];
3457   # DEBUG x => x_9
3458   stack[stack_depth_8] = x_9;
3459   stack_depth_11 = stack_depth_8 + 1;
3460   # DEBUG stack_depth => stack_depth_11
3461   stack[stack_depth_11] = x_9;
3462   stack_depth_13 = stack_depth_11 + 1;
3463   # DEBUG stack_depth => stack_depth_13
3464   # DEBUG instr1 => NULL
3465   # DEBUG /* PUSH_CONST */ => NULL
3466   stack[stack_depth_13] = 2;
3468   /* etc; edited for brevity */
3469 @end example
3471 @noindent
3473 We can perhaps better see the code by turning off
3474 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} to suppress all those @code{DEBUG}
3475 statements, giving:
3477 @example
3478 $ less /tmp/libgccjit-1Hywc0/fake.c.016t.ssa
3479 @end example
3481 @noindent
3483 @example
3484 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3486 factorial (signed int arg)
3488   signed int stack[8];
3489   signed int stack_depth;
3490   signed int x;
3491   signed int y;
3492   <unnamed type> _20;
3493   signed int _21;
3494   signed int _38;
3495   signed int _44;
3496   signed int _51;
3497   signed int _56;
3499 initial:
3500   stack_depth_3 = 0;
3501   stack[stack_depth_3] = arg_5(D);
3502   stack_depth_7 = stack_depth_3 + 1;
3503   stack_depth_8 = stack_depth_7 + -1;
3504   x_9 = stack[stack_depth_8];
3505   stack[stack_depth_8] = x_9;
3506   stack_depth_11 = stack_depth_8 + 1;
3507   stack[stack_depth_11] = x_9;
3508   stack_depth_13 = stack_depth_11 + 1;
3509   stack[stack_depth_13] = 2;
3510   stack_depth_15 = stack_depth_13 + 1;
3511   stack_depth_16 = stack_depth_15 + -1;
3512   y_17 = stack[stack_depth_16];
3513   stack_depth_18 = stack_depth_16 + -1;
3514   x_19 = stack[stack_depth_18];
3515   _20 = x_19 < y_17;
3516   _21 = (signed int) _20;
3517   stack[stack_depth_18] = _21;
3518   stack_depth_23 = stack_depth_18 + 1;
3519   stack_depth_24 = stack_depth_23 + -1;
3520   x_25 = stack[stack_depth_24];
3521   if (x_25 != 0)
3522     goto <bb 4> (instr9);
3523   else
3524     goto <bb 3> (instr4);
3526 instr4:
3527 /* DUP */:
3528   stack_depth_26 = stack_depth_24 + -1;
3529   x_27 = stack[stack_depth_26];
3530   stack[stack_depth_26] = x_27;
3531   stack_depth_29 = stack_depth_26 + 1;
3532   stack[stack_depth_29] = x_27;
3533   stack_depth_31 = stack_depth_29 + 1;
3534   stack[stack_depth_31] = 1;
3535   stack_depth_33 = stack_depth_31 + 1;
3536   stack_depth_34 = stack_depth_33 + -1;
3537   y_35 = stack[stack_depth_34];
3538   stack_depth_36 = stack_depth_34 + -1;
3539   x_37 = stack[stack_depth_36];
3540   _38 = x_37 - y_35;
3541   stack[stack_depth_36] = _38;
3542   stack_depth_40 = stack_depth_36 + 1;
3543   stack_depth_41 = stack_depth_40 + -1;
3544   x_42 = stack[stack_depth_41];
3545   _44 = factorial (x_42);
3546   stack[stack_depth_41] = _44;
3547   stack_depth_46 = stack_depth_41 + 1;
3548   stack_depth_47 = stack_depth_46 + -1;
3549   y_48 = stack[stack_depth_47];
3550   stack_depth_49 = stack_depth_47 + -1;
3551   x_50 = stack[stack_depth_49];
3552   _51 = x_50 * y_48;
3553   stack[stack_depth_49] = _51;
3554   stack_depth_53 = stack_depth_49 + 1;
3556   # stack_depth_1 = PHI <stack_depth_24(2), stack_depth_53(3)>
3557 instr9:
3558 /* RETURN */:
3559   stack_depth_54 = stack_depth_1 + -1;
3560   x_55 = stack[stack_depth_54];
3561   _56 = x_55;
3562   stack =@{v@} @{CLOBBER@};
3563   return _56;
3566 @end example
3568 @noindent
3570 Note in the above how all the @pxref{28,,gcc_jit_block} instances we
3571 created have been consolidated into just 3 blocks in GCC's internal
3572 representation: @code{initial}, @code{instr4} and @code{instr9}.
3574 @menu
3575 * Optimizing away stack manipulation:: 
3576 * Elimination of tail recursion:: 
3578 @end menu
3580 @node Optimizing away stack manipulation,Elimination of tail recursion,,Behind the curtain How does our code get optimized?
3581 @anchor{intro/tutorial04 optimizing-away-stack-manipulation}@anchor{46}
3582 @subsubsection Optimizing away stack manipulation
3585 Recall our simple implementation of stack operations.  Let's examine
3586 how the stack operations are optimized away.
3588 After a pass of constant-propagation, the depth of the stack at each
3589 opcode can be determined at compile-time:
3591 @example
3592 $ less /tmp/libgccjit-1Hywc0/fake.c.021t.ccp1
3593 @end example
3595 @noindent
3597 @example
3598 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3600 factorial (signed int arg)
3602   signed int stack[8];
3603   signed int stack_depth;
3604   signed int x;
3605   signed int y;
3606   <unnamed type> _20;
3607   signed int _21;
3608   signed int _38;
3609   signed int _44;
3610   signed int _51;
3612 initial:
3613   stack[0] = arg_5(D);
3614   x_9 = stack[0];
3615   stack[0] = x_9;
3616   stack[1] = x_9;
3617   stack[2] = 2;
3618   y_17 = stack[2];
3619   x_19 = stack[1];
3620   _20 = x_19 < y_17;
3621   _21 = (signed int) _20;
3622   stack[1] = _21;
3623   x_25 = stack[1];
3624   if (x_25 != 0)
3625     goto <bb 4> (instr9);
3626   else
3627     goto <bb 3> (instr4);
3629 instr4:
3630 /* DUP */:
3631   x_27 = stack[0];
3632   stack[0] = x_27;
3633   stack[1] = x_27;
3634   stack[2] = 1;
3635   y_35 = stack[2];
3636   x_37 = stack[1];
3637   _38 = x_37 - y_35;
3638   stack[1] = _38;
3639   x_42 = stack[1];
3640   _44 = factorial (x_42);
3641   stack[1] = _44;
3642   y_48 = stack[1];
3643   x_50 = stack[0];
3644   _51 = x_50 * y_48;
3645   stack[0] = _51;
3647 instr9:
3648 /* RETURN */:
3649   x_55 = stack[0];
3650   x_56 = x_55;
3651   stack =@{v@} @{CLOBBER@};
3652   return x_56;
3655 @end example
3657 @noindent
3659 Note how, in the above, all those @code{stack_depth} values are now just
3660 constants: we're accessing specific stack locations at each opcode.
3662 The "esra" pass ("Early Scalar Replacement of Aggregates") breaks
3663 out our "stack" array into individual elements:
3665 @example
3666 $ less /tmp/libgccjit-1Hywc0/fake.c.024t.esra
3667 @end example
3669 @noindent
3671 @example
3672 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3674 Created a replacement for stack offset: 0, size: 32: stack$0
3675 Created a replacement for stack offset: 32, size: 32: stack$1
3676 Created a replacement for stack offset: 64, size: 32: stack$2
3678 Symbols to be put in SSA form
3679 @{ D.89 D.90 D.91 @}
3680 Incremental SSA update started at block: 0
3681 Number of blocks in CFG: 5
3682 Number of blocks to update: 4 ( 80%)
3685 factorial (signed int arg)
3687   signed int stack$2;
3688   signed int stack$1;
3689   signed int stack$0;
3690   signed int stack[8];
3691   signed int stack_depth;
3692   signed int x;
3693   signed int y;
3694   <unnamed type> _20;
3695   signed int _21;
3696   signed int _38;
3697   signed int _44;
3698   signed int _51;
3700 initial:
3701   stack$0_45 = arg_5(D);
3702   x_9 = stack$0_45;
3703   stack$0_39 = x_9;
3704   stack$1_32 = x_9;
3705   stack$2_30 = 2;
3706   y_17 = stack$2_30;
3707   x_19 = stack$1_32;
3708   _20 = x_19 < y_17;
3709   _21 = (signed int) _20;
3710   stack$1_28 = _21;
3711   x_25 = stack$1_28;
3712   if (x_25 != 0)
3713     goto <bb 4> (instr9);
3714   else
3715     goto <bb 3> (instr4);
3717 instr4:
3718 /* DUP */:
3719   x_27 = stack$0_39;
3720   stack$0_22 = x_27;
3721   stack$1_14 = x_27;
3722   stack$2_12 = 1;
3723   y_35 = stack$2_12;
3724   x_37 = stack$1_14;
3725   _38 = x_37 - y_35;
3726   stack$1_10 = _38;
3727   x_42 = stack$1_10;
3728   _44 = factorial (x_42);
3729   stack$1_6 = _44;
3730   y_48 = stack$1_6;
3731   x_50 = stack$0_22;
3732   _51 = x_50 * y_48;
3733   stack$0_1 = _51;
3735   # stack$0_52 = PHI <stack$0_39(2), stack$0_1(3)>
3736 instr9:
3737 /* RETURN */:
3738   x_55 = stack$0_52;
3739   x_56 = x_55;
3740   stack =@{v@} @{CLOBBER@};
3741   return x_56;
3744 @end example
3746 @noindent
3748 Hence at this point, all those pushes and pops of the stack are now
3749 simply assignments to specific temporary variables.
3751 After some copy propagation, the stack manipulation has been completely
3752 optimized away:
3754 @example
3755 $ less /tmp/libgccjit-1Hywc0/fake.c.026t.copyprop1
3756 @end example
3758 @noindent
3760 @example
3761 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3763 factorial (signed int arg)
3765   signed int stack$2;
3766   signed int stack$1;
3767   signed int stack$0;
3768   signed int stack[8];
3769   signed int stack_depth;
3770   signed int x;
3771   signed int y;
3772   <unnamed type> _20;
3773   signed int _21;
3774   signed int _38;
3775   signed int _44;
3776   signed int _51;
3778 initial:
3779   stack$0_39 = arg_5(D);
3780   _20 = arg_5(D) <= 1;
3781   _21 = (signed int) _20;
3782   if (_21 != 0)
3783     goto <bb 4> (instr9);
3784   else
3785     goto <bb 3> (instr4);
3787 instr4:
3788 /* DUP */:
3789   _38 = arg_5(D) + -1;
3790   _44 = factorial (_38);
3791   _51 = arg_5(D) * _44;
3792   stack$0_1 = _51;
3794   # stack$0_52 = PHI <arg_5(D)(2), _51(3)>
3795 instr9:
3796 /* RETURN */:
3797   stack =@{v@} @{CLOBBER@};
3798   return stack$0_52;
3801 @end example
3803 @noindent
3805 Later on, another pass finally eliminated @code{stack_depth} local and the
3806 unused parts of the @cite{stack`} array altogether:
3808 @example
3809 $ less /tmp/libgccjit-1Hywc0/fake.c.036t.release_ssa
3810 @end example
3812 @noindent
3814 @example
3815 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3817 Released 44 names, 314.29%, removed 44 holes
3818 factorial (signed int arg)
3820   signed int stack$0;
3821   signed int mult_acc_1;
3822   <unnamed type> _5;
3823   signed int _6;
3824   signed int _7;
3825   signed int mul_tmp_10;
3826   signed int mult_acc_11;
3827   signed int mult_acc_13;
3829   # arg_9 = PHI <arg_8(D)(0)>
3830   # mult_acc_13 = PHI <1(0)>
3831 initial:
3833   <bb 5>:
3834   # arg_4 = PHI <arg_9(2), _7(3)>
3835   # mult_acc_1 = PHI <mult_acc_13(2), mult_acc_11(3)>
3836   _5 = arg_4 <= 1;
3837   _6 = (signed int) _5;
3838   if (_6 != 0)
3839     goto <bb 4> (instr9);
3840   else
3841     goto <bb 3> (instr4);
3843 instr4:
3844 /* DUP */:
3845   _7 = arg_4 + -1;
3846   mult_acc_11 = mult_acc_1 * arg_4;
3847   goto <bb 5>;
3849   # stack$0_12 = PHI <arg_4(5)>
3850 instr9:
3851 /* RETURN */:
3852   mul_tmp_10 = mult_acc_1 * stack$0_12;
3853   return mul_tmp_10;
3856 @end example
3858 @noindent
3860 @node Elimination of tail recursion,,Optimizing away stack manipulation,Behind the curtain How does our code get optimized?
3861 @anchor{intro/tutorial04 elimination-of-tail-recursion}@anchor{47}
3862 @subsubsection Elimination of tail recursion
3865 Another significant optimization is the detection that the call to
3866 @code{factorial} is tail recursion, which can be eliminated in favor of
3867 an iteration:
3869 @example
3870 $ less /tmp/libgccjit-1Hywc0/fake.c.030t.tailr1
3871 @end example
3873 @noindent
3875 @example
3876 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3879 Symbols to be put in SSA form
3880 @{ D.88 @}
3881 Incremental SSA update started at block: 0
3882 Number of blocks in CFG: 5
3883 Number of blocks to update: 4 ( 80%)
3886 factorial (signed int arg)
3888   signed int stack$2;
3889   signed int stack$1;
3890   signed int stack$0;
3891   signed int stack[8];
3892   signed int stack_depth;
3893   signed int x;
3894   signed int y;
3895   signed int mult_acc_1;
3896   <unnamed type> _20;
3897   signed int _21;
3898   signed int _38;
3899   signed int mul_tmp_44;
3900   signed int mult_acc_51;
3902   # arg_5 = PHI <arg_39(D)(0), _38(3)>
3903   # mult_acc_1 = PHI <1(0), mult_acc_51(3)>
3904 initial:
3905   _20 = arg_5 <= 1;
3906   _21 = (signed int) _20;
3907   if (_21 != 0)
3908     goto <bb 4> (instr9);
3909   else
3910     goto <bb 3> (instr4);
3912 instr4:
3913 /* DUP */:
3914   _38 = arg_5 + -1;
3915   mult_acc_51 = mult_acc_1 * arg_5;
3916   goto <bb 2> (initial);
3918   # stack$0_52 = PHI <arg_5(2)>
3919 instr9:
3920 /* RETURN */:
3921   stack =@{v@} @{CLOBBER@};
3922   mul_tmp_44 = mult_acc_1 * stack$0_52;
3923   return mul_tmp_44;
3926 @end example
3928 @noindent
3930 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
3931 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
3932 @c 
3933 @c This is free software: you can redistribute it and/or modify it
3934 @c under the terms of the GNU General Public License as published by
3935 @c the Free Software Foundation, either version 3 of the License, or
3936 @c (at your option) any later version.
3937 @c 
3938 @c This program is distributed in the hope that it will be useful, but
3939 @c WITHOUT ANY WARRANTY; without even the implied warranty of
3940 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
3941 @c General Public License for more details.
3942 @c 
3943 @c You should have received a copy of the GNU General Public License
3944 @c along with this program.  If not, see
3945 @c <http://www.gnu.org/licenses/>.
3947 @node Topic Reference,C++ bindings for libgccjit,Tutorial,Top
3948 @anchor{topics/index doc}@anchor{48}@anchor{topics/index topic-reference}@anchor{49}
3949 @chapter Topic Reference
3952 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
3953 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
3954 @c 
3955 @c This is free software: you can redistribute it and/or modify it
3956 @c under the terms of the GNU General Public License as published by
3957 @c the Free Software Foundation, either version 3 of the License, or
3958 @c (at your option) any later version.
3959 @c 
3960 @c This program is distributed in the hope that it will be useful, but
3961 @c WITHOUT ANY WARRANTY; without even the implied warranty of
3962 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
3963 @c General Public License for more details.
3964 @c 
3965 @c You should have received a copy of the GNU General Public License
3966 @c along with this program.  If not, see
3967 @c <http://www.gnu.org/licenses/>.
3969 @menu
3970 * Compilation contexts:: 
3971 * Objects:: 
3972 * Types:: 
3973 * Expressions:: 
3974 * Creating and using functions:: 
3975 * Source Locations:: 
3976 * Compilation results:: 
3978 Compilation contexts
3980 * Lifetime-management:: 
3981 * Thread-safety:: 
3982 * Error-handling: Error-handling<2>. 
3983 * Debugging:: 
3984 * Options: Options<2>. 
3986 Options
3988 * String Options:: 
3989 * Boolean options:: 
3990 * Integer options:: 
3992 Types
3994 * Standard types:: 
3995 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile. 
3996 * Structures and unions:: 
3998 Expressions
4000 * Rvalues:: 
4001 * Lvalues:: 
4002 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions. 
4004 Rvalues
4006 * Simple expressions:: 
4007 * Unary Operations:: 
4008 * Binary Operations:: 
4009 * Comparisons:: 
4010 * Function calls:: 
4011 * Type-coercion:: 
4013 Lvalues
4015 * Global variables:: 
4017 Creating and using functions
4019 * Params:: 
4020 * Functions:: 
4021 * Blocks:: 
4022 * Statements:: 
4024 Source Locations
4026 * Faking it:: 
4028 @end menu
4031 @node Compilation contexts,Objects,,Topic Reference
4032 @anchor{topics/contexts compilation-contexts}@anchor{4a}@anchor{topics/contexts doc}@anchor{4b}
4033 @section Compilation contexts
4036 @geindex gcc_jit_context (C type)
4037 @anchor{topics/contexts gcc_jit_context}@anchor{8}
4038 @deffn {C Type} gcc_jit_context
4039 @end deffn
4041 The top-level of the API is the @pxref{8,,gcc_jit_context} type.
4043 A @pxref{8,,gcc_jit_context} instance encapsulates the state of a
4044 compilation.
4046 You can set up options on it, and add types, functions and code.
4047 Invoking @pxref{15,,gcc_jit_context_compile()} on it gives you a
4048 @pxref{16,,gcc_jit_result}.
4050 @menu
4051 * Lifetime-management:: 
4052 * Thread-safety:: 
4053 * Error-handling: Error-handling<2>. 
4054 * Debugging:: 
4055 * Options: Options<2>. 
4057 @end menu
4059 @node Lifetime-management,Thread-safety,,Compilation contexts
4060 @anchor{topics/contexts lifetime-management}@anchor{4c}
4061 @subsection Lifetime-management
4064 Contexts are the unit of lifetime-management within the API: objects
4065 have their lifetime bounded by the context they are created within, and
4066 cleanup of such objects is done for you when the context is released.
4068 @geindex gcc_jit_context_acquire (C function)
4069 @anchor{topics/contexts gcc_jit_context_acquire}@anchor{9}
4070 @deffn {C Function} gcc_jit_context *gcc_jit_context_acquire (void)
4072 This function acquires a new @pxref{e,,gcc_jit_object *} instance,
4073 which is independent of any others that may be present within this
4074 process.
4075 @end deffn
4077 @geindex gcc_jit_context_release (C function)
4078 @anchor{topics/contexts gcc_jit_context_release}@anchor{c}
4079 @deffn {C Function} void gcc_jit_context_release (gcc_jit_context@w{ }*ctxt)
4081 This function releases all resources associated with the given context.
4082 Both the context itself and all of its @pxref{e,,gcc_jit_object *}
4083 instances are cleaned up.  It should be called exactly once on a given
4084 context.
4086 It is invalid to use the context or any of its "contextual" objects
4087 after calling this.
4089 @example
4090 gcc_jit_context_release (ctxt);
4091 @end example
4093 @noindent
4094 @end deffn
4096 @geindex gcc_jit_context_new_child_context (C function)
4097 @anchor{topics/contexts gcc_jit_context_new_child_context}@anchor{4d}
4098 @deffn {C Function} gcc_jit_context * gcc_jit_context_new_child_context (gcc_jit_context@w{ }*parent_ctxt)
4100 Given an existing JIT context, create a child context.
4102 The child inherits a copy of all option-settings from the parent.
4104 The child can reference objects created within the parent, but not
4105 vice-versa.
4107 The lifetime of the child context must be bounded by that of the
4108 parent: you should release a child context before releasing the parent
4109 context.
4111 If you use a function from a parent context within a child context,
4112 you have to compile the parent context before you can compile the
4113 child context, and the gcc_jit_result of the parent context must
4114 outlive the gcc_jit_result of the child context.
4116 This allows caching of shared initializations.  For example, you could
4117 create types and declarations of global functions in a parent context
4118 once within a process, and then create child contexts whenever a
4119 function or loop becomes hot. Each such child context can be used for
4120 JIT-compiling just one function or loop, but can reference types
4121 and helper functions created within the parent context.
4123 Contexts can be arbitrarily nested, provided the above rules are
4124 followed, but it's probably not worth going above 2 or 3 levels, and
4125 there will likely be a performance hit for such nesting.
4126 @end deffn
4128 @node Thread-safety,Error-handling<2>,Lifetime-management,Compilation contexts
4129 @anchor{topics/contexts thread-safety}@anchor{4e}
4130 @subsection Thread-safety
4133 Instances of @pxref{8,,gcc_jit_context *} created via
4134 @pxref{9,,gcc_jit_context_acquire()} are independent from each other:
4135 only one thread may use a given context at once, but multiple threads
4136 could each have their own contexts without needing locks.
4138 Contexts created via @pxref{4d,,gcc_jit_context_new_child_context()} are
4139 related to their parent context.  They can be partitioned by their
4140 ultimate ancestor into independent "family trees".   Only one thread
4141 within a process may use a given "family tree" of such contexts at once,
4142 and if you're using multiple threads you should provide your own locking
4143 around entire such context partitions.
4145 @node Error-handling<2>,Debugging,Thread-safety,Compilation contexts
4146 @anchor{topics/contexts error-handling}@anchor{19}@anchor{topics/contexts id1}@anchor{4f}
4147 @subsection Error-handling
4150 Various kinds of errors are possible when using the API, such as
4151 mismatched types in an assignment.  You can only compile and get code from
4152 a context if no errors occur.
4154 Errors are printed on stderr and can be queried using
4155 @pxref{50,,gcc_jit_context_get_first_error()}.
4157 They typically contain the name of the API entrypoint where the error
4158 occurred, and pertinent information on the problem:
4160 @example
4161 ./buggy-program: error: gcc_jit_block_add_assignment: mismatching types: assignment to i (type: int) from "hello world" (type: const char *)
4162 @end example
4164 @noindent
4166 In general, if an error occurs when using an API entrypoint, the
4167 entrypoint returns NULL.  You don't have to check everywhere for NULL
4168 results, since the API handles a NULL being passed in for any
4169 argument by issuing another error.  This typically leads to a cascade of
4170 followup error messages, but is safe (albeit verbose).  The first error
4171 message is usually the one to pay attention to, since it is likely to
4172 be responsible for all of the rest:
4174 @geindex gcc_jit_context_get_first_error (C function)
4175 @anchor{topics/contexts gcc_jit_context_get_first_error}@anchor{50}
4176 @deffn {C Function} const char *           gcc_jit_context_get_first_error (gcc_jit_context@w{ }*ctxt)
4178 Returns the first error message that occurred on the context.
4180 The returned string is valid for the rest of the lifetime of the
4181 context.
4183 If no errors occurred, this will be NULL.
4184 @end deffn
4186 If you are wrapping the C API for a higher-level language that supports
4187 exception-handling, you may instead by interested in the last error that
4188 occurred on the context, so that you can embed this in an exception:
4190 @geindex gcc_jit_context_get_last_error (C function)
4191 @anchor{topics/contexts gcc_jit_context_get_last_error}@anchor{51}
4192 @deffn {C Function} const char *           gcc_jit_context_get_last_error (gcc_jit_context@w{ }*ctxt)
4194 Returns the last error message that occurred on the context.
4196 The returned string is valid for the rest of the lifetime of the
4197 context.
4199 If no errors occurred, this will be NULL.
4200 @end deffn
4202 @node Debugging,Options<2>,Error-handling<2>,Compilation contexts
4203 @anchor{topics/contexts debugging}@anchor{52}
4204 @subsection Debugging
4207 @geindex gcc_jit_context_dump_to_file (C function)
4208 @anchor{topics/contexts gcc_jit_context_dump_to_file}@anchor{53}
4209 @deffn {C Function} void           gcc_jit_context_dump_to_file (gcc_jit_context@w{ }*ctxt, const char@w{ }*path, int@w{ }update_locations)
4211 To help with debugging: dump a C-like representation to the given path,
4212 describing what's been set up on the context.
4214 If "update_locations" is true, then also set up @pxref{3b,,gcc_jit_location}
4215 information throughout the context, pointing at the dump file as if it
4216 were a source file.  This may be of use in conjunction with
4217 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} to allow stepping through the
4218 code in a debugger.
4219 @end deffn
4221 @geindex gcc_jit_context_set_logfile (C function)
4222 @anchor{topics/contexts gcc_jit_context_set_logfile}@anchor{54}
4223 @deffn {C Function} void           gcc_jit_context_set_logfile (gcc_jit_context@w{ }*ctxt, FILE@w{ }*logfile, int@w{ }flags, int@w{ }verbosity)
4225 To help with debugging; enable ongoing logging of the context's
4226 activity to the given file.
4228 For example, the following will enable logging to stderr.
4230 @example
4231 gcc_jit_context_set_logfile (ctxt, stderr, 0, 0);
4232 @end example
4234 @noindent
4236 Examples of information logged include:
4239 @itemize *
4241 @item 
4242 API calls
4244 @item 
4245 the various steps involved within compilation
4247 @item 
4248 activity on any @pxref{16,,gcc_jit_result} instances created by
4249 the context
4251 @item 
4252 activity within any child contexts
4253 @end itemize
4255 An example of a log can be seen @pxref{55,,here},
4256 though the precise format and kinds of information logged is subject
4257 to change.
4259 The caller remains responsible for closing @cite{logfile}, and it must not
4260 be closed until all users are released.  In particular, note that
4261 child contexts and @pxref{16,,gcc_jit_result} instances created by
4262 the context will use the logfile.
4264 There may a performance cost for logging.
4266 You can turn off logging on @cite{ctxt} by passing @cite{NULL} for @cite{logfile}.
4267 Doing so only affects the context; it does not affect child contexts
4268 or @pxref{16,,gcc_jit_result} instances already created by
4269 the context.
4271 The parameters "flags" and "verbosity" are reserved for future
4272 expansion, and must be zero for now.
4273 @end deffn
4275 To contrast the above: @pxref{53,,gcc_jit_context_dump_to_file()} dumps the
4276 current state of a context to the given path, whereas
4277 @pxref{54,,gcc_jit_context_set_logfile()} enables on-going logging of
4278 future activies on a context to the given @cite{FILE *}.
4280 @geindex gcc_jit_context_dump_reproducer_to_file (C function)
4281 @anchor{topics/contexts gcc_jit_context_dump_reproducer_to_file}@anchor{56}
4282 @deffn {C Function} void           gcc_jit_context_dump_reproducer_to_file (gcc_jit_context@w{ }*ctxt, const char@w{ }*path)
4284 Write C source code into @cite{path} that can be compiled into a
4285 self-contained executable (i.e. with libgccjit as the only dependency).
4286 The generated code will attempt to replay the API calls that have been
4287 made into the given context.
4289 This may be useful when debugging the library or client code, for
4290 reducing a complicated recipe for reproducing a bug into a simpler
4291 form.  For example, consider client code that parses some source file
4292 into some internal representation, and then walks this IR, calling into
4293 libgccjit.  If this encounters a bug, a call to
4294 @cite{gcc_jit_context_dump_reproducer_to_file} will write out C code for
4295 a much simpler executable that performs the equivalent calls into
4296 libgccjit, without needing the client code and its data.
4298 Typically you need to supply @code{-Wno-unused-variable} when
4299 compiling the generated file (since the result of each API call is
4300 assigned to a unique variable within the generated C source, and not
4301 all are necessarily then used).
4302 @end deffn
4304 @geindex gcc_jit_context_enable_dump (C function)
4305 @anchor{topics/contexts gcc_jit_context_enable_dump}@anchor{57}
4306 @deffn {C Function} void           gcc_jit_context_enable_dump (gcc_jit_context@w{ }*ctxt, const char@w{ }*dumpname, char@w{ }**out_ptr)
4308 Enable the dumping of a specific set of internal state from the
4309 compilation, capturing the result in-memory as a buffer.
4311 Parameter "dumpname" corresponds to the equivalent gcc command-line
4312 option, without the "-fdump-" prefix.
4313 For example, to get the equivalent of @code{-fdump-tree-vrp1},
4314 supply @code{"tree-vrp1"}:
4316 @example
4317 static char *dump_vrp1;
4319 void
4320 create_code (gcc_jit_context *ctxt)
4322    gcc_jit_context_enable_dump (ctxt, "tree-vrp1", &dump_vrp1);
4323    /* (other API calls omitted for brevity) */
4325 @end example
4327 @noindent
4329 The context directly stores the dumpname as a @code{(const char *)}, so
4330 the passed string must outlive the context.
4332 @pxref{15,,gcc_jit_context_compile()} will capture the dump as a
4333 dynamically-allocated buffer, writing it to @code{*out_ptr}.
4335 The caller becomes responsible for calling:
4337 @example
4338 free (*out_ptr)
4339 @end example
4341 @noindent
4343 each time that @pxref{15,,gcc_jit_context_compile()} is called.
4344 @code{*out_ptr} will be written to, either with the address of a buffer,
4345 or with @code{NULL} if an error occurred.
4347 @cartouche
4348 @quotation Warning 
4349 This API entrypoint is likely to be less stable than the others.
4350 In particular, both the precise dumpnames, and the format and content
4351 of the dumps are subject to change.
4353 It exists primarily for writing the library's own test suite.
4354 @end quotation
4355 @end cartouche
4356 @end deffn
4358 @node Options<2>,,Debugging,Compilation contexts
4359 @anchor{topics/contexts options}@anchor{58}
4360 @subsection Options
4363 @menu
4364 * String Options:: 
4365 * Boolean options:: 
4366 * Integer options:: 
4368 @end menu
4370 @node String Options,Boolean options,,Options<2>
4371 @anchor{topics/contexts string-options}@anchor{59}
4372 @subsubsection String Options
4375 @geindex gcc_jit_context_set_str_option (C function)
4376 @anchor{topics/contexts gcc_jit_context_set_str_option}@anchor{5a}
4377 @deffn {C Function} void gcc_jit_context_set_str_option (gcc_jit_context@w{ }*ctxt, enum gcc_jit_str_option@w{ }opt, const char@w{ }*value)
4379 Set a string option of the context.
4381 @geindex gcc_jit_str_option (C type)
4382 @anchor{topics/contexts gcc_jit_str_option}@anchor{5b}
4383 @deffn {C Type} enum gcc_jit_str_option
4384 @end deffn
4386 There is currently just one string option:
4388 @geindex GCC_JIT_STR_OPTION_PROGNAME (C macro)
4389 @anchor{topics/contexts GCC_JIT_STR_OPTION_PROGNAME}@anchor{5c}
4390 @deffn {C Macro} GCC_JIT_STR_OPTION_PROGNAME
4392 The name of the program, for use as a prefix when printing error
4393 messages to stderr.  If @cite{NULL}, or default, "libgccjit.so" is used.
4394 @end deffn
4395 @end deffn
4397 @node Boolean options,Integer options,String Options,Options<2>
4398 @anchor{topics/contexts boolean-options}@anchor{5d}
4399 @subsubsection Boolean options
4402 @geindex gcc_jit_context_set_bool_option (C function)
4403 @anchor{topics/contexts gcc_jit_context_set_bool_option}@anchor{1b}
4404 @deffn {C Function} void gcc_jit_context_set_bool_option (gcc_jit_context@w{ }*ctxt, enum gcc_jit_bool_option@w{ }opt, int@w{ }value)
4406 Set a boolean option of the context.
4407 Zero is "false" (the default), non-zero is "true".
4409 @geindex gcc_jit_bool_option (C type)
4410 @anchor{topics/contexts gcc_jit_bool_option}@anchor{5e}
4411 @deffn {C Type} enum gcc_jit_bool_option
4412 @end deffn
4414 @geindex GCC_JIT_BOOL_OPTION_DEBUGINFO (C macro)
4415 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DEBUGINFO}@anchor{42}
4416 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DEBUGINFO
4418 If true, @pxref{15,,gcc_jit_context_compile()} will attempt to do the right
4419 thing so that if you attach a debugger to the process, it will
4420 be able to inspect variables and step through your code.
4422 Note that you can't step through code unless you set up source
4423 location information for the code (by creating and passing in
4424 @pxref{3b,,gcc_jit_location} instances).
4425 @end deffn
4427 @geindex GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE (C macro)
4428 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE}@anchor{5f}
4429 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE
4431 If true, @pxref{15,,gcc_jit_context_compile()} will dump its initial
4432 "tree" representation of your code to stderr (before any
4433 optimizations).
4435 Here's some sample output (from the @cite{square} example):
4437 @example
4438 <statement_list 0x7f4875a62cc0
4439    type <void_type 0x7f4875a64bd0 VOID
4440        align 8 symtab 0 alias set -1 canonical type 0x7f4875a64bd0
4441        pointer_to_this <pointer_type 0x7f4875a64c78>>
4442    side-effects head 0x7f4875a761e0 tail 0x7f4875a761f8 stmts 0x7f4875a62d20 0x7f4875a62d00
4444    stmt <label_expr 0x7f4875a62d20 type <void_type 0x7f4875a64bd0>
4445        side-effects
4446        arg 0 <label_decl 0x7f4875a79080 entry type <void_type 0x7f4875a64bd0>
4447            VOID file (null) line 0 col 0
4448            align 1 context <function_decl 0x7f4875a77500 square>>>
4449    stmt <return_expr 0x7f4875a62d00
4450        type <integer_type 0x7f4875a645e8 public SI
4451            size <integer_cst 0x7f4875a623a0 constant 32>
4452            unit size <integer_cst 0x7f4875a623c0 constant 4>
4453            align 32 symtab 0 alias set -1 canonical type 0x7f4875a645e8 precision 32 min <integer_cst 0x7f4875a62340 -2147483648> max <integer_cst 0x7f4875a62360 2147483647>
4454            pointer_to_this <pointer_type 0x7f4875a6b348>>
4455        side-effects
4456        arg 0 <modify_expr 0x7f4875a72a78 type <integer_type 0x7f4875a645e8>
4457            side-effects arg 0 <result_decl 0x7f4875a7a000 D.54>
4458            arg 1 <mult_expr 0x7f4875a72a50 type <integer_type 0x7f4875a645e8>
4459                arg 0 <parm_decl 0x7f4875a79000 i> arg 1 <parm_decl 0x7f4875a79000 i>>>>>
4460 @end example
4462 @noindent
4463 @end deffn
4465 @geindex GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE (C macro)
4466 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE}@anchor{1c}
4467 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE
4469 If true, @pxref{15,,gcc_jit_context_compile()} will dump the "gimple"
4470 representation of your code to stderr, before any optimizations
4471 are performed.  The dump resembles C code:
4473 @example
4474 square (signed int i)
4476   signed int D.56;
4478   entry:
4479   D.56 = i * i;
4480   return D.56;
4482 @end example
4484 @noindent
4485 @end deffn
4487 @geindex GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE (C macro)
4488 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE}@anchor{1d}
4489 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE
4491 If true, @pxref{15,,gcc_jit_context_compile()} will dump the final
4492 generated code to stderr, in the form of assembly language:
4494 @example
4495     .file    "fake.c"
4496     .text
4497     .globl    square
4498     .type    square, @@function
4499 square:
4500 .LFB0:
4501     .cfi_startproc
4502     pushq    %rbp
4503     .cfi_def_cfa_offset 16
4504     .cfi_offset 6, -16
4505     movq    %rsp, %rbp
4506     .cfi_def_cfa_register 6
4507     movl    %edi, -4(%rbp)
4508 .L2:
4509     movl    -4(%rbp), %eax
4510     imull    -4(%rbp), %eax
4511     popq    %rbp
4512     .cfi_def_cfa 7, 8
4513     ret
4514     .cfi_endproc
4515 .LFE0:
4516     .size    square, .-square
4517     .ident    "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.1-%@{gcc_release@})"
4518     .section    .note.GNU-stack,"",@@progbits
4519 @end example
4521 @noindent
4522 @end deffn
4524 @geindex GCC_JIT_BOOL_OPTION_DUMP_SUMMARY (C macro)
4525 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_SUMMARY}@anchor{60}
4526 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_SUMMARY
4528 If true, @pxref{15,,gcc_jit_context_compile()} will print information to stderr
4529 on the actions it is performing, followed by a profile showing
4530 the time taken and memory usage of each phase.
4531 @end deffn
4533 @geindex GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING (C macro)
4534 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING}@anchor{61}
4535 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING
4537 If true, @pxref{15,,gcc_jit_context_compile()} will dump copious
4538 amount of information on what it's doing to various
4539 files within a temporary directory.  Use
4540 @pxref{62,,GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES} (see below) to
4541 see the results.  The files are intended to be human-readable,
4542 but the exact files and their formats are subject to change.
4543 @end deffn
4545 @geindex GCC_JIT_BOOL_OPTION_SELFCHECK_GC (C macro)
4546 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_SELFCHECK_GC}@anchor{63}
4547 @deffn {C Macro} GCC_JIT_BOOL_OPTION_SELFCHECK_GC
4549 If true, libgccjit will aggressively run its garbage collector, to
4550 shake out bugs (greatly slowing down the compile).  This is likely
4551 to only be of interest to developers @emph{of} the library.  It is
4552 used when running the selftest suite.
4553 @end deffn
4555 @geindex GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES (C macro)
4556 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES}@anchor{62}
4557 @deffn {C Macro} GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES
4559 If true, the @pxref{8,,gcc_jit_context} will not clean up intermediate files
4560 written to the filesystem, and will display their location on stderr.
4561 @end deffn
4562 @end deffn
4564 @node Integer options,,Boolean options,Options<2>
4565 @anchor{topics/contexts integer-options}@anchor{64}
4566 @subsubsection Integer options
4569 @geindex gcc_jit_context_set_int_option (C function)
4570 @anchor{topics/contexts gcc_jit_context_set_int_option}@anchor{1e}
4571 @deffn {C Function} void gcc_jit_context_set_int_option (gcc_jit_context@w{ }*ctxt, enum gcc_jit_int_option@w{ }opt, int@w{ }value)
4573 Set an integer option of the context.
4575 @geindex gcc_jit_int_option (C type)
4576 @anchor{topics/contexts gcc_jit_int_option}@anchor{65}
4577 @deffn {C Type} enum gcc_jit_int_option
4578 @end deffn
4580 There is currently just one integer option:
4582 @geindex GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL (C macro)
4583 @anchor{topics/contexts GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}@anchor{1f}
4584 @deffn {C Macro} GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL
4586 How much to optimize the code.
4588 Valid values are 0-3, corresponding to GCC's command-line options
4589 -O0 through -O3.
4591 The default value is 0 (unoptimized).
4592 @end deffn
4593 @end deffn
4595 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
4596 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
4597 @c 
4598 @c This is free software: you can redistribute it and/or modify it
4599 @c under the terms of the GNU General Public License as published by
4600 @c the Free Software Foundation, either version 3 of the License, or
4601 @c (at your option) any later version.
4602 @c 
4603 @c This program is distributed in the hope that it will be useful, but
4604 @c WITHOUT ANY WARRANTY; without even the implied warranty of
4605 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
4606 @c General Public License for more details.
4607 @c 
4608 @c You should have received a copy of the GNU General Public License
4609 @c along with this program.  If not, see
4610 @c <http://www.gnu.org/licenses/>.
4612 @node Objects,Types,Compilation contexts,Topic Reference
4613 @anchor{topics/objects objects}@anchor{66}@anchor{topics/objects doc}@anchor{67}
4614 @section Objects
4617 @geindex gcc_jit_object (C type)
4618 @anchor{topics/objects gcc_jit_object}@anchor{e}
4619 @deffn {C Type} gcc_jit_object
4620 @end deffn
4622 Almost every entity in the API (with the exception of
4623 @pxref{8,,gcc_jit_context *} and @pxref{16,,gcc_jit_result *}) is a
4624 "contextual" object, a @pxref{e,,gcc_jit_object *}
4626 A JIT object:
4628 @quotation
4631 @itemize *
4633 @item 
4634 is associated with a @pxref{8,,gcc_jit_context *}.
4636 @item 
4637 is automatically cleaned up for you when its context is released so
4638 you don't need to manually track and cleanup all objects, just the
4639 contexts.
4640 @end itemize
4641 @end quotation
4643 Although the API is C-based, there is a form of class hierarchy, which
4644 looks like this:
4646 @example
4647 +- gcc_jit_object
4648     +- gcc_jit_location
4649     +- gcc_jit_type
4650        +- gcc_jit_struct
4651     +- gcc_jit_field
4652     +- gcc_jit_function
4653     +- gcc_jit_block
4654     +- gcc_jit_rvalue
4655         +- gcc_jit_lvalue
4656            +- gcc_jit_param
4657 @end example
4659 @noindent
4661 There are casting methods for upcasting from subclasses to parent classes.
4662 For example, @pxref{d,,gcc_jit_type_as_object()}:
4664 @example
4665 gcc_jit_object *obj = gcc_jit_type_as_object (int_type);
4666 @end example
4668 @noindent
4670 The object "base class" has the following operations:
4672 @geindex gcc_jit_object_get_context (C function)
4673 @anchor{topics/objects gcc_jit_object_get_context}@anchor{68}
4674 @deffn {C Function} gcc_jit_context *gcc_jit_object_get_context (gcc_jit_object@w{ }*obj)
4676 Which context is "obj" within?
4677 @end deffn
4679 @geindex gcc_jit_object_get_debug_string (C function)
4680 @anchor{topics/objects gcc_jit_object_get_debug_string}@anchor{f}
4681 @deffn {C Function} const char *gcc_jit_object_get_debug_string (gcc_jit_object@w{ }*obj)
4683 Generate a human-readable description for the given object.
4685 For example,
4687 @example
4688 printf ("obj: %s\n", gcc_jit_object_get_debug_string (obj));
4689 @end example
4691 @noindent
4693 might give this text on stdout:
4695 @example
4696 obj: 4.0 * (float)i
4697 @end example
4699 @noindent
4701 @cartouche
4702 @quotation Note 
4703 If you call this on an object, the @cite{const char *} buffer is allocated
4704 and generated on the first call for that object, and the buffer will
4705 have the same lifetime as the object  i.e. it will exist until the
4706 object's context is released.
4707 @end quotation
4708 @end cartouche
4709 @end deffn
4711 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
4712 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
4713 @c 
4714 @c This is free software: you can redistribute it and/or modify it
4715 @c under the terms of the GNU General Public License as published by
4716 @c the Free Software Foundation, either version 3 of the License, or
4717 @c (at your option) any later version.
4718 @c 
4719 @c This program is distributed in the hope that it will be useful, but
4720 @c WITHOUT ANY WARRANTY; without even the implied warranty of
4721 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
4722 @c General Public License for more details.
4723 @c 
4724 @c You should have received a copy of the GNU General Public License
4725 @c along with this program.  If not, see
4726 @c <http://www.gnu.org/licenses/>.
4728 @node Types,Expressions,Objects,Topic Reference
4729 @anchor{topics/types doc}@anchor{69}@anchor{topics/types types}@anchor{6a}
4730 @section Types
4733 @geindex gcc_jit_type (C type)
4734 @anchor{topics/types gcc_jit_type}@anchor{a}
4735 @deffn {C Type} gcc_jit_type
4737 gcc_jit_type represents a type within the library.
4738 @end deffn
4740 @geindex gcc_jit_type_as_object (C function)
4741 @anchor{topics/types gcc_jit_type_as_object}@anchor{d}
4742 @deffn {C Function} gcc_jit_object *gcc_jit_type_as_object (gcc_jit_type@w{ }*type)
4744 Upcast a type to an object.
4745 @end deffn
4747 Types can be created in several ways:
4750 @itemize *
4752 @item 
4753 fundamental types can be accessed using
4754 @pxref{b,,gcc_jit_context_get_type()}:
4756 @example
4757 gcc_jit_type *int_type = gcc_jit_context_get_type (GCC_JIT_TYPE_INT);
4758 @end example
4760 @noindent
4762 See @pxref{b,,gcc_jit_context_get_type()} for the available types.
4764 @item 
4765 derived types can be accessed by using functions such as
4766 @pxref{6b,,gcc_jit_type_get_pointer()} and @pxref{6c,,gcc_jit_type_get_const()}:
4768 @example
4769 gcc_jit_type *const_int_star = gcc_jit_type_get_pointer (gcc_jit_type_get_const (int_type));
4770 gcc_jit_type *int_const_star = gcc_jit_type_get_const (gcc_jit_type_get_pointer (int_type));
4771 @end example
4773 @noindent
4775 @item 
4776 by creating structures (see below).
4777 @end itemize
4779 @menu
4780 * Standard types:: 
4781 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile. 
4782 * Structures and unions:: 
4784 @end menu
4786 @node Standard types,Pointers const and volatile,,Types
4787 @anchor{topics/types standard-types}@anchor{6d}
4788 @subsection Standard types
4791 @geindex gcc_jit_context_get_type (C function)
4792 @anchor{topics/types gcc_jit_context_get_type}@anchor{b}
4793 @deffn {C Function} gcc_jit_type *gcc_jit_context_get_type (gcc_jit_context@w{ }*ctxt, enum gcc_jit_types@w{ }type_)
4795 Access a specific type.  The available types are:
4798 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
4799 @headitem
4801 @cite{enum gcc_jit_types} value
4803 @tab
4805 Meaning
4807 @item
4809 @code{GCC_JIT_TYPE_VOID}
4811 @tab
4813 C's @code{void} type.
4815 @item
4817 @code{GCC_JIT_TYPE_VOID_PTR}
4819 @tab
4821 C's @code{void *}.
4823 @item
4825 @code{GCC_JIT_TYPE_BOOL}
4827 @tab
4829 C++'s @code{bool} type; also C99's
4830 @code{_Bool} type, aka @code{bool} if
4831 using stdbool.h.
4833 @item
4835 @code{GCC_JIT_TYPE_CHAR}
4837 @tab
4839 C's @code{char} (of some signedness)
4841 @item
4843 @code{GCC_JIT_TYPE_SIGNED_CHAR}
4845 @tab
4847 C's @code{signed char}
4849 @item
4851 @code{GCC_JIT_TYPE_UNSIGNED_CHAR}
4853 @tab
4855 C's @code{unsigned char}
4857 @item
4859 @code{GCC_JIT_TYPE_SHORT}
4861 @tab
4863 C's @code{short} (signed)
4865 @item
4867 @code{GCC_JIT_TYPE_UNSIGNED_SHORT}
4869 @tab
4871 C's @code{unsigned short}
4873 @item
4875 @code{GCC_JIT_TYPE_INT}
4877 @tab
4879 C's @code{int} (signed)
4881 @item
4883 @code{GCC_JIT_TYPE_UNSIGNED_INT}
4885 @tab
4887 C's @code{unsigned int}
4889 @item
4891 @code{GCC_JIT_TYPE_LONG}
4893 @tab
4895 C's @code{long} (signed)
4897 @item
4899 @code{GCC_JIT_TYPE_UNSIGNED_LONG}
4901 @tab
4903 C's @code{unsigned long}
4905 @item
4907 @code{GCC_JIT_TYPE_LONG_LONG}
4909 @tab
4911 C99's @code{long long} (signed)
4913 @item
4915 @code{GCC_JIT_TYPE_UNSIGNED_LONG_LONG}
4917 @tab
4919 C99's @code{unsigned long long}
4921 @item
4923 @code{GCC_JIT_TYPE_FLOAT}
4925 @tab
4927 @item
4929 @code{GCC_JIT_TYPE_DOUBLE}
4931 @tab
4933 @item
4935 @code{GCC_JIT_TYPE_LONG_DOUBLE}
4937 @tab
4939 @item
4941 @code{GCC_JIT_TYPE_CONST_CHAR_PTR}
4943 @tab
4945 C type: @code{(const char *)}
4947 @item
4949 @code{GCC_JIT_TYPE_SIZE_T}
4951 @tab
4953 C's @code{size_t} type
4955 @item
4957 @code{GCC_JIT_TYPE_FILE_PTR}
4959 @tab
4961 C type: @code{(FILE *)}
4963 @item
4965 @code{GCC_JIT_TYPE_COMPLEX_FLOAT}
4967 @tab
4969 C99's @code{_Complex float}
4971 @item
4973 @code{GCC_JIT_TYPE_COMPLEX_DOUBLE}
4975 @tab
4977 C99's @code{_Complex double}
4979 @item
4981 @code{GCC_JIT_TYPE_COMPLEX_LONG_DOUBLE}
4983 @tab
4985 C99's @code{_Complex long double}
4987 @end multitable
4989 @end deffn
4991 @geindex gcc_jit_context_get_int_type (C function)
4992 @anchor{topics/types gcc_jit_context_get_int_type}@anchor{6e}
4993 @deffn {C Function} gcc_jit_type *           gcc_jit_context_get_int_type (gcc_jit_context@w{ }*ctxt, int@w{ }num_bytes, int@w{ }is_signed)
4995 Access the integer type of the given size.
4996 @end deffn
4998 @node Pointers const and volatile,Structures and unions,Standard types,Types
4999 @anchor{topics/types pointers-const-and-volatile}@anchor{6f}
5000 @subsection Pointers, @cite{const}, and @cite{volatile}
5003 @geindex gcc_jit_type_get_pointer (C function)
5004 @anchor{topics/types gcc_jit_type_get_pointer}@anchor{6b}
5005 @deffn {C Function} gcc_jit_type *gcc_jit_type_get_pointer (gcc_jit_type@w{ }*type)
5007 Given type "T", get type "T*".
5008 @end deffn
5010 @geindex gcc_jit_type_get_const (C function)
5011 @anchor{topics/types gcc_jit_type_get_const}@anchor{6c}
5012 @deffn {C Function} gcc_jit_type *gcc_jit_type_get_const (gcc_jit_type@w{ }*type)
5014 Given type "T", get type "const T".
5015 @end deffn
5017 @geindex gcc_jit_type_get_volatile (C function)
5018 @anchor{topics/types gcc_jit_type_get_volatile}@anchor{70}
5019 @deffn {C Function} gcc_jit_type *gcc_jit_type_get_volatile (gcc_jit_type@w{ }*type)
5021 Given type "T", get type "volatile T".
5022 @end deffn
5024 @geindex gcc_jit_context_new_array_type (C function)
5025 @anchor{topics/types gcc_jit_context_new_array_type}@anchor{71}
5026 @deffn {C Function} gcc_jit_type *            gcc_jit_context_new_array_type (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, gcc_jit_type@w{ }*element_type, int@w{ }num_elements)
5028 Given type "T", get type "T[N]" (for a constant N).
5029 @end deffn
5031 @node Structures and unions,,Pointers const and volatile,Types
5032 @anchor{topics/types structures-and-unions}@anchor{72}
5033 @subsection Structures and unions
5036 @geindex gcc_jit_struct (C type)
5037 @anchor{topics/types gcc_jit_struct}@anchor{73}
5038 @deffn {C Type} gcc_jit_struct
5039 @end deffn
5041 A compound type analagous to a C @cite{struct}.
5043 @geindex gcc_jit_field (C type)
5044 @anchor{topics/types gcc_jit_field}@anchor{74}
5045 @deffn {C Type} gcc_jit_field
5046 @end deffn
5048 A field within a @pxref{73,,gcc_jit_struct}.
5050 You can model C @cite{struct} types by creating @pxref{73,,gcc_jit_struct *} and
5051 @pxref{74,,gcc_jit_field} instances, in either order:
5054 @itemize *
5056 @item 
5057 by creating the fields, then the structure.  For example, to model:
5059 @example
5060 struct coord @{double x; double y; @};
5061 @end example
5063 @noindent
5065 you could call:
5067 @example
5068 gcc_jit_field *field_x =
5069   gcc_jit_context_new_field (ctxt, NULL, double_type, "x");
5070 gcc_jit_field *field_y =
5071   gcc_jit_context_new_field (ctxt, NULL, double_type, "y");
5072 gcc_jit_field *fields[2] = @{field_x, field_y@};
5073 gcc_jit_struct *coord =
5074   gcc_jit_context_new_struct_type (ctxt, NULL, "coord", 2, fields);
5075 @end example
5077 @noindent
5079 @item 
5080 by creating the structure, then populating it with fields, typically
5081 to allow modelling self-referential structs such as:
5083 @example
5084 struct node @{ int m_hash; struct node *m_next; @};
5085 @end example
5087 @noindent
5089 like this:
5091 @example
5092 gcc_jit_type *node =
5093   gcc_jit_context_new_opaque_struct (ctxt, NULL, "node");
5094 gcc_jit_type *node_ptr =
5095   gcc_jit_type_get_pointer (node);
5096 gcc_jit_field *field_hash =
5097   gcc_jit_context_new_field (ctxt, NULL, int_type, "m_hash");
5098 gcc_jit_field *field_next =
5099   gcc_jit_context_new_field (ctxt, NULL, node_ptr, "m_next");
5100 gcc_jit_field *fields[2] = @{field_hash, field_next@};
5101 gcc_jit_struct_set_fields (node, NULL, 2, fields);
5102 @end example
5104 @noindent
5105 @end itemize
5107 @geindex gcc_jit_context_new_field (C function)
5108 @anchor{topics/types gcc_jit_context_new_field}@anchor{75}
5109 @deffn {C Function} gcc_jit_field *           gcc_jit_context_new_field (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, gcc_jit_type@w{ }*type, const char@w{ }*name)
5111 Construct a new field, with the given type and name.
5112 @end deffn
5114 @geindex gcc_jit_field_as_object (C function)
5115 @anchor{topics/types gcc_jit_field_as_object}@anchor{76}
5116 @deffn {C Function} gcc_jit_object *           gcc_jit_field_as_object (gcc_jit_field@w{ }*field)
5118 Upcast from field to object.
5119 @end deffn
5121 @geindex gcc_jit_context_new_struct_type (C function)
5122 @anchor{topics/types gcc_jit_context_new_struct_type}@anchor{77}
5123 @deffn {C Function} gcc_jit_struct *gcc_jit_context_new_struct_type (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, const char@w{ }*name, int@w{ }num_fields, gcc_jit_field@w{ }**fields)
5125 @quotation
5127 Construct a new struct type, with the given name and fields.
5128 @end quotation
5129 @end deffn
5131 @geindex gcc_jit_context_new_opaque_struct (C function)
5132 @anchor{topics/types gcc_jit_context_new_opaque_struct}@anchor{78}
5133 @deffn {C Function} gcc_jit_struct *         gcc_jit_context_new_opaque_struct (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, const char@w{ }*name)
5135 Construct a new struct type, with the given name, but without
5136 specifying the fields.   The fields can be omitted (in which case the
5137 size of the struct is not known), or later specified using
5138 @pxref{79,,gcc_jit_struct_set_fields()}.
5139 @end deffn
5141 @geindex gcc_jit_struct_as_type (C function)
5142 @anchor{topics/types gcc_jit_struct_as_type}@anchor{7a}
5143 @deffn {C Function} gcc_jit_type *           gcc_jit_struct_as_type (gcc_jit_struct@w{ }*struct_type)
5145 Upcast from struct to type.
5146 @end deffn
5148 @geindex gcc_jit_struct_set_fields (C function)
5149 @anchor{topics/types gcc_jit_struct_set_fields}@anchor{79}
5150 @deffn {C Function} void           gcc_jit_struct_set_fields (gcc_jit_struct@w{ }*struct_type, gcc_jit_location@w{ }*loc, int@w{ }num_fields, gcc_jit_field@w{ }**fields)
5152 Populate the fields of a formerly-opaque struct type.
5154 This can only be called once on a given struct type.
5155 @end deffn
5157 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
5158 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
5159 @c 
5160 @c This is free software: you can redistribute it and/or modify it
5161 @c under the terms of the GNU General Public License as published by
5162 @c the Free Software Foundation, either version 3 of the License, or
5163 @c (at your option) any later version.
5164 @c 
5165 @c This program is distributed in the hope that it will be useful, but
5166 @c WITHOUT ANY WARRANTY; without even the implied warranty of
5167 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
5168 @c General Public License for more details.
5169 @c 
5170 @c You should have received a copy of the GNU General Public License
5171 @c along with this program.  If not, see
5172 @c <http://www.gnu.org/licenses/>.
5174 @node Expressions,Creating and using functions,Types,Topic Reference
5175 @anchor{topics/expressions expressions}@anchor{7b}@anchor{topics/expressions doc}@anchor{7c}
5176 @section Expressions
5179 @menu
5180 * Rvalues:: 
5181 * Lvalues:: 
5182 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions. 
5184 Rvalues
5186 * Simple expressions:: 
5187 * Unary Operations:: 
5188 * Binary Operations:: 
5189 * Comparisons:: 
5190 * Function calls:: 
5191 * Type-coercion:: 
5193 Lvalues
5195 * Global variables:: 
5197 @end menu
5200 @node Rvalues,Lvalues,,Expressions
5201 @anchor{topics/expressions rvalues}@anchor{7d}
5202 @subsection Rvalues
5205 @geindex gcc_jit_rvalue (C type)
5206 @anchor{topics/expressions gcc_jit_rvalue}@anchor{13}
5207 @deffn {C Type} gcc_jit_rvalue
5208 @end deffn
5210 A @pxref{13,,gcc_jit_rvalue *} is an expression that can be computed.
5212 It can be simple, e.g.:
5214 @quotation
5217 @itemize *
5219 @item 
5220 an integer value e.g. @cite{0} or @cite{42}
5222 @item 
5223 a string literal e.g. @cite{"Hello world"}
5225 @item 
5226 a variable e.g. @cite{i}.  These are also lvalues (see below).
5227 @end itemize
5228 @end quotation
5230 or compound e.g.:
5232 @quotation
5235 @itemize *
5237 @item 
5238 a unary expression e.g. @cite{!cond}
5240 @item 
5241 a binary expression e.g. @cite{(a + b)}
5243 @item 
5244 a function call e.g. @cite{get_distance (&player_ship@comma{} &target)}
5246 @item 
5247 etc.
5248 @end itemize
5249 @end quotation
5251 Every rvalue has an associated type, and the API will check to ensure
5252 that types match up correctly (otherwise the context will emit an error).
5254 @geindex gcc_jit_rvalue_get_type (C function)
5255 @anchor{topics/expressions gcc_jit_rvalue_get_type}@anchor{7e}
5256 @deffn {C Function} gcc_jit_type *gcc_jit_rvalue_get_type (gcc_jit_rvalue@w{ }*rvalue)
5258 Get the type of this rvalue.
5259 @end deffn
5261 @geindex gcc_jit_rvalue_as_object (C function)
5262 @anchor{topics/expressions gcc_jit_rvalue_as_object}@anchor{14}
5263 @deffn {C Function} gcc_jit_object *gcc_jit_rvalue_as_object (gcc_jit_rvalue@w{ }*rvalue)
5265 Upcast the given rvalue to be an object.
5266 @end deffn
5268 @menu
5269 * Simple expressions:: 
5270 * Unary Operations:: 
5271 * Binary Operations:: 
5272 * Comparisons:: 
5273 * Function calls:: 
5274 * Type-coercion:: 
5276 @end menu
5278 @node Simple expressions,Unary Operations,,Rvalues
5279 @anchor{topics/expressions simple-expressions}@anchor{7f}
5280 @subsubsection Simple expressions
5283 @geindex gcc_jit_context_new_rvalue_from_int (C function)
5284 @anchor{topics/expressions gcc_jit_context_new_rvalue_from_int}@anchor{30}
5285 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_context_new_rvalue_from_int (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*numeric_type, int@w{ }value)
5287 Given a numeric type (integer or floating point), build an rvalue for
5288 the given constant @code{int} value.
5289 @end deffn
5291 @geindex gcc_jit_context_new_rvalue_from_long (C function)
5292 @anchor{topics/expressions gcc_jit_context_new_rvalue_from_long}@anchor{80}
5293 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_context_new_rvalue_from_long (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*numeric_type, long@w{ }value)
5295 Given a numeric type (integer or floating point), build an rvalue for
5296 the given constant @code{long} value.
5297 @end deffn
5299 @geindex gcc_jit_context_zero (C function)
5300 @anchor{topics/expressions gcc_jit_context_zero}@anchor{2b}
5301 @deffn {C Function} gcc_jit_rvalue *gcc_jit_context_zero (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*numeric_type)
5303 Given a numeric type (integer or floating point), get the rvalue for
5304 zero.  Essentially this is just a shortcut for:
5306 @example
5307 gcc_jit_context_new_rvalue_from_int (ctxt, numeric_type, 0)
5308 @end example
5310 @noindent
5311 @end deffn
5313 @geindex gcc_jit_context_one (C function)
5314 @anchor{topics/expressions gcc_jit_context_one}@anchor{2f}
5315 @deffn {C Function} gcc_jit_rvalue *gcc_jit_context_one (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*numeric_type)
5317 Given a numeric type (integer or floating point), get the rvalue for
5318 zero.  Essentially this is just a shortcut for:
5320 @example
5321 gcc_jit_context_new_rvalue_from_int (ctxt, numeric_type, 1)
5322 @end example
5324 @noindent
5325 @end deffn
5327 @geindex gcc_jit_context_new_rvalue_from_double (C function)
5328 @anchor{topics/expressions gcc_jit_context_new_rvalue_from_double}@anchor{31}
5329 @deffn {C Function} gcc_jit_rvalue *            gcc_jit_context_new_rvalue_from_double (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*numeric_type, double@w{ }value)
5331 Given a numeric type (integer or floating point), build an rvalue for
5332 the given constant @code{double} value.
5333 @end deffn
5335 @geindex gcc_jit_context_new_rvalue_from_ptr (C function)
5336 @anchor{topics/expressions gcc_jit_context_new_rvalue_from_ptr}@anchor{81}
5337 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_context_new_rvalue_from_ptr (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*pointer_type, void@w{ }*value)
5339 Given a pointer type, build an rvalue for the given address.
5340 @end deffn
5342 @geindex gcc_jit_context_null (C function)
5343 @anchor{topics/expressions gcc_jit_context_null}@anchor{82}
5344 @deffn {C Function} gcc_jit_rvalue *gcc_jit_context_null (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*pointer_type)
5346 Given a pointer type, build an rvalue for @code{NULL}.  Essentially this
5347 is just a shortcut for:
5349 @example
5350 gcc_jit_context_new_rvalue_from_ptr (ctxt, pointer_type, NULL)
5351 @end example
5353 @noindent
5354 @end deffn
5356 @geindex gcc_jit_context_new_string_literal (C function)
5357 @anchor{topics/expressions gcc_jit_context_new_string_literal}@anchor{83}
5358 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_context_new_string_literal (gcc_jit_context@w{ }*ctxt, const char@w{ }*value)
5360 Generate an rvalue for the given NIL-terminated string, of type
5361 @code{GCC_JIT_TYPE_CONST_CHAR_PTR}.
5362 @end deffn
5364 @node Unary Operations,Binary Operations,Simple expressions,Rvalues
5365 @anchor{topics/expressions unary-operations}@anchor{84}
5366 @subsubsection Unary Operations
5369 @geindex gcc_jit_context_new_unary_op (C function)
5370 @anchor{topics/expressions gcc_jit_context_new_unary_op}@anchor{85}
5371 @deffn {C Function} gcc_jit_rvalue *            gcc_jit_context_new_unary_op (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, enum gcc_jit_unary_op@w{ }op, gcc_jit_type@w{ }*result_type, gcc_jit_rvalue@w{ }*rvalue)
5373 Build a unary operation out of an input rvalue.
5374 @end deffn
5376 @geindex gcc_jit_unary_op (C type)
5377 @anchor{topics/expressions gcc_jit_unary_op}@anchor{86}
5378 @deffn {C Type} enum gcc_jit_unary_op
5379 @end deffn
5381 The available unary operations are:
5384 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
5385 @headitem
5387 Unary Operation
5389 @tab
5391 C equivalent
5393 @item
5395 @pxref{87,,GCC_JIT_UNARY_OP_MINUS}
5397 @tab
5399 @cite{-(EXPR)}
5401 @item
5403 @pxref{88,,GCC_JIT_UNARY_OP_BITWISE_NEGATE}
5405 @tab
5407 @cite{~(EXPR)}
5409 @item
5411 @pxref{89,,GCC_JIT_UNARY_OP_LOGICAL_NEGATE}
5413 @tab
5415 @cite{!(EXPR)}
5417 @item
5419 @pxref{8a,,GCC_JIT_UNARY_OP_ABS}
5421 @tab
5423 @cite{abs (EXPR)}
5425 @end multitable
5428 @geindex GCC_JIT_UNARY_OP_MINUS (C macro)
5429 @anchor{topics/expressions GCC_JIT_UNARY_OP_MINUS}@anchor{87}
5430 @deffn {C Macro} GCC_JIT_UNARY_OP_MINUS
5432 Negate an arithmetic value; analogous to:
5434 @example
5435 -(EXPR)
5436 @end example
5438 @noindent
5440 in C.
5441 @end deffn
5443 @geindex GCC_JIT_UNARY_OP_BITWISE_NEGATE (C macro)
5444 @anchor{topics/expressions GCC_JIT_UNARY_OP_BITWISE_NEGATE}@anchor{88}
5445 @deffn {C Macro} GCC_JIT_UNARY_OP_BITWISE_NEGATE
5447 Bitwise negation of an integer value (one's complement); analogous
5450 @example
5451 ~(EXPR)
5452 @end example
5454 @noindent
5456 in C.
5457 @end deffn
5459 @geindex GCC_JIT_UNARY_OP_LOGICAL_NEGATE (C macro)
5460 @anchor{topics/expressions GCC_JIT_UNARY_OP_LOGICAL_NEGATE}@anchor{89}
5461 @deffn {C Macro} GCC_JIT_UNARY_OP_LOGICAL_NEGATE
5463 Logical negation of an arithmetic or pointer value; analogous to:
5465 @example
5466 !(EXPR)
5467 @end example
5469 @noindent
5471 in C.
5472 @end deffn
5474 @geindex GCC_JIT_UNARY_OP_ABS (C macro)
5475 @anchor{topics/expressions GCC_JIT_UNARY_OP_ABS}@anchor{8a}
5476 @deffn {C Macro} GCC_JIT_UNARY_OP_ABS
5478 Absolute value of an arithmetic expression; analogous to:
5480 @example
5481 abs (EXPR)
5482 @end example
5484 @noindent
5486 in C.
5487 @end deffn
5489 @node Binary Operations,Comparisons,Unary Operations,Rvalues
5490 @anchor{topics/expressions binary-operations}@anchor{8b}
5491 @subsubsection Binary Operations
5494 @geindex gcc_jit_context_new_binary_op (C function)
5495 @anchor{topics/expressions gcc_jit_context_new_binary_op}@anchor{12}
5496 @deffn {C Function} gcc_jit_rvalue *gcc_jit_context_new_binary_op (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, enum gcc_jit_binary_op@w{ }op, gcc_jit_type@w{ }*result_type, gcc_jit_rvalue@w{ }*a, gcc_jit_rvalue@w{ }*b)
5498 Build a binary operation out of two constituent rvalues.
5499 @end deffn
5501 @geindex gcc_jit_binary_op (C type)
5502 @anchor{topics/expressions gcc_jit_binary_op}@anchor{8c}
5503 @deffn {C Type} enum gcc_jit_binary_op
5504 @end deffn
5506 The available binary operations are:
5509 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
5510 @headitem
5512 Binary Operation
5514 @tab
5516 C equivalent
5518 @item
5520 @pxref{8d,,GCC_JIT_BINARY_OP_PLUS}
5522 @tab
5524 @cite{x + y}
5526 @item
5528 @code{GCC_JIT_BINARY_OP_MINUS}
5530 @tab
5532 @cite{x - y}
5534 @item
5536 @pxref{8e,,GCC_JIT_BINARY_OP_MULT}
5538 @tab
5540 @cite{x * y}
5542 @item
5544 @pxref{8f,,GCC_JIT_BINARY_OP_DIVIDE}
5546 @tab
5548 @cite{x / y}
5550 @item
5552 @pxref{90,,GCC_JIT_BINARY_OP_MODULO}
5554 @tab
5556 @cite{x % y}
5558 @item
5560 @pxref{91,,GCC_JIT_BINARY_OP_BITWISE_AND}
5562 @tab
5564 @cite{x & y}
5566 @item
5568 @pxref{92,,GCC_JIT_BINARY_OP_BITWISE_XOR}
5570 @tab
5572 @cite{x ^ y}
5574 @item
5576 @pxref{93,,GCC_JIT_BINARY_OP_BITWISE_OR}
5578 @tab
5580 @cite{x | y}
5582 @item
5584 @pxref{94,,GCC_JIT_BINARY_OP_LOGICAL_AND}
5586 @tab
5588 @cite{x && y}
5590 @item
5592 @pxref{95,,GCC_JIT_BINARY_OP_LOGICAL_OR}
5594 @tab
5596 @cite{x || y}
5598 @item
5600 @pxref{96,,GCC_JIT_BINARY_OP_LSHIFT}
5602 @tab
5604 @cite{x << y}
5606 @item
5608 @pxref{97,,GCC_JIT_BINARY_OP_RSHIFT}
5610 @tab
5612 @cite{x >> y}
5614 @end multitable
5617 @geindex GCC_JIT_BINARY_OP_PLUS (C macro)
5618 @anchor{topics/expressions GCC_JIT_BINARY_OP_PLUS}@anchor{8d}
5619 @deffn {C Macro} GCC_JIT_BINARY_OP_PLUS
5621 Addition of arithmetic values; analogous to:
5623 @example
5624 (EXPR_A) + (EXPR_B)
5625 @end example
5627 @noindent
5629 in C.
5631 For pointer addition, use @pxref{98,,gcc_jit_context_new_array_access()}.
5632 @end deffn
5635 @deffn {C Macro} GCC_JIT_BINARY_OP_MINUS`
5637 Subtraction of arithmetic values; analogous to:
5639 @example
5640 (EXPR_A) - (EXPR_B)
5641 @end example
5643 @noindent
5645 in C.
5646 @end deffn
5648 @geindex GCC_JIT_BINARY_OP_MULT (C macro)
5649 @anchor{topics/expressions GCC_JIT_BINARY_OP_MULT}@anchor{8e}
5650 @deffn {C Macro} GCC_JIT_BINARY_OP_MULT
5652 Multiplication of a pair of arithmetic values; analogous to:
5654 @example
5655 (EXPR_A) * (EXPR_B)
5656 @end example
5658 @noindent
5660 in C.
5661 @end deffn
5663 @geindex GCC_JIT_BINARY_OP_DIVIDE (C macro)
5664 @anchor{topics/expressions GCC_JIT_BINARY_OP_DIVIDE}@anchor{8f}
5665 @deffn {C Macro} GCC_JIT_BINARY_OP_DIVIDE
5667 Quotient of division of arithmetic values; analogous to:
5669 @example
5670 (EXPR_A) / (EXPR_B)
5671 @end example
5673 @noindent
5675 in C.
5677 The result type affects the kind of division: if the result type is
5678 integer-based, then the result is truncated towards zero, whereas
5679 a floating-point result type indicates floating-point division.
5680 @end deffn
5682 @geindex GCC_JIT_BINARY_OP_MODULO (C macro)
5683 @anchor{topics/expressions GCC_JIT_BINARY_OP_MODULO}@anchor{90}
5684 @deffn {C Macro} GCC_JIT_BINARY_OP_MODULO
5686 Remainder of division of arithmetic values; analogous to:
5688 @example
5689 (EXPR_A) % (EXPR_B)
5690 @end example
5692 @noindent
5694 in C.
5695 @end deffn
5697 @geindex GCC_JIT_BINARY_OP_BITWISE_AND (C macro)
5698 @anchor{topics/expressions GCC_JIT_BINARY_OP_BITWISE_AND}@anchor{91}
5699 @deffn {C Macro} GCC_JIT_BINARY_OP_BITWISE_AND
5701 Bitwise AND; analogous to:
5703 @example
5704 (EXPR_A) & (EXPR_B)
5705 @end example
5707 @noindent
5709 in C.
5710 @end deffn
5712 @geindex GCC_JIT_BINARY_OP_BITWISE_XOR (C macro)
5713 @anchor{topics/expressions GCC_JIT_BINARY_OP_BITWISE_XOR}@anchor{92}
5714 @deffn {C Macro} GCC_JIT_BINARY_OP_BITWISE_XOR
5716 Bitwise exclusive OR; analogous to:
5718 @example
5719 (EXPR_A) ^ (EXPR_B)
5720 @end example
5722 @noindent
5724 in C.
5725 @end deffn
5727 @geindex GCC_JIT_BINARY_OP_BITWISE_OR (C macro)
5728 @anchor{topics/expressions GCC_JIT_BINARY_OP_BITWISE_OR}@anchor{93}
5729 @deffn {C Macro} GCC_JIT_BINARY_OP_BITWISE_OR
5731 Bitwise inclusive OR; analogous to:
5733 @example
5734 (EXPR_A) | (EXPR_B)
5735 @end example
5737 @noindent
5739 in C.
5740 @end deffn
5742 @geindex GCC_JIT_BINARY_OP_LOGICAL_AND (C macro)
5743 @anchor{topics/expressions GCC_JIT_BINARY_OP_LOGICAL_AND}@anchor{94}
5744 @deffn {C Macro} GCC_JIT_BINARY_OP_LOGICAL_AND
5746 Logical AND; analogous to:
5748 @example
5749 (EXPR_A) && (EXPR_B)
5750 @end example
5752 @noindent
5754 in C.
5755 @end deffn
5757 @geindex GCC_JIT_BINARY_OP_LOGICAL_OR (C macro)
5758 @anchor{topics/expressions GCC_JIT_BINARY_OP_LOGICAL_OR}@anchor{95}
5759 @deffn {C Macro} GCC_JIT_BINARY_OP_LOGICAL_OR
5761 Logical OR; analogous to:
5763 @example
5764 (EXPR_A) || (EXPR_B)
5765 @end example
5767 @noindent
5769 in C.
5770 @end deffn
5772 @geindex GCC_JIT_BINARY_OP_LSHIFT (C macro)
5773 @anchor{topics/expressions GCC_JIT_BINARY_OP_LSHIFT}@anchor{96}
5774 @deffn {C Macro} GCC_JIT_BINARY_OP_LSHIFT
5776 Left shift; analogous to:
5778 @example
5779 (EXPR_A) << (EXPR_B)
5780 @end example
5782 @noindent
5784 in C.
5785 @end deffn
5787 @geindex GCC_JIT_BINARY_OP_RSHIFT (C macro)
5788 @anchor{topics/expressions GCC_JIT_BINARY_OP_RSHIFT}@anchor{97}
5789 @deffn {C Macro} GCC_JIT_BINARY_OP_RSHIFT
5791 Right shift; analogous to:
5793 @example
5794 (EXPR_A) >> (EXPR_B)
5795 @end example
5797 @noindent
5799 in C.
5800 @end deffn
5802 @node Comparisons,Function calls,Binary Operations,Rvalues
5803 @anchor{topics/expressions comparisons}@anchor{99}
5804 @subsubsection Comparisons
5807 @geindex gcc_jit_context_new_comparison (C function)
5808 @anchor{topics/expressions gcc_jit_context_new_comparison}@anchor{2c}
5809 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_context_new_comparison (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, enum gcc_jit_comparison@w{ }op, gcc_jit_rvalue@w{ }*a, gcc_jit_rvalue@w{ }*b)
5811 Build a boolean rvalue out of the comparison of two other rvalues.
5812 @end deffn
5814 @geindex gcc_jit_comparison (C type)
5815 @anchor{topics/expressions gcc_jit_comparison}@anchor{9a}
5816 @deffn {C Type} enum gcc_jit_comparison
5817 @end deffn
5820 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
5821 @headitem
5823 Comparison
5825 @tab
5827 C equivalent
5829 @item
5831 @code{GCC_JIT_COMPARISON_EQ}
5833 @tab
5835 @cite{x == y}
5837 @item
5839 @code{GCC_JIT_COMPARISON_NE}
5841 @tab
5843 @cite{x != y}
5845 @item
5847 @code{GCC_JIT_COMPARISON_LT}
5849 @tab
5851 @cite{x < y}
5853 @item
5855 @code{GCC_JIT_COMPARISON_LE}
5857 @tab
5859 @cite{x <= y}
5861 @item
5863 @code{GCC_JIT_COMPARISON_GT}
5865 @tab
5867 @cite{x > y}
5869 @item
5871 @code{GCC_JIT_COMPARISON_GE}
5873 @tab
5875 @cite{x >= y}
5877 @end multitable
5880 @node Function calls,Type-coercion,Comparisons,Rvalues
5881 @anchor{topics/expressions function-calls}@anchor{9b}
5882 @subsubsection Function calls
5885 @geindex gcc_jit_context_new_call (C function)
5886 @anchor{topics/expressions gcc_jit_context_new_call}@anchor{9c}
5887 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_context_new_call (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, gcc_jit_function@w{ }*func, int@w{ }numargs, gcc_jit_rvalue@w{ }**args)
5889 Given a function and the given table of argument rvalues, construct a
5890 call to the function, with the result as an rvalue.
5892 @cartouche
5893 @quotation Note 
5894 @pxref{9c,,gcc_jit_context_new_call()} merely builds a
5895 @pxref{13,,gcc_jit_rvalue} i.e. an expression that can be evaluated,
5896 perhaps as part of a more complicated expression.
5897 The call @emph{won't} happen unless you add a statement to a function
5898 that evaluates the expression.
5900 For example, if you want to call a function and discard the result
5901 (or to call a function with @code{void} return type), use
5902 @pxref{9d,,gcc_jit_block_add_eval()}:
5904 @example
5905 /* Add "(void)printf (arg0, arg1);".  */
5906 gcc_jit_block_add_eval (
5907   block, NULL,
5908   gcc_jit_context_new_call (
5909     ctxt,
5910     NULL,
5911     printf_func,
5912     2, args));
5913 @end example
5915 @noindent
5916 @end quotation
5917 @end cartouche
5918 @end deffn
5920 @node Type-coercion,,Function calls,Rvalues
5921 @anchor{topics/expressions type-coercion}@anchor{9e}
5922 @subsubsection Type-coercion
5925 @geindex gcc_jit_context_new_cast (C function)
5926 @anchor{topics/expressions gcc_jit_context_new_cast}@anchor{9f}
5927 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_context_new_cast (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, gcc_jit_rvalue@w{ }*rvalue, gcc_jit_type@w{ }*type)
5929 Given an rvalue of T, construct another rvalue of another type.
5931 Currently only a limited set of conversions are possible:
5933 @quotation
5936 @itemize *
5938 @item 
5939 int <-> float
5941 @item 
5942 int <-> bool
5944 @item 
5945 P*  <-> Q*, for pointer types P and Q
5946 @end itemize
5947 @end quotation
5948 @end deffn
5950 @node Lvalues,Working with pointers structs and unions,Rvalues,Expressions
5951 @anchor{topics/expressions lvalues}@anchor{a0}
5952 @subsection Lvalues
5955 @geindex gcc_jit_lvalue (C type)
5956 @anchor{topics/expressions gcc_jit_lvalue}@anchor{24}
5957 @deffn {C Type} gcc_jit_lvalue
5958 @end deffn
5960 An lvalue is something that can of the @emph{left}-hand side of an assignment:
5961 a storage area (such as a variable).  It is also usable as an rvalue,
5962 where the rvalue is computed by reading from the storage area.
5964 @geindex gcc_jit_lvalue_as_object (C function)
5965 @anchor{topics/expressions gcc_jit_lvalue_as_object}@anchor{a1}
5966 @deffn {C Function} gcc_jit_object *           gcc_jit_lvalue_as_object (gcc_jit_lvalue@w{ }*lvalue)
5968 Upcast an lvalue to be an object.
5969 @end deffn
5971 @geindex gcc_jit_lvalue_as_rvalue (C function)
5972 @anchor{topics/expressions gcc_jit_lvalue_as_rvalue}@anchor{a2}
5973 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_lvalue_as_rvalue (gcc_jit_lvalue@w{ }*lvalue)
5975 Upcast an lvalue to be an rvalue.
5976 @end deffn
5978 @geindex gcc_jit_lvalue_get_address (C function)
5979 @anchor{topics/expressions gcc_jit_lvalue_get_address}@anchor{a3}
5980 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_lvalue_get_address (gcc_jit_lvalue@w{ }*lvalue, gcc_jit_location@w{ }*loc)
5982 Take the address of an lvalue; analogous to:
5984 @example
5985 &(EXPR)
5986 @end example
5988 @noindent
5990 in C.
5991 @end deffn
5993 @menu
5994 * Global variables:: 
5996 @end menu
5998 @node Global variables,,,Lvalues
5999 @anchor{topics/expressions global-variables}@anchor{a4}
6000 @subsubsection Global variables
6003 @geindex gcc_jit_context_new_global (C function)
6004 @anchor{topics/expressions gcc_jit_context_new_global}@anchor{a5}
6005 @deffn {C Function} gcc_jit_lvalue *           gcc_jit_context_new_global (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, enum gcc_jit_global_kind@w{ }kind, gcc_jit_type@w{ }*type, const char@w{ }*name)
6007 Add a new global variable of the given type and name to the context.
6009 The "kind" parameter determines the visibility of the "global" outside
6010 of the @pxref{16,,gcc_jit_result}:
6012 @geindex gcc_jit_global_kind (C type)
6013 @anchor{topics/expressions gcc_jit_global_kind}@anchor{a6}
6014 @deffn {C Type} enum gcc_jit_global_kind
6015 @end deffn
6017 @geindex GCC_JIT_GLOBAL_EXPORTED (C macro)
6018 @anchor{topics/expressions GCC_JIT_GLOBAL_EXPORTED}@anchor{a7}
6019 @deffn {C Macro} GCC_JIT_GLOBAL_EXPORTED
6021 Global is defined by the client code and is visible
6022 by name outside of this JIT context via
6023 @pxref{a8,,gcc_jit_result_get_global()} (and this value is required for
6024 the global to be accessible via that entrypoint).
6025 @end deffn
6027 @geindex GCC_JIT_GLOBAL_INTERNAL (C macro)
6028 @anchor{topics/expressions GCC_JIT_GLOBAL_INTERNAL}@anchor{a9}
6029 @deffn {C Macro} GCC_JIT_GLOBAL_INTERNAL
6031 Global is defined by the client code, but is invisible
6032 outside of it.  Analogous to a "static" global within a .c file.
6033 Specifically, the variable will only be visible within this
6034 context and within child contexts.
6035 @end deffn
6037 @geindex GCC_JIT_GLOBAL_IMPORTED (C macro)
6038 @anchor{topics/expressions GCC_JIT_GLOBAL_IMPORTED}@anchor{aa}
6039 @deffn {C Macro} GCC_JIT_GLOBAL_IMPORTED
6041 Global is not defined by the client code; we're merely
6042 referring to it.  Analogous to using an "extern" global from a
6043 header file.
6044 @end deffn
6045 @end deffn
6047 @node Working with pointers structs and unions,,Lvalues,Expressions
6048 @anchor{topics/expressions working-with-pointers-structs-and-unions}@anchor{ab}
6049 @subsection Working with pointers, structs and unions
6052 @geindex gcc_jit_rvalue_dereference (C function)
6053 @anchor{topics/expressions gcc_jit_rvalue_dereference}@anchor{ac}
6054 @deffn {C Function} gcc_jit_lvalue *           gcc_jit_rvalue_dereference (gcc_jit_rvalue@w{ }*rvalue, gcc_jit_location@w{ }*loc)
6056 Given an rvalue of pointer type @code{T *}, dereferencing the pointer,
6057 getting an lvalue of type @code{T}.  Analogous to:
6059 @example
6060 *(EXPR)
6061 @end example
6063 @noindent
6065 in C.
6066 @end deffn
6068 Field access is provided separately for both lvalues and rvalues.
6070 @geindex gcc_jit_lvalue_access_field (C function)
6071 @anchor{topics/expressions gcc_jit_lvalue_access_field}@anchor{ad}
6072 @deffn {C Function} gcc_jit_lvalue *           gcc_jit_lvalue_access_field (gcc_jit_lvalue@w{ }*struct_, gcc_jit_location@w{ }*loc, gcc_jit_field@w{ }*field)
6074 Given an lvalue of struct or union type, access the given field,
6075 getting an lvalue of the field's type.  Analogous to:
6077 @example
6078 (EXPR).field = ...;
6079 @end example
6081 @noindent
6083 in C.
6084 @end deffn
6086 @geindex gcc_jit_rvalue_access_field (C function)
6087 @anchor{topics/expressions gcc_jit_rvalue_access_field}@anchor{ae}
6088 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_rvalue_access_field (gcc_jit_rvalue@w{ }*struct_, gcc_jit_location@w{ }*loc, gcc_jit_field@w{ }*field)
6090 Given an rvalue of struct or union type, access the given field
6091 as an rvalue.  Analogous to:
6093 @example
6094 (EXPR).field
6095 @end example
6097 @noindent
6099 in C.
6100 @end deffn
6102 @geindex gcc_jit_rvalue_dereference_field (C function)
6103 @anchor{topics/expressions gcc_jit_rvalue_dereference_field}@anchor{af}
6104 @deffn {C Function} gcc_jit_lvalue *           gcc_jit_rvalue_dereference_field (gcc_jit_rvalue@w{ }*ptr, gcc_jit_location@w{ }*loc, gcc_jit_field@w{ }*field)
6106 Given an rvalue of pointer type @code{T *} where T is of struct or union
6107 type, access the given field as an lvalue.  Analogous to:
6109 @example
6110 (EXPR)->field
6111 @end example
6113 @noindent
6115 in C, itself equivalent to @code{(*EXPR).FIELD}.
6116 @end deffn
6118 @geindex gcc_jit_context_new_array_access (C function)
6119 @anchor{topics/expressions gcc_jit_context_new_array_access}@anchor{98}
6120 @deffn {C Function} gcc_jit_lvalue *           gcc_jit_context_new_array_access (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, gcc_jit_rvalue@w{ }*ptr, gcc_jit_rvalue@w{ }*index)
6122 Given an rvalue of pointer type @code{T *}, get at the element @cite{T} at
6123 the given index, using standard C array indexing rules i.e. each
6124 increment of @code{index} corresponds to @code{sizeof(T)} bytes.
6125 Analogous to:
6127 @example
6128 PTR[INDEX]
6129 @end example
6131 @noindent
6133 in C (or, indeed, to @code{PTR + INDEX}).
6134 @end deffn
6136 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
6137 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6138 @c 
6139 @c This is free software: you can redistribute it and/or modify it
6140 @c under the terms of the GNU General Public License as published by
6141 @c the Free Software Foundation, either version 3 of the License, or
6142 @c (at your option) any later version.
6143 @c 
6144 @c This program is distributed in the hope that it will be useful, but
6145 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6146 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6147 @c General Public License for more details.
6148 @c 
6149 @c You should have received a copy of the GNU General Public License
6150 @c along with this program.  If not, see
6151 @c <http://www.gnu.org/licenses/>.
6153 @node Creating and using functions,Source Locations,Expressions,Topic Reference
6154 @anchor{topics/functions doc}@anchor{b0}@anchor{topics/functions creating-and-using-functions}@anchor{b1}
6155 @section Creating and using functions
6158 @menu
6159 * Params:: 
6160 * Functions:: 
6161 * Blocks:: 
6162 * Statements:: 
6164 @end menu
6166 @node Params,Functions,,Creating and using functions
6167 @anchor{topics/functions params}@anchor{b2}
6168 @subsection Params
6171 @geindex gcc_jit_param (C type)
6172 @anchor{topics/functions gcc_jit_param}@anchor{25}
6173 @deffn {C Type} gcc_jit_param
6175 A @cite{gcc_jit_param} represents a parameter to a function.
6176 @end deffn
6178 @geindex gcc_jit_context_new_param (C function)
6179 @anchor{topics/functions gcc_jit_context_new_param}@anchor{10}
6180 @deffn {C Function} gcc_jit_param *           gcc_jit_context_new_param (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, gcc_jit_type@w{ }*type, const char@w{ }*name)
6182 In preparation for creating a function, create a new parameter of the
6183 given type and name.
6184 @end deffn
6186 Parameters are lvalues, and thus are also rvalues (and objects), so the
6187 following upcasts are available:
6189 @geindex gcc_jit_param_as_lvalue (C function)
6190 @anchor{topics/functions gcc_jit_param_as_lvalue}@anchor{b3}
6191 @deffn {C Function} gcc_jit_lvalue *            gcc_jit_param_as_lvalue (gcc_jit_param@w{ }*param)
6193 Upcasting from param to lvalue.
6194 @end deffn
6196 @geindex gcc_jit_param_as_rvalue (C function)
6197 @anchor{topics/functions gcc_jit_param_as_rvalue}@anchor{b4}
6198 @deffn {C Function} gcc_jit_rvalue *            gcc_jit_param_as_rvalue (gcc_jit_param@w{ }*param)
6200 Upcasting from param to rvalue.
6201 @end deffn
6203 @geindex gcc_jit_param_as_object (C function)
6204 @anchor{topics/functions gcc_jit_param_as_object}@anchor{b5}
6205 @deffn {C Function} gcc_jit_object *            gcc_jit_param_as_object (gcc_jit_param@w{ }*param)
6207 Upcasting from param to object.
6208 @end deffn
6210 @node Functions,Blocks,Params,Creating and using functions
6211 @anchor{topics/functions functions}@anchor{b6}
6212 @subsection Functions
6215 @geindex gcc_jit_function (C type)
6216 @anchor{topics/functions gcc_jit_function}@anchor{29}
6217 @deffn {C Type} gcc_jit_function
6219 A @cite{gcc_jit_function} represents a function - either one that we're
6220 creating ourselves, or one that we're referencing.
6221 @end deffn
6223 @geindex gcc_jit_context_new_function (C function)
6224 @anchor{topics/functions gcc_jit_context_new_function}@anchor{11}
6225 @deffn {C Function} gcc_jit_function *            gcc_jit_context_new_function (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, enum gcc_jit_function_kind@w{ }kind, gcc_jit_type@w{ }*return_type, const char@w{ }*name, int@w{ }num_params, gcc_jit_param@w{ }**params, int@w{ }is_variadic)
6227 Create a gcc_jit_function with the given name and parameters.
6229 @geindex gcc_jit_function_kind (C type)
6230 @anchor{topics/functions gcc_jit_function_kind}@anchor{b7}
6231 @deffn {C Type} enum gcc_jit_function_kind
6232 @end deffn
6234 This enum controls the kind of function created, and has the following
6235 values:
6237 @quotation
6239 @geindex GCC_JIT_FUNCTION_EXPORTED (C macro)
6240 @anchor{topics/functions GCC_JIT_FUNCTION_EXPORTED}@anchor{b8}
6241 @deffn {C Macro} GCC_JIT_FUNCTION_EXPORTED
6243 Function is defined by the client code and visible
6244 by name outside of the JIT.
6246 This value is required if you want to extract machine code
6247 for this function from a @pxref{16,,gcc_jit_result} via
6248 @pxref{17,,gcc_jit_result_get_code()}.
6249 @end deffn
6251 @geindex GCC_JIT_FUNCTION_INTERNAL (C macro)
6252 @anchor{topics/functions GCC_JIT_FUNCTION_INTERNAL}@anchor{b9}
6253 @deffn {C Macro} GCC_JIT_FUNCTION_INTERNAL
6255 Function is defined by the client code, but is invisible
6256 outside of the JIT.  Analogous to a "static" function.
6257 @end deffn
6259 @geindex GCC_JIT_FUNCTION_IMPORTED (C macro)
6260 @anchor{topics/functions GCC_JIT_FUNCTION_IMPORTED}@anchor{ba}
6261 @deffn {C Macro} GCC_JIT_FUNCTION_IMPORTED
6263 Function is not defined by the client code; we're merely
6264 referring to it.  Analogous to using an "extern" function from a
6265 header file.
6266 @end deffn
6268 @geindex GCC_JIT_FUNCTION_ALWAYS_INLINE (C macro)
6269 @anchor{topics/functions GCC_JIT_FUNCTION_ALWAYS_INLINE}@anchor{bb}
6270 @deffn {C Macro} GCC_JIT_FUNCTION_ALWAYS_INLINE
6272 Function is only ever inlined into other functions, and is
6273 invisible outside of the JIT.
6275 Analogous to prefixing with @code{inline} and adding
6276 @code{__attribute__((always_inline))}
6278 Inlining will only occur when the optimization level is
6279 above 0; when optimization is off, this is essentially the
6280 same as GCC_JIT_FUNCTION_INTERNAL.
6281 @end deffn
6282 @end quotation
6283 @end deffn
6285 @geindex gcc_jit_context_get_builtin_function (C function)
6286 @anchor{topics/functions gcc_jit_context_get_builtin_function}@anchor{bc}
6287 @deffn {C Function} gcc_jit_function *gcc_jit_context_get_builtin_function (gcc_jit_context@w{ }*ctxt, const char@w{ }*name)
6288 @end deffn
6290 @geindex gcc_jit_function_as_object (C function)
6291 @anchor{topics/functions gcc_jit_function_as_object}@anchor{bd}
6292 @deffn {C Function} gcc_jit_object *           gcc_jit_function_as_object (gcc_jit_function@w{ }*func)
6294 Upcasting from function to object.
6295 @end deffn
6297 @geindex gcc_jit_function_get_param (C function)
6298 @anchor{topics/functions gcc_jit_function_get_param}@anchor{be}
6299 @deffn {C Function} gcc_jit_param *            gcc_jit_function_get_param (gcc_jit_function@w{ }*func, int@w{ }index)
6301 Get the param of the given index (0-based).
6302 @end deffn
6304 @geindex gcc_jit_function_dump_to_dot (C function)
6305 @anchor{topics/functions gcc_jit_function_dump_to_dot}@anchor{33}
6306 @deffn {C Function} void             gcc_jit_function_dump_to_dot (gcc_jit_function@w{ }*func, const char@w{ }*path)
6308 Emit the function in graphviz format to the given path.
6309 @end deffn
6311 @geindex gcc_jit_function_new_local (C function)
6312 @anchor{topics/functions gcc_jit_function_new_local}@anchor{26}
6313 @deffn {C Function} gcc_jit_lvalue *           gcc_jit_function_new_local (gcc_jit_function@w{ }*func, gcc_jit_location@w{ }*loc, gcc_jit_type@w{ }*type, const char@w{ }*name)
6315 Create a new local variable within the function, of the given type and
6316 name.
6317 @end deffn
6319 @node Blocks,Statements,Functions,Creating and using functions
6320 @anchor{topics/functions blocks}@anchor{bf}
6321 @subsection Blocks
6324 @geindex gcc_jit_block (C type)
6325 @anchor{topics/functions gcc_jit_block}@anchor{28}
6326 @deffn {C Type} gcc_jit_block
6328 A @cite{gcc_jit_block} represents a basic block within a function  i.e. a
6329 sequence of statements with a single entry point and a single exit
6330 point.
6332 The first basic block that you create within a function will
6333 be the entrypoint.
6335 Each basic block that you create within a function must be
6336 terminated, either with a conditional, a jump, or a return.
6338 It's legal to have multiple basic blocks that return within
6339 one function.
6340 @end deffn
6342 @geindex gcc_jit_function_new_block (C function)
6343 @anchor{topics/functions gcc_jit_function_new_block}@anchor{c0}
6344 @deffn {C Function} gcc_jit_block *            gcc_jit_function_new_block (gcc_jit_function@w{ }*func, const char@w{ }*name)
6346 Create a basic block of the given name.  The name may be NULL, but
6347 providing meaningful names is often helpful when debugging: it may
6348 show up in dumps of the internal representation, and in error
6349 messages.
6350 @end deffn
6352 @geindex gcc_jit_block_as_object (C function)
6353 @anchor{topics/functions gcc_jit_block_as_object}@anchor{c1}
6354 @deffn {C Function} gcc_jit_object *            gcc_jit_block_as_object (gcc_jit_block@w{ }*block)
6356 Upcast from block to object.
6357 @end deffn
6359 @geindex gcc_jit_block_get_function (C function)
6360 @anchor{topics/functions gcc_jit_block_get_function}@anchor{c2}
6361 @deffn {C Function} gcc_jit_function *            gcc_jit_block_get_function (gcc_jit_block@w{ }*block)
6363 Which function is this block within?
6364 @end deffn
6366 @node Statements,,Blocks,Creating and using functions
6367 @anchor{topics/functions statements}@anchor{c3}
6368 @subsection Statements
6371 @geindex gcc_jit_block_add_eval (C function)
6372 @anchor{topics/functions gcc_jit_block_add_eval}@anchor{9d}
6373 @deffn {C Function} void           gcc_jit_block_add_eval (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, gcc_jit_rvalue@w{ }*rvalue)
6375 Add evaluation of an rvalue, discarding the result
6376 (e.g. a function call that "returns" void).
6378 This is equivalent to this C code:
6380 @example
6381 (void)expression;
6382 @end example
6384 @noindent
6385 @end deffn
6387 @geindex gcc_jit_block_add_assignment (C function)
6388 @anchor{topics/functions gcc_jit_block_add_assignment}@anchor{2a}
6389 @deffn {C Function} void           gcc_jit_block_add_assignment (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, gcc_jit_lvalue@w{ }*lvalue, gcc_jit_rvalue@w{ }*rvalue)
6391 Add evaluation of an rvalue, assigning the result to the given
6392 lvalue.
6394 This is roughly equivalent to this C code:
6396 @example
6397 lvalue = rvalue;
6398 @end example
6400 @noindent
6401 @end deffn
6403 @geindex gcc_jit_block_add_assignment_op (C function)
6404 @anchor{topics/functions gcc_jit_block_add_assignment_op}@anchor{2e}
6405 @deffn {C Function} void           gcc_jit_block_add_assignment_op (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, gcc_jit_lvalue@w{ }*lvalue, enum gcc_jit_binary_op@w{ }op, gcc_jit_rvalue@w{ }*rvalue)
6407 Add evaluation of an rvalue, using the result to modify an
6408 lvalue.
6410 This is analogous to "+=" and friends:
6412 @example
6413 lvalue += rvalue;
6414 lvalue *= rvalue;
6415 lvalue /= rvalue;
6416 @end example
6418 @noindent
6420 etc.  For example:
6422 @example
6423 /* "i++" */
6424 gcc_jit_block_add_assignment_op (
6425   loop_body, NULL,
6426   i,
6427   GCC_JIT_BINARY_OP_PLUS,
6428   gcc_jit_context_one (ctxt, int_type));
6429 @end example
6431 @noindent
6432 @end deffn
6434 @geindex gcc_jit_block_add_comment (C function)
6435 @anchor{topics/functions gcc_jit_block_add_comment}@anchor{3d}
6436 @deffn {C Function} void           gcc_jit_block_add_comment (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, const char@w{ }*text)
6438 Add a no-op textual comment to the internal representation of the
6439 code.  It will be optimized away, but will be visible in the dumps
6440 seen via @pxref{5f,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE}
6441 and @pxref{1c,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE},
6442 and thus may be of use when debugging how your project's internal
6443 representation gets converted to the libgccjit IR.
6444 @end deffn
6446 @geindex gcc_jit_block_end_with_conditional (C function)
6447 @anchor{topics/functions gcc_jit_block_end_with_conditional}@anchor{2d}
6448 @deffn {C Function} void           gcc_jit_block_end_with_conditional (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, gcc_jit_rvalue@w{ }*boolval, gcc_jit_block@w{ }*on_true, gcc_jit_block@w{ }*on_false)
6450 Terminate a block by adding evaluation of an rvalue, branching on the
6451 result to the appropriate successor block.
6453 This is roughly equivalent to this C code:
6455 @example
6456 if (boolval)
6457   goto on_true;
6458 else
6459   goto on_false;
6460 @end example
6462 @noindent
6464 block, boolval, on_true, and on_false must be non-NULL.
6465 @end deffn
6467 @geindex gcc_jit_block_end_with_jump (C function)
6468 @anchor{topics/functions gcc_jit_block_end_with_jump}@anchor{c4}
6469 @deffn {C Function} void           gcc_jit_block_end_with_jump (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, gcc_jit_block@w{ }*target)
6471 Terminate a block by adding a jump to the given target block.
6473 This is roughly equivalent to this C code:
6475 @example
6476 goto target;
6477 @end example
6479 @noindent
6480 @end deffn
6482 @geindex gcc_jit_block_end_with_return (C function)
6483 @anchor{topics/functions gcc_jit_block_end_with_return}@anchor{c5}
6484 @deffn {C Function} void           gcc_jit_block_end_with_return (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, gcc_jit_rvalue@w{ }*rvalue)
6486 Terminate a block by adding evaluation of an rvalue, returning the value.
6488 This is roughly equivalent to this C code:
6490 @example
6491 return expression;
6492 @end example
6494 @noindent
6495 @end deffn
6497 @geindex gcc_jit_block_end_with_void_return (C function)
6498 @anchor{topics/functions gcc_jit_block_end_with_void_return}@anchor{c6}
6499 @deffn {C Function} void           gcc_jit_block_end_with_void_return (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc)
6501 Terminate a block by adding a valueless return, for use within a function
6502 with "void" return type.
6504 This is equivalent to this C code:
6506 @example
6507 return;
6508 @end example
6510 @noindent
6511 @end deffn
6513 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
6514 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6515 @c 
6516 @c This is free software: you can redistribute it and/or modify it
6517 @c under the terms of the GNU General Public License as published by
6518 @c the Free Software Foundation, either version 3 of the License, or
6519 @c (at your option) any later version.
6520 @c 
6521 @c This program is distributed in the hope that it will be useful, but
6522 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6523 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6524 @c General Public License for more details.
6525 @c 
6526 @c You should have received a copy of the GNU General Public License
6527 @c along with this program.  If not, see
6528 @c <http://www.gnu.org/licenses/>.
6530 @node Source Locations,Compilation results,Creating and using functions,Topic Reference
6531 @anchor{topics/locations source-locations}@anchor{c7}@anchor{topics/locations doc}@anchor{c8}
6532 @section Source Locations
6535 @geindex gcc_jit_location (C type)
6536 @anchor{topics/locations gcc_jit_location}@anchor{3b}
6537 @deffn {C Type} gcc_jit_location
6539 A @cite{gcc_jit_location} encapsulates a source code location, so that
6540 you can (optionally) associate locations in your language with
6541 statements in the JIT-compiled code, allowing the debugger to
6542 single-step through your language.
6544 @cite{gcc_jit_location} instances are optional: you can always pass NULL to
6545 any API entrypoint accepting one.
6547 You can construct them using @pxref{41,,gcc_jit_context_new_location()}.
6549 You need to enable @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} on the
6550 @pxref{8,,gcc_jit_context} for these locations to actually be usable by
6551 the debugger:
6553 @example
6554 gcc_jit_context_set_bool_option (
6555   ctxt,
6556   GCC_JIT_BOOL_OPTION_DEBUGINFO,
6557   1);
6558 @end example
6560 @noindent
6561 @end deffn
6563 @geindex gcc_jit_context_new_location (C function)
6564 @anchor{topics/locations gcc_jit_context_new_location}@anchor{41}
6565 @deffn {C Function} gcc_jit_location *           gcc_jit_context_new_location (gcc_jit_context@w{ }*ctxt, const char@w{ }*filename, int@w{ }line, int@w{ }column)
6567 Create a @cite{gcc_jit_location} instance representing the given source
6568 location.
6569 @end deffn
6571 @menu
6572 * Faking it:: 
6574 @end menu
6576 @node Faking it,,,Source Locations
6577 @anchor{topics/locations faking-it}@anchor{c9}
6578 @subsection Faking it
6581 If you don't have source code for your internal representation, but need
6582 to debug, you can generate a C-like representation of the functions in
6583 your context using @pxref{53,,gcc_jit_context_dump_to_file()}:
6585 @example
6586 gcc_jit_context_dump_to_file (ctxt, "/tmp/something.c",
6587                               1 /* update_locations */);
6588 @end example
6590 @noindent
6592 This will dump C-like code to the given path.  If the @cite{update_locations}
6593 argument is true, this will also set up @cite{gcc_jit_location} information
6594 throughout the context, pointing at the dump file as if it were a source
6595 file, giving you @emph{something} you can step through in the debugger.
6597 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
6598 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6599 @c 
6600 @c This is free software: you can redistribute it and/or modify it
6601 @c under the terms of the GNU General Public License as published by
6602 @c the Free Software Foundation, either version 3 of the License, or
6603 @c (at your option) any later version.
6604 @c 
6605 @c This program is distributed in the hope that it will be useful, but
6606 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6607 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6608 @c General Public License for more details.
6609 @c 
6610 @c You should have received a copy of the GNU General Public License
6611 @c along with this program.  If not, see
6612 @c <http://www.gnu.org/licenses/>.
6614 @node Compilation results,,Source Locations,Topic Reference
6615 @anchor{topics/results compilation-results}@anchor{ca}@anchor{topics/results doc}@anchor{cb}
6616 @section Compilation results
6619 @geindex gcc_jit_result (C type)
6620 @anchor{topics/results gcc_jit_result}@anchor{16}
6621 @deffn {C Type} gcc_jit_result
6623 A @cite{gcc_jit_result} encapsulates the result of compiling a context,
6624 and the lifetimes of any machine code functions or globals that are
6625 within it.
6626 @end deffn
6628 @geindex gcc_jit_context_compile (C function)
6629 @anchor{topics/results gcc_jit_context_compile}@anchor{15}
6630 @deffn {C Function} gcc_jit_result *           gcc_jit_context_compile (gcc_jit_context@w{ }*ctxt)
6632 This calls into GCC and builds the code, returning a
6633 @cite{gcc_jit_result *}.
6635 If this is non-NULL, the caller becomes responsible for
6636 calling @pxref{39,,gcc_jit_result_release()} on it once they're done
6637 with it.
6638 @end deffn
6640 @geindex gcc_jit_result_get_code (C function)
6641 @anchor{topics/results gcc_jit_result_get_code}@anchor{17}
6642 @deffn {C Function} void *           gcc_jit_result_get_code (gcc_jit_result@w{ }*result, const char@w{ }*funcname)
6644 Locate a given function within the built machine code.
6646 Functions are looked up by name.  For this to succeed, a function
6647 with a name matching @cite{funcname} must have been created on
6648 @cite{result}'s context (or a parent context) via a call to
6649 @pxref{11,,gcc_jit_context_new_function()} with @cite{kind}
6650 @pxref{b8,,GCC_JIT_FUNCTION_EXPORTED}:
6652 @example
6653 gcc_jit_context_new_function (ctxt,
6654                               any_location, /* or NULL */
6655                               /* Required for func to be visible to
6656                                  gcc_jit_result_get_code: */
6657                               GCC_JIT_FUNCTION_EXPORTED,
6658                               any_return_type,
6659                               /* Must string-compare equal: */
6660                               funcname,
6661                               /* etc */);
6662 @end example
6664 @noindent
6666 If such a function is not found (or @cite{result} or @cite{funcname} are
6667 @code{NULL}), an error message will be emitted on stderr and
6668 @code{NULL} will be returned.
6670 If the function is found, the result will need to be cast to a
6671 function pointer of the correct type before it can be called.
6673 Note that the resulting machine code becomes invalid after
6674 @pxref{39,,gcc_jit_result_release()} is called on the
6675 @pxref{16,,gcc_jit_result *}; attempting to call it after that may lead
6676 to a segmentation fault.
6677 @end deffn
6679 @geindex gcc_jit_result_get_global (C function)
6680 @anchor{topics/results gcc_jit_result_get_global}@anchor{a8}
6681 @deffn {C Function} void *           gcc_jit_result_get_global (gcc_jit_result@w{ }*result, const char@w{ }*name)
6683 Locate a given global within the built machine code.
6685 Globals are looked up by name.  For this to succeed, a global
6686 with a name matching @cite{name} must have been created on
6687 @cite{result}'s context (or a parent context) via a call to
6688 @pxref{a5,,gcc_jit_context_new_global()} with @cite{kind}
6689 @pxref{a7,,GCC_JIT_GLOBAL_EXPORTED}.
6691 If the global is found, the result will need to be cast to a
6692 pointer of the correct type before it can be called.
6694 This is a @emph{pointer} to the global, so e.g. for an @code{int} this is
6695 an @code{int *}.
6697 For example, given an @code{int foo;} created this way:
6699 @example
6700 gcc_jit_lvalue *exported_global =
6701   gcc_jit_context_new_global (ctxt,
6702   any_location, /* or NULL */
6703   GCC_JIT_GLOBAL_EXPORTED,
6704   int_type,
6705   "foo");
6706 @end example
6708 @noindent
6710 we can access it like this:
6712 @example
6713 int *ptr_to_foo =
6714   (int *)gcc_jit_result_get_global (result, "foo");
6715 @end example
6717 @noindent
6719 If such a global is not found (or @cite{result} or @cite{name} are
6720 @code{NULL}), an error message will be emitted on stderr and
6721 @code{NULL} will be returned.
6723 Note that the resulting address becomes invalid after
6724 @pxref{39,,gcc_jit_result_release()} is called on the
6725 @pxref{16,,gcc_jit_result *}; attempting to use it after that may lead
6726 to a segmentation fault.
6727 @end deffn
6729 @geindex gcc_jit_result_release (C function)
6730 @anchor{topics/results gcc_jit_result_release}@anchor{39}
6731 @deffn {C Function} void           gcc_jit_result_release (gcc_jit_result@w{ }*result)
6733 Once we're done with the code, this unloads the built .so file.
6734 This cleans up the result; after calling this, it's no longer
6735 valid to use the result, or any code or globals that were obtained
6736 by calling @pxref{17,,gcc_jit_result_get_code()} or
6737 @pxref{a8,,gcc_jit_result_get_global()} on it.
6738 @end deffn
6740 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
6741 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6742 @c 
6743 @c This is free software: you can redistribute it and/or modify it
6744 @c under the terms of the GNU General Public License as published by
6745 @c the Free Software Foundation, either version 3 of the License, or
6746 @c (at your option) any later version.
6747 @c 
6748 @c This program is distributed in the hope that it will be useful, but
6749 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6750 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6751 @c General Public License for more details.
6752 @c 
6753 @c You should have received a copy of the GNU General Public License
6754 @c along with this program.  If not, see
6755 @c <http://www.gnu.org/licenses/>.
6757 @node C++ bindings for libgccjit,Internals,Topic Reference,Top
6758 @anchor{cp/index c-bindings-for-libgccjit}@anchor{cc}@anchor{cp/index doc}@anchor{cd}
6759 @chapter C++ bindings for libgccjit
6762 This document describes the C++ bindings to
6763 libgccjit@footnote{http://gcc.gnu.org/wiki/JIT}, an API for embedding GCC
6764 inside programs and libraries.
6766 The C++ bindings consist of a single header file @code{libgccjit++.h}.
6768 This is a collection of "thin" wrapper classes around the C API.
6769 Everything is an inline function, implemented in terms of the C API,
6770 so there is nothing extra to link against.
6772 Note that libgccjit is currently of "Alpha" quality;
6773 the APIs are not yet set in stone, and they shouldn't be used in
6774 production yet.
6776 Contents:
6778 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
6779 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6780 @c 
6781 @c This is free software: you can redistribute it and/or modify it
6782 @c under the terms of the GNU General Public License as published by
6783 @c the Free Software Foundation, either version 3 of the License, or
6784 @c (at your option) any later version.
6785 @c 
6786 @c This program is distributed in the hope that it will be useful, but
6787 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6788 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6789 @c General Public License for more details.
6790 @c 
6791 @c You should have received a copy of the GNU General Public License
6792 @c along with this program.  If not, see
6793 @c <http://www.gnu.org/licenses/>.
6795 @menu
6796 * Tutorial: Tutorial<2>. 
6797 * Topic Reference: Topic Reference<2>. 
6799 Tutorial
6801 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world"<2>. 
6802 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function<2>. 
6803 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables<2>. 
6804 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>. 
6806 Tutorial part 2: Creating a trivial machine code function
6808 * Options: Options<3>. 
6809 * Full example: Full example<3>. 
6811 Tutorial part 3: Loops and variables
6813 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues<2>. 
6814 * Control flow: Control flow<2>. 
6815 * Visualizing the control flow graph: Visualizing the control flow graph<2>. 
6816 * Full example: Full example<4>. 
6818 Tutorial part 4: Adding JIT-compilation to a toy interpreter
6820 * Our toy interpreter: Our toy interpreter<2>. 
6821 * Compiling to machine code: Compiling to machine code<2>. 
6822 * Setting things up: Setting things up<2>. 
6823 * Populating the function: Populating the function<2>. 
6824 * Verifying the control flow graph: Verifying the control flow graph<2>. 
6825 * Compiling the context: Compiling the context<2>. 
6826 * Single-stepping through the generated code: Single-stepping through the generated code<2>. 
6827 * Examining the generated code: Examining the generated code<2>. 
6828 * Putting it all together: Putting it all together<2>. 
6829 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?<2>. 
6831 Behind the curtain: How does our code get optimized?
6833 * Optimizing away stack manipulation: Optimizing away stack manipulation<2>. 
6834 * Elimination of tail recursion: Elimination of tail recursion<2>. 
6836 Topic Reference
6838 * Compilation contexts: Compilation contexts<2>. 
6839 * Objects: Objects<2>. 
6840 * Types: Types<2>. 
6841 * Expressions: Expressions<2>. 
6842 * Creating and using functions: Creating and using functions<2>. 
6843 * Source Locations: Source Locations<2>. 
6844 * Compilation results: Compilation results<2>. 
6846 Compilation contexts
6848 * Lifetime-management: Lifetime-management<2>. 
6849 * Thread-safety: Thread-safety<2>. 
6850 * Error-handling: Error-handling<3>. 
6851 * Debugging: Debugging<2>. 
6852 * Options: Options<4>. 
6854 Options
6856 * String Options: String Options<2>. 
6857 * Boolean options: Boolean options<2>. 
6858 * Integer options: Integer options<2>. 
6860 Types
6862 * Standard types: Standard types<2>. 
6863 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile<2>. 
6864 * Structures and unions: Structures and unions<2>. 
6866 Expressions
6868 * Rvalues: Rvalues<2>. 
6869 * Lvalues: Lvalues<2>. 
6870 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions<2>. 
6872 Rvalues
6874 * Simple expressions: Simple expressions<2>. 
6875 * Unary Operations: Unary Operations<2>. 
6876 * Binary Operations: Binary Operations<2>. 
6877 * Comparisons: Comparisons<2>. 
6878 * Function calls: Function calls<2>. 
6879 * Type-coercion: Type-coercion<2>. 
6881 Lvalues
6883 * Global variables: Global variables<2>. 
6885 Creating and using functions
6887 * Params: Params<2>. 
6888 * Functions: Functions<2>. 
6889 * Blocks: Blocks<2>. 
6890 * Statements: Statements<2>. 
6892 Source Locations
6894 * Faking it: Faking it<2>. 
6896 @end menu
6899 @node Tutorial<2>,Topic Reference<2>,,C++ bindings for libgccjit
6900 @anchor{cp/intro/index doc}@anchor{ce}@anchor{cp/intro/index tutorial}@anchor{cf}
6901 @section Tutorial
6904 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
6905 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6906 @c 
6907 @c This is free software: you can redistribute it and/or modify it
6908 @c under the terms of the GNU General Public License as published by
6909 @c the Free Software Foundation, either version 3 of the License, or
6910 @c (at your option) any later version.
6911 @c 
6912 @c This program is distributed in the hope that it will be useful, but
6913 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6914 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6915 @c General Public License for more details.
6916 @c 
6917 @c You should have received a copy of the GNU General Public License
6918 @c along with this program.  If not, see
6919 @c <http://www.gnu.org/licenses/>.
6921 @menu
6922 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world"<2>. 
6923 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function<2>. 
6924 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables<2>. 
6925 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>. 
6927 @end menu
6929 @node Tutorial part 1 "Hello world"<2>,Tutorial part 2 Creating a trivial machine code function<2>,,Tutorial<2>
6930 @anchor{cp/intro/tutorial01 doc}@anchor{d0}@anchor{cp/intro/tutorial01 tutorial-part-1-hello-world}@anchor{d1}
6931 @subsection Tutorial part 1: "Hello world"
6934 Before we look at the details of the API, let's look at building and
6935 running programs that use the library.
6937 Here's a toy "hello world" program that uses the library's C++ API to
6938 synthesize a call to @cite{printf} and uses it to write a message to stdout.
6940 Don't worry about the content of the program for now; we'll cover
6941 the details in later parts of this tutorial.
6943 @quotation
6945 @example
6946 /* Smoketest example for libgccjit.so C++ API
6947    Copyright (C) 2014-2015 Free Software Foundation, Inc.
6949 This file is part of GCC.
6951 GCC is free software; you can redistribute it and/or modify it
6952 under the terms of the GNU General Public License as published by
6953 the Free Software Foundation; either version 3, or (at your option)
6954 any later version.
6956 GCC is distributed in the hope that it will be useful, but
6957 WITHOUT ANY WARRANTY; without even the implied warranty of
6958 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6959 General Public License for more details.
6961 You should have received a copy of the GNU General Public License
6962 along with GCC; see the file COPYING3.  If not see
6963 <http://www.gnu.org/licenses/>.  */
6965 #include <libgccjit++.h>
6967 #include <stdlib.h>
6968 #include <stdio.h>
6970 static void
6971 create_code (gccjit::context ctxt)
6973   /* Let's try to inject the equivalent of this C code:
6974      void
6975      greet (const char *name)
6976      @{
6977         printf ("hello %s\n", name);
6978      @}
6979   */
6980   gccjit::type void_type = ctxt.get_type (GCC_JIT_TYPE_VOID);
6981   gccjit::type const_char_ptr_type =
6982     ctxt.get_type (GCC_JIT_TYPE_CONST_CHAR_PTR);
6983   gccjit::param param_name =
6984     ctxt.new_param (const_char_ptr_type, "name");
6985   std::vector<gccjit::param> func_params;
6986   func_params.push_back (param_name);
6987   gccjit::function func =
6988     ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
6989                        void_type,
6990                        "greet",
6991                        func_params, 0);
6993   gccjit::param param_format =
6994     ctxt.new_param (const_char_ptr_type, "format");
6995   std::vector<gccjit::param> printf_params;
6996   printf_params.push_back (param_format);
6997   gccjit::function printf_func =
6998     ctxt.new_function (GCC_JIT_FUNCTION_IMPORTED,
6999                        ctxt.get_type (GCC_JIT_TYPE_INT),
7000                        "printf",
7001                        printf_params, 1);
7003   gccjit::block block = func.new_block ();
7004   block.add_eval (ctxt.new_call (printf_func,
7005                                  ctxt.new_rvalue ("hello %s\n"),
7006                                  param_name));
7007   block.end_with_return ();
7011 main (int argc, char **argv)
7013   gccjit::context ctxt;
7014   gcc_jit_result *result;
7016   /* Get a "context" object for working with the library.  */
7017   ctxt = gccjit::context::acquire ();
7019   /* Set some options on the context.
7020      Turn this on to see the code being generated, in assembler form.  */
7021   ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE, 0);
7023   /* Populate the context.  */
7024   create_code (ctxt);
7026   /* Compile the code.  */
7027   result = ctxt.compile ();
7028   if (!result)
7029     @{
7030       fprintf (stderr, "NULL result");
7031       exit (1);
7032     @}
7034   ctxt.release ();
7036   /* Extract the generated code from "result".  */
7037   typedef void (*fn_type) (const char *);
7038   fn_type greet =
7039     (fn_type)gcc_jit_result_get_code (result, "greet");
7040   if (!greet)
7041     @{
7042       fprintf (stderr, "NULL greet");
7043       exit (1);
7044     @}
7046   /* Now call the generated function: */
7047   greet ("world");
7048   fflush (stdout);
7050   gcc_jit_result_release (result);
7051   return 0;
7054 @end example
7056 @noindent
7057 @end quotation
7059 Copy the above to @cite{tut01-hello-world.cc}.
7061 Assuming you have the jit library installed, build the test program
7062 using:
7064 @example
7065 $ gcc \
7066     tut01-hello-world.cc \
7067     -o tut01-hello-world \
7068     -lgccjit
7069 @end example
7071 @noindent
7073 You should then be able to run the built program:
7075 @example
7076 $ ./tut01-hello-world
7077 hello world
7078 @end example
7080 @noindent
7082 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
7083 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
7084 @c 
7085 @c This is free software: you can redistribute it and/or modify it
7086 @c under the terms of the GNU General Public License as published by
7087 @c the Free Software Foundation, either version 3 of the License, or
7088 @c (at your option) any later version.
7089 @c 
7090 @c This program is distributed in the hope that it will be useful, but
7091 @c WITHOUT ANY WARRANTY; without even the implied warranty of
7092 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
7093 @c General Public License for more details.
7094 @c 
7095 @c You should have received a copy of the GNU General Public License
7096 @c along with this program.  If not, see
7097 @c <http://www.gnu.org/licenses/>.
7099 @node Tutorial part 2 Creating a trivial machine code function<2>,Tutorial part 3 Loops and variables<2>,Tutorial part 1 "Hello world"<2>,Tutorial<2>
7100 @anchor{cp/intro/tutorial02 doc}@anchor{d2}@anchor{cp/intro/tutorial02 tutorial-part-2-creating-a-trivial-machine-code-function}@anchor{d3}
7101 @subsection Tutorial part 2: Creating a trivial machine code function
7104 Consider this C function:
7106 @example
7107 int square (int i)
7109   return i * i;
7111 @end example
7113 @noindent
7115 How can we construct this at run-time using libgccjit's C++ API?
7117 First we need to include the relevant header:
7119 @example
7120 #include <libgccjit++.h>
7121 @end example
7123 @noindent
7125 All state associated with compilation is associated with a
7126 @code{gccjit::context}, which is a thin C++ wrapper around the C API's
7127 @pxref{8,,gcc_jit_context *}.
7129 Create one using @pxref{d4,,gccjit;;context;;acquire()}:
7131 @example
7132 gccjit::context ctxt;
7133 ctxt = gccjit::context::acquire ();
7134 @end example
7136 @noindent
7138 The JIT library has a system of types.  It is statically-typed: every
7139 expression is of a specific type, fixed at compile-time.  In our example,
7140 all of the expressions are of the C @cite{int} type, so let's obtain this from
7141 the context, as a @code{gccjit::type}, using
7142 @pxref{d5,,gccjit;;context;;get_type()}:
7144 @example
7145 gccjit::type int_type = ctxt.get_type (GCC_JIT_TYPE_INT);
7146 @end example
7148 @noindent
7150 @code{gccjit::type} is an example of a "contextual" object: every
7151 entity in the API is associated with a @code{gccjit::context}.
7153 Memory management is easy: all such "contextual" objects are automatically
7154 cleaned up for you when the context is released, using
7155 @pxref{d6,,gccjit;;context;;release()}:
7157 @example
7158 ctxt.release ();
7159 @end example
7161 @noindent
7163 so you don't need to manually track and cleanup all objects, just the
7164 contexts.
7166 All of the C++ classes in the API are thin wrappers around pointers to
7167 types in the C API.
7169 The C++ class hierarchy within the @code{gccjit} namespace looks like this:
7171 @example
7172 +- object
7173     +- location
7174     +- type
7175        +- struct
7176     +- field
7177     +- function
7178     +- block
7179     +- rvalue
7180         +- lvalue
7181            +- param
7182 @end example
7184 @noindent
7186 One thing you can do with a @code{gccjit::object} is
7187 to ask it for a human-readable description as a @code{std::string}, using
7188 @pxref{d7,,gccjit;;object;;get_debug_string()}:
7190 @example
7191 printf ("obj: %s\n", obj.get_debug_string ().c_str ());
7192 @end example
7194 @noindent
7196 giving this text on stdout:
7198 @example
7199 obj: int
7200 @end example
7202 @noindent
7204 This is invaluable when debugging.
7206 Let's create the function.  To do so, we first need to construct
7207 its single parameter, specifying its type and giving it a name,
7208 using @pxref{d8,,gccjit;;context;;new_param()}:
7210 @example
7211 gccjit::param param_i = ctxt.new_param (int_type, "i");
7212 @end example
7214 @noindent
7216 and we can then make a vector of all of the params of the function,
7217 in this case just one:
7219 @example
7220 std::vector<gccjit::param> params;
7221 params.push_back (param_i);
7222 @end example
7224 @noindent
7226 Now we can create the function, using
7227 @code{gccjit::context::new_function()}:
7229 @example
7230 gccjit::function func =
7231   ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
7232                      int_type,
7233                      "square",
7234                      params,
7235                      0);
7236 @end example
7238 @noindent
7240 To define the code within the function, we must create basic blocks
7241 containing statements.
7243 Every basic block contains a list of statements, eventually terminated
7244 by a statement that either returns, or jumps to another basic block.
7246 Our function has no control-flow, so we just need one basic block:
7248 @example
7249 gccjit::block block = func.new_block ();
7250 @end example
7252 @noindent
7254 Our basic block is relatively simple: it immediately terminates by
7255 returning the value of an expression.
7257 We can build the expression using @pxref{d9,,gccjit;;context;;new_binary_op()}:
7259 @example
7260 gccjit::rvalue expr =
7261   ctxt.new_binary_op (
7262     GCC_JIT_BINARY_OP_MULT, int_type,
7263     param_i, param_i);
7264 @end example
7266 @noindent
7268 A @code{gccjit::rvalue} is another example of a
7269 @code{gccjit::object} subclass.  As before, we can print it with
7270 @pxref{d7,,gccjit;;object;;get_debug_string()}.
7272 @example
7273 printf ("expr: %s\n", expr.get_debug_string ().c_str ());
7274 @end example
7276 @noindent
7278 giving this output:
7280 @example
7281 expr: i * i
7282 @end example
7284 @noindent
7286 Note that @code{gccjit::rvalue} provides numerous overloaded operators
7287 which can be used to dramatically reduce the amount of typing needed.
7288 We can build the above binary operation more directly with this one-liner:
7290 @example
7291 gccjit::rvalue expr = param_i * param_i;
7292 @end example
7294 @noindent
7296 Creating the expression in itself doesn't do anything; we have to add
7297 this expression to a statement within the block.  In this case, we use it
7298 to build a return statement, which terminates the basic block:
7300 @example
7301 block.end_with_return (expr);
7302 @end example
7304 @noindent
7306 OK, we've populated the context.  We can now compile it using
7307 @pxref{da,,gccjit;;context;;compile()}:
7309 @example
7310 gcc_jit_result *result;
7311 result = ctxt.compile ();
7312 @end example
7314 @noindent
7316 and get a @pxref{16,,gcc_jit_result *}.
7318 We can now use @pxref{17,,gcc_jit_result_get_code()} to look up a specific
7319 machine code routine within the result, in this case, the function we
7320 created above.
7322 @example
7323 void *fn_ptr = gcc_jit_result_get_code (result, "square");
7324 if (!fn_ptr)
7325   @{
7326     fprintf (stderr, "NULL fn_ptr");
7327     goto error;
7328   @}
7329 @end example
7331 @noindent
7333 We can now cast the pointer to an appropriate function pointer type, and
7334 then call it:
7336 @example
7337 typedef int (*fn_type) (int);
7338 fn_type square = (fn_type)fn_ptr;
7339 printf ("result: %d", square (5));
7340 @end example
7342 @noindent
7344 @example
7345 result: 25
7346 @end example
7348 @noindent
7350 @menu
7351 * Options: Options<3>. 
7352 * Full example: Full example<3>. 
7354 @end menu
7356 @node Options<3>,Full example<3>,,Tutorial part 2 Creating a trivial machine code function<2>
7357 @anchor{cp/intro/tutorial02 options}@anchor{db}
7358 @subsubsection Options
7361 To get more information on what's going on, you can set debugging flags
7362 on the context using @pxref{dc,,gccjit;;context;;set_bool_option()}.
7364 @c (I'm deliberately not mentioning
7365 @c :c:macro:`GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE` here since I think
7366 @c it's probably more of use to implementors than to users)
7368 Setting @pxref{1c,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE} will dump a
7369 C-like representation to stderr when you compile (GCC's "GIMPLE"
7370 representation):
7372 @example
7373 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE, 1);
7374 result = ctxt.compile ();
7375 @end example
7377 @noindent
7379 @example
7380 square (signed int i)
7382   signed int D.260;
7384   entry:
7385   D.260 = i * i;
7386   return D.260;
7388 @end example
7390 @noindent
7392 We can see the generated machine code in assembler form (on stderr) by
7393 setting @pxref{1d,,GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE} on the context
7394 before compiling:
7396 @example
7397 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE, 1);
7398 result = ctxt.compile ();
7399 @end example
7401 @noindent
7403 @example
7404       .file   "fake.c"
7405       .text
7406       .globl  square
7407       .type   square, @@function
7408 square:
7409 .LFB6:
7410       .cfi_startproc
7411       pushq   %rbp
7412       .cfi_def_cfa_offset 16
7413       .cfi_offset 6, -16
7414       movq    %rsp, %rbp
7415       .cfi_def_cfa_register 6
7416       movl    %edi, -4(%rbp)
7417 .L14:
7418       movl    -4(%rbp), %eax
7419       imull   -4(%rbp), %eax
7420       popq    %rbp
7421       .cfi_def_cfa 7, 8
7422       ret
7423       .cfi_endproc
7424 .LFE6:
7425       .size   square, .-square
7426       .ident  "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)"
7427       .section       .note.GNU-stack,"",@@progbits
7428 @end example
7430 @noindent
7432 By default, no optimizations are performed, the equivalent of GCC's
7433 @cite{-O0} option.  We can turn things up to e.g. @cite{-O3} by calling
7434 @pxref{dd,,gccjit;;context;;set_int_option()} with
7435 @pxref{1f,,GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}:
7437 @example
7438 ctxt.set_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL, 3);
7439 @end example
7441 @noindent
7443 @example
7444       .file   "fake.c"
7445       .text
7446       .p2align 4,,15
7447       .globl  square
7448       .type   square, @@function
7449 square:
7450 .LFB7:
7451       .cfi_startproc
7452 .L16:
7453       movl    %edi, %eax
7454       imull   %edi, %eax
7455       ret
7456       .cfi_endproc
7457 .LFE7:
7458       .size   square, .-square
7459       .ident  "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)"
7460       .section        .note.GNU-stack,"",@@progbits
7461 @end example
7463 @noindent
7465 Naturally this has only a small effect on such a trivial function.
7467 @node Full example<3>,,Options<3>,Tutorial part 2 Creating a trivial machine code function<2>
7468 @anchor{cp/intro/tutorial02 full-example}@anchor{de}
7469 @subsubsection Full example
7472 Here's what the above looks like as a complete program:
7474 @quotation
7476 @example
7477 /* Usage example for libgccjit.so's C++ API
7478    Copyright (C) 2014-2015 Free Software Foundation, Inc.
7480 This file is part of GCC.
7482 GCC is free software; you can redistribute it and/or modify it
7483 under the terms of the GNU General Public License as published by
7484 the Free Software Foundation; either version 3, or (at your option)
7485 any later version.
7487 GCC is distributed in the hope that it will be useful, but
7488 WITHOUT ANY WARRANTY; without even the implied warranty of
7489 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
7490 General Public License for more details.
7492 You should have received a copy of the GNU General Public License
7493 along with GCC; see the file COPYING3.  If not see
7494 <http://www.gnu.org/licenses/>.  */
7496 #include <libgccjit++.h>
7498 #include <stdlib.h>
7499 #include <stdio.h>
7501 void
7502 create_code (gccjit::context ctxt)
7504   /* Let's try to inject the equivalent of this C code:
7506       int square (int i)
7507       @{
7508         return i * i;
7509       @}
7510   */
7511   gccjit::type int_type = ctxt.get_type (GCC_JIT_TYPE_INT);
7512   gccjit::param param_i = ctxt.new_param (int_type, "i");
7513   std::vector<gccjit::param> params;
7514   params.push_back (param_i);
7515   gccjit::function func = ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
7516                                              int_type,
7517                                              "square",
7518                                              params, 0);
7520   gccjit::block block = func.new_block ();
7522   gccjit::rvalue expr =
7523     ctxt.new_binary_op (GCC_JIT_BINARY_OP_MULT, int_type,
7524                         param_i, param_i);
7526   block.end_with_return (expr);
7530 main (int argc, char **argv)
7532   /* Get a "context" object for working with the library.  */
7533   gccjit::context ctxt = gccjit::context::acquire ();
7535   /* Set some options on the context.
7536      Turn this on to see the code being generated, in assembler form.  */
7537   ctxt.set_bool_option (
7538     GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
7539     0);
7541   /* Populate the context.  */
7542   create_code (ctxt);
7544   /* Compile the code.  */
7545   gcc_jit_result *result = ctxt.compile ();
7547   /* We're done with the context; we can release it: */
7548   ctxt.release ();
7550   if (!result)
7551     @{
7552       fprintf (stderr, "NULL result");
7553       return 1;
7554     @}
7556   /* Extract the generated code from "result".  */
7557   void *fn_ptr = gcc_jit_result_get_code (result, "square");
7558   if (!fn_ptr)
7559      @{
7560        fprintf (stderr, "NULL fn_ptr");
7561        gcc_jit_result_release (result);
7562        return 1;
7563      @}
7565   typedef int (*fn_type) (int);
7566   fn_type square = (fn_type)fn_ptr;
7567   printf ("result: %d\n", square (5));
7569   gcc_jit_result_release (result);
7570   return 0;
7573 @end example
7575 @noindent
7576 @end quotation
7578 Building and running it:
7580 @example
7581 $ gcc \
7582     tut02-square.cc \
7583     -o tut02-square \
7584     -lgccjit
7586 # Run the built program:
7587 $ ./tut02-square
7588 result: 25
7589 @end example
7591 @noindent
7593 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
7594 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
7595 @c 
7596 @c This is free software: you can redistribute it and/or modify it
7597 @c under the terms of the GNU General Public License as published by
7598 @c the Free Software Foundation, either version 3 of the License, or
7599 @c (at your option) any later version.
7600 @c 
7601 @c This program is distributed in the hope that it will be useful, but
7602 @c WITHOUT ANY WARRANTY; without even the implied warranty of
7603 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
7604 @c General Public License for more details.
7605 @c 
7606 @c You should have received a copy of the GNU General Public License
7607 @c along with this program.  If not, see
7608 @c <http://www.gnu.org/licenses/>.
7610 @node Tutorial part 3 Loops and variables<2>,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>,Tutorial part 2 Creating a trivial machine code function<2>,Tutorial<2>
7611 @anchor{cp/intro/tutorial03 tutorial-part-3-loops-and-variables}@anchor{df}@anchor{cp/intro/tutorial03 doc}@anchor{e0}
7612 @subsection Tutorial part 3: Loops and variables
7615 Consider this C function:
7617 @quotation
7619 @example
7620 int loop_test (int n)
7622   int sum = 0;
7623   for (int i = 0; i < n; i++)
7624     sum += i * i;
7625   return sum;
7627 @end example
7629 @noindent
7630 @end quotation
7632 This example demonstrates some more features of libgccjit, with local
7633 variables and a loop.
7635 To break this down into libgccjit terms, it's usually easier to reword
7636 the @cite{for} loop as a @cite{while} loop, giving:
7638 @quotation
7640 @example
7641 int loop_test (int n)
7643   int sum = 0;
7644   int i = 0;
7645   while (i < n)
7646   @{
7647     sum += i * i;
7648     i++;
7649   @}
7650   return sum;
7652 @end example
7654 @noindent
7655 @end quotation
7657 Here's what the final control flow graph will look like:
7659 @quotation
7662 @float Figure
7664 @image{sum-of-squares,,,image of a control flow graph,png}
7666 @end float
7668 @end quotation
7670 As before, we include the libgccjit++ header and make a
7671 @code{gccjit::context}.
7673 @example
7674 #include <libgccjit++.h>
7676 void test (void)
7678   gccjit::context ctxt;
7679   ctxt = gccjit::context::acquire ();
7680 @end example
7682 @noindent
7684 The function works with the C @cite{int} type.
7686 In the previous tutorial we acquired this via
7688 @example
7689 gccjit::type the_type = ctxt.get_type (ctxt, GCC_JIT_TYPE_INT);
7690 @end example
7692 @noindent
7694 though we could equally well make it work on, say, @cite{double}:
7696 @example
7697 gccjit::type the_type = ctxt.get_type (ctxt, GCC_JIT_TYPE_DOUBLE);
7698 @end example
7700 @noindent
7702 For integer types we can use @code{gccjit::context::get_int_type}
7703 to directly bind a specific type:
7705 @example
7706 gccjit::type the_type = ctxt.get_int_type <int> ();
7707 @end example
7709 @noindent
7711 Let's build the function:
7713 @example
7714 gcc_jit_param n = ctxt.new_param (the_type, "n");
7715 std::vector<gccjit::param> params;
7716 params.push_back (n);
7717 gccjit::function func =
7718   ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
7719                      return_type,
7720                      "loop_test",
7721                      params, 0);
7722 @end example
7724 @noindent
7726 @menu
7727 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues<2>. 
7728 * Control flow: Control flow<2>. 
7729 * Visualizing the control flow graph: Visualizing the control flow graph<2>. 
7730 * Full example: Full example<4>. 
7732 @end menu
7734 @node Expressions lvalues and rvalues<2>,Control flow<2>,,Tutorial part 3 Loops and variables<2>
7735 @anchor{cp/intro/tutorial03 expressions-lvalues-and-rvalues}@anchor{e1}
7736 @subsubsection Expressions: lvalues and rvalues
7739 The base class of expression is the @code{gccjit::rvalue},
7740 representing an expression that can be on the @emph{right}-hand side of
7741 an assignment: a value that can be computed somehow, and assigned
7742 @emph{to} a storage area (such as a variable).  It has a specific
7743 @code{gccjit::type}.
7745 Anothe important class is @code{gccjit::lvalue}.
7746 A @code{gccjit::lvalue}. is something that can of the @emph{left}-hand
7747 side of an assignment: a storage area (such as a variable).
7749 In other words, every assignment can be thought of as:
7751 @example
7752 LVALUE = RVALUE;
7753 @end example
7755 @noindent
7757 Note that @code{gccjit::lvalue} is a subclass of
7758 @code{gccjit::rvalue}, where in an assignment of the form:
7760 @example
7761 LVALUE_A = LVALUE_B;
7762 @end example
7764 @noindent
7766 the @cite{LVALUE_B} implies reading the current value of that storage
7767 area, assigning it into the @cite{LVALUE_A}.
7769 So far the only expressions we've seen are from the previous tutorial:
7772 @enumerate 
7774 @item 
7775 the multiplication @cite{i * i}:
7776 @end enumerate
7778 @quotation
7780 @example
7781 gccjit::rvalue expr =
7782   ctxt.new_binary_op (
7783     GCC_JIT_BINARY_OP_MULT, int_type,
7784     param_i, param_i);
7786 /* Alternatively, using operator-overloading: */
7787 gccjit::rvalue expr = param_i * param_i;
7788 @end example
7790 @noindent
7792 which is a @code{gccjit::rvalue}, and
7793 @end quotation
7796 @enumerate 2
7798 @item 
7799 the various function parameters: @cite{param_i} and @cite{param_n}, instances of
7800 @code{gccjit::param}, which is a subclass of @code{gccjit::lvalue}
7801 (and, in turn, of @code{gccjit::rvalue}):
7802 we can both read from and write to function parameters within the
7803 body of a function.
7804 @end enumerate
7806 Our new example has a new kind of expression: we have two local
7807 variables.  We create them by calling
7808 @pxref{e2,,gccjit;;function;;new_local()}, supplying a type and a name:
7810 @example
7811 /* Build locals:  */
7812 gccjit::lvalue i = func.new_local (the_type, "i");
7813 gccjit::lvalue sum = func.new_local (the_type, "sum");
7814 @end example
7816 @noindent
7818 These are instances of @code{gccjit::lvalue} - they can be read from
7819 and written to.
7821 Note that there is no precanned way to create @emph{and} initialize a variable
7822 like in C:
7824 @example
7825 int i = 0;
7826 @end example
7828 @noindent
7830 Instead, having added the local to the function, we have to separately add
7831 an assignment of @cite{0} to @cite{local_i} at the beginning of the function.
7833 @node Control flow<2>,Visualizing the control flow graph<2>,Expressions lvalues and rvalues<2>,Tutorial part 3 Loops and variables<2>
7834 @anchor{cp/intro/tutorial03 control-flow}@anchor{e3}
7835 @subsubsection Control flow
7838 This function has a loop, so we need to build some basic blocks to
7839 handle the control flow.  In this case, we need 4 blocks:
7842 @enumerate 
7844 @item 
7845 before the loop (initializing the locals)
7847 @item 
7848 the conditional at the top of the loop (comparing @cite{i < n})
7850 @item 
7851 the body of the loop
7853 @item 
7854 after the loop terminates (@cite{return sum})
7855 @end enumerate
7857 so we create these as @code{gccjit::block} instances within the
7858 @code{gccjit::function}:
7860 @example
7861 gccjit::block b_initial = func.new_block ("initial");
7862 gccjit::block b_loop_cond = func.new_block ("loop_cond");
7863 gccjit::block b_loop_body = func.new_block ("loop_body");
7864 gccjit::block b_after_loop = func.new_block ("after_loop");
7865 @end example
7867 @noindent
7869 We now populate each block with statements.
7871 The entry block @cite{b_initial} consists of initializations followed by a jump
7872 to the conditional.  We assign @cite{0} to @cite{i} and to @cite{sum}, using
7873 @pxref{e4,,gccjit;;block;;add_assignment()} to add
7874 an assignment statement, and using @pxref{e5,,gccjit;;context;;zero()} to get
7875 the constant value @cite{0} for the relevant type for the right-hand side of
7876 the assignment:
7878 @example
7879 /* sum = 0; */
7880 b_initial.add_assignment (sum, ctxt.zero (the_type));
7882 /* i = 0; */
7883 b_initial.add_assignment (i, ctxt.zero (the_type));
7884 @end example
7886 @noindent
7888 We can then terminate the entry block by jumping to the conditional:
7890 @example
7891 b_initial.end_with_jump (b_loop_cond);
7892 @end example
7894 @noindent
7896 The conditional block is equivalent to the line @cite{while (i < n)} from our
7897 C example. It contains a single statement: a conditional, which jumps to
7898 one of two destination blocks depending on a boolean
7899 @code{gccjit::rvalue}, in this case the comparison of @cite{i} and @cite{n}.
7901 We could build the comparison using @pxref{e6,,gccjit;;context;;new_comparison()}:
7903 @example
7904 gccjit::rvalue guard =
7905   ctxt.new_comparison (GCC_JIT_COMPARISON_GE,
7906                        i, n);
7907 @end example
7909 @noindent
7911 and can then use this to add @cite{b_loop_cond}'s sole statement, via
7912 @pxref{e7,,gccjit;;block;;end_with_conditional()}:
7914 @example
7915 b_loop_cond.end_with_conditional (guard);
7916 @end example
7918 @noindent
7920 However @code{gccjit::rvalue} has overloaded operators for this, so we
7921 express the conditional as
7923 @example
7924 gccjit::rvalue guard = (i >= n);
7925 @end example
7927 @noindent
7929 and hence write the block more concisely as:
7931 @example
7932 b_loop_cond.end_with_conditional (
7933   i >= n,
7934   b_after_loop,
7935   b_loop_body);
7936 @end example
7938 @noindent
7940 Next, we populate the body of the loop.
7942 The C statement @cite{sum += i * i;} is an assignment operation, where an
7943 lvalue is modified "in-place".  We use
7944 @pxref{e8,,gccjit;;block;;add_assignment_op()} to handle these operations:
7946 @example
7947 /* sum += i * i */
7948 b_loop_body.add_assignment_op (sum,
7949                                GCC_JIT_BINARY_OP_PLUS,
7950                                i * i);
7951 @end example
7953 @noindent
7955 The @cite{i++} can be thought of as @cite{i += 1}, and can thus be handled in
7956 a similar way.  We use @pxref{2f,,gcc_jit_context_one()} to get the constant
7957 value @cite{1} (for the relevant type) for the right-hand side
7958 of the assignment.
7960 @example
7961 /* i++ */
7962 b_loop_body.add_assignment_op (i,
7963                                GCC_JIT_BINARY_OP_PLUS,
7964                                ctxt.one (the_type));
7965 @end example
7967 @noindent
7969 @cartouche
7970 @quotation Note 
7971 For numeric constants other than 0 or 1, we could use
7972 @pxref{e9,,gccjit;;context;;new_rvalue()}, which has overloads
7973 for both @code{int} and @code{double}.
7974 @end quotation
7975 @end cartouche
7977 The loop body completes by jumping back to the conditional:
7979 @example
7980 b_loop_body.end_with_jump (b_loop_cond);
7981 @end example
7983 @noindent
7985 Finally, we populate the @cite{b_after_loop} block, reached when the loop
7986 conditional is false.  We want to generate the equivalent of:
7988 @example
7989 return sum;
7990 @end example
7992 @noindent
7994 so the block is just one statement:
7996 @example
7997 /* return sum */
7998 b_after_loop.end_with_return (sum);
7999 @end example
8001 @noindent
8003 @cartouche
8004 @quotation Note 
8005 You can intermingle block creation with statement creation,
8006 but given that the terminator statements generally include references
8007 to other blocks, I find it's clearer to create all the blocks,
8008 @emph{then} all the statements.
8009 @end quotation
8010 @end cartouche
8012 We've finished populating the function.  As before, we can now compile it
8013 to machine code:
8015 @example
8016 gcc_jit_result *result;
8017 result = ctxt.compile ();
8019 ctxt.release ();
8021 if (!result)
8022   @{
8023     fprintf (stderr, "NULL result");
8024     return 1;
8025   @}
8027 typedef int (*loop_test_fn_type) (int);
8028 loop_test_fn_type loop_test =
8029  (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
8030 if (!loop_test)
8031   @{
8032     fprintf (stderr, "NULL loop_test");
8033     gcc_jit_result_release (result);
8034     return 1;
8035   @}
8036 printf ("result: %d", loop_test (10));
8037 @end example
8039 @noindent
8041 @example
8042 result: 285
8043 @end example
8045 @noindent
8047 @node Visualizing the control flow graph<2>,Full example<4>,Control flow<2>,Tutorial part 3 Loops and variables<2>
8048 @anchor{cp/intro/tutorial03 visualizing-the-control-flow-graph}@anchor{ea}
8049 @subsubsection Visualizing the control flow graph
8052 You can see the control flow graph of a function using
8053 @pxref{eb,,gccjit;;function;;dump_to_dot()}:
8055 @example
8056 func.dump_to_dot ("/tmp/sum-of-squares.dot");
8057 @end example
8059 @noindent
8061 giving a .dot file in GraphViz format.
8063 You can convert this to an image using @cite{dot}:
8065 @example
8066 $ dot -Tpng /tmp/sum-of-squares.dot -o /tmp/sum-of-squares.png
8067 @end example
8069 @noindent
8071 or use a viewer (my preferred one is xdot.py; see
8072 @indicateurl{https://github.com/jrfonseca/xdot.py}; on Fedora you can
8073 install it with @cite{yum install python-xdot}):
8075 @quotation
8078 @float Figure
8080 @image{sum-of-squares,,,image of a control flow graph,png}
8082 @end float
8084 @end quotation
8086 @node Full example<4>,,Visualizing the control flow graph<2>,Tutorial part 3 Loops and variables<2>
8087 @anchor{cp/intro/tutorial03 full-example}@anchor{ec}
8088 @subsubsection Full example
8091 @quotation
8093 @example
8094 /* Usage example for libgccjit.so's C++ API
8095    Copyright (C) 2014-2015 Free Software Foundation, Inc.
8097 This file is part of GCC.
8099 GCC is free software; you can redistribute it and/or modify it
8100 under the terms of the GNU General Public License as published by
8101 the Free Software Foundation; either version 3, or (at your option)
8102 any later version.
8104 GCC is distributed in the hope that it will be useful, but
8105 WITHOUT ANY WARRANTY; without even the implied warranty of
8106 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
8107 General Public License for more details.
8109 You should have received a copy of the GNU General Public License
8110 along with GCC; see the file COPYING3.  If not see
8111 <http://www.gnu.org/licenses/>.  */
8113 #include <libgccjit++.h>
8115 #include <stdlib.h>
8116 #include <stdio.h>
8118 void
8119 create_code (gccjit::context ctxt)
8121   /*
8122     Simple sum-of-squares, to test conditionals and looping
8124     int loop_test (int n)
8125     @{
8126       int i;
8127       int sum = 0;
8128       for (i = 0; i < n ; i ++)
8129       @{
8130         sum += i * i;
8131       @}
8132       return sum;
8133    */
8134   gccjit::type the_type = ctxt.get_int_type <int> ();
8135   gccjit::type return_type = the_type;
8137   gccjit::param n = ctxt.new_param (the_type, "n");
8138   std::vector<gccjit::param> params;
8139   params.push_back (n);
8140   gccjit::function func =
8141     ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
8142                        return_type,
8143                        "loop_test",
8144                        params, 0);
8146   /* Build locals:  */
8147   gccjit::lvalue i = func.new_local (the_type, "i");
8148   gccjit::lvalue sum = func.new_local (the_type, "sum");
8150   gccjit::block b_initial = func.new_block ("initial");
8151   gccjit::block b_loop_cond = func.new_block ("loop_cond");
8152   gccjit::block b_loop_body = func.new_block ("loop_body");
8153   gccjit::block b_after_loop = func.new_block ("after_loop");
8155   /* sum = 0; */
8156   b_initial.add_assignment (sum, ctxt.zero (the_type));
8158   /* i = 0; */
8159   b_initial.add_assignment (i, ctxt.zero (the_type));
8161   b_initial.end_with_jump (b_loop_cond);
8163   /* if (i >= n) */
8164   b_loop_cond.end_with_conditional (
8165     i >= n,
8166     b_after_loop,
8167     b_loop_body);
8169   /* sum += i * i */
8170   b_loop_body.add_assignment_op (sum,
8171                                  GCC_JIT_BINARY_OP_PLUS,
8172                                  i * i);
8174   /* i++ */
8175   b_loop_body.add_assignment_op (i,
8176                                 GCC_JIT_BINARY_OP_PLUS,
8177                                 ctxt.one (the_type));
8179   b_loop_body.end_with_jump (b_loop_cond);
8181   /* return sum */
8182   b_after_loop.end_with_return (sum);
8186 main (int argc, char **argv)
8188   gccjit::context ctxt;
8189   gcc_jit_result *result = NULL;
8191   /* Get a "context" object for working with the library.  */
8192   ctxt = gccjit::context::acquire ();
8194   /* Set some options on the context.
8195      Turn this on to see the code being generated, in assembler form.  */
8196   ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
8197                         0);
8199   /* Populate the context.  */
8200   create_code (ctxt);
8202   /* Compile the code.  */
8203   result = ctxt.compile ();
8205   ctxt.release ();
8207   if (!result)
8208     @{
8209       fprintf (stderr, "NULL result");
8210       return 1;
8211     @}
8213   /* Extract the generated code from "result".  */
8214   typedef int (*loop_test_fn_type) (int);
8215   loop_test_fn_type loop_test =
8216     (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
8217   if (!loop_test)
8218     @{
8219       fprintf (stderr, "NULL loop_test");
8220       gcc_jit_result_release (result);
8221       return 1;
8222     @}
8224   /* Run the generated code.  */
8225   int val = loop_test (10);
8226   printf("loop_test returned: %d\n", val);
8228   gcc_jit_result_release (result);
8229   return 0;
8232 @end example
8234 @noindent
8235 @end quotation
8237 Building and running it:
8239 @example
8240 $ gcc \
8241     tut03-sum-of-squares.cc \
8242     -o tut03-sum-of-squares \
8243     -lgccjit
8245 # Run the built program:
8246 $ ./tut03-sum-of-squares
8247 loop_test returned: 285
8248 @end example
8250 @noindent
8252 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
8253 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
8254 @c 
8255 @c This is free software: you can redistribute it and/or modify it
8256 @c under the terms of the GNU General Public License as published by
8257 @c the Free Software Foundation, either version 3 of the License, or
8258 @c (at your option) any later version.
8259 @c 
8260 @c This program is distributed in the hope that it will be useful, but
8261 @c WITHOUT ANY WARRANTY; without even the implied warranty of
8262 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
8263 @c General Public License for more details.
8264 @c 
8265 @c You should have received a copy of the GNU General Public License
8266 @c along with this program.  If not, see
8267 @c <http://www.gnu.org/licenses/>.
8269 @node Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>,,Tutorial part 3 Loops and variables<2>,Tutorial<2>
8270 @anchor{cp/intro/tutorial04 tutorial-part-4-adding-jit-compilation-to-a-toy-interpreter}@anchor{ed}@anchor{cp/intro/tutorial04 doc}@anchor{ee}
8271 @subsection Tutorial part 4: Adding JIT-compilation to a toy interpreter
8274 In this example we construct a "toy" interpreter, and add JIT-compilation
8275 to it.
8277 @menu
8278 * Our toy interpreter: Our toy interpreter<2>. 
8279 * Compiling to machine code: Compiling to machine code<2>. 
8280 * Setting things up: Setting things up<2>. 
8281 * Populating the function: Populating the function<2>. 
8282 * Verifying the control flow graph: Verifying the control flow graph<2>. 
8283 * Compiling the context: Compiling the context<2>. 
8284 * Single-stepping through the generated code: Single-stepping through the generated code<2>. 
8285 * Examining the generated code: Examining the generated code<2>. 
8286 * Putting it all together: Putting it all together<2>. 
8287 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?<2>. 
8289 @end menu
8291 @node Our toy interpreter<2>,Compiling to machine code<2>,,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
8292 @anchor{cp/intro/tutorial04 our-toy-interpreter}@anchor{ef}
8293 @subsubsection Our toy interpreter
8296 It's a stack-based interpreter, and is intended as a (very simple) example
8297 of the kind of bytecode interpreter seen in dynamic languages such as
8298 Python, Ruby etc.
8300 For the sake of simplicity, our toy virtual machine is very limited:
8302 @quotation
8305 @itemize *
8307 @item 
8308 The only data type is @cite{int}
8310 @item 
8311 It can only work on one function at a time (so that the only
8312 function call that can be made is to recurse).
8314 @item 
8315 Functions can only take one parameter.
8317 @item 
8318 Functions have a stack of @cite{int} values.
8320 @item 
8321 We'll implement function call within the interpreter by calling a
8322 function in our implementation, rather than implementing our own
8323 frame stack.
8325 @item 
8326 The parser is only good enough to get the examples to work.
8327 @end itemize
8328 @end quotation
8330 Naturally, a real interpreter would be much more complicated that this.
8332 The following operations are supported:
8335 @multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxx} 
8336 @headitem
8338 Operation
8340 @tab
8342 Meaning
8344 @tab
8346 Old Stack
8348 @tab
8350 New Stack
8352 @item
8356 @tab
8358 Duplicate top of stack.
8360 @tab
8362 @code{[..., x]}
8364 @tab
8366 @code{[..., x, x]}
8368 @item
8372 @tab
8374 Swap top two elements
8375 of stack.
8377 @tab
8379 @code{[..., x, y]}
8381 @tab
8383 @code{[..., y, x]}
8385 @item
8387 BINARY_ADD
8389 @tab
8391 Add the top two elements
8392 on the stack.
8394 @tab
8396 @code{[..., x, y]}
8398 @tab
8400 @code{[..., (x+y)]}
8402 @item
8404 BINARY_SUBTRACT
8406 @tab
8408 Likewise, but subtract.
8410 @tab
8412 @code{[..., x, y]}
8414 @tab
8416 @code{[..., (x-y)]}
8418 @item
8420 BINARY_MULT
8422 @tab
8424 Likewise, but multiply.
8426 @tab
8428 @code{[..., x, y]}
8430 @tab
8432 @code{[..., (x*y)]}
8434 @item
8436 BINARY_COMPARE_LT
8438 @tab
8440 Compare the top two
8441 elements on the stack
8442 and push a nonzero/zero
8443 if (x<y).
8445 @tab
8447 @code{[..., x, y]}
8449 @tab
8451 @code{[..., (x<y)]}
8453 @item
8455 RECURSE
8457 @tab
8459 Recurse, passing the top
8460 of the stack, and
8461 popping the result.
8463 @tab
8465 @code{[..., x]}
8467 @tab
8469 @code{[..., fn(x)]}
8471 @item
8473 RETURN
8475 @tab
8477 Return the top of the
8478 stack.
8480 @tab
8482 @code{[x]}
8484 @tab
8486 @code{[]}
8488 @item
8490 PUSH_CONST @cite{arg}
8492 @tab
8494 Push an int const.
8496 @tab
8498 @code{[...]}
8500 @tab
8502 @code{[..., arg]}
8504 @item
8506 JUMP_ABS_IF_TRUE @cite{arg}
8508 @tab
8510 Pop; if top of stack was
8511 nonzero, jump to
8512 @code{arg}.
8514 @tab
8516 @code{[..., x]}
8518 @tab
8520 @code{[...]}
8522 @end multitable
8525 Programs can be interpreted, disassembled, and compiled to machine code.
8527 The interpreter reads @code{.toy} scripts.  Here's what a simple recursive
8528 factorial program looks like, the script @code{factorial.toy}.
8529 The parser ignores lines beginning with a @cite{#}.
8531 @quotation
8533 @example
8534 # Simple recursive factorial implementation, roughly equivalent to:
8536 #  int factorial (int arg)
8537 #  @{
8538 #     if (arg < 2)
8539 #       return arg
8540 #     return arg * factorial (arg - 1)
8541 #  @}
8543 # Initial state:
8544 # stack: [arg]
8546 # 0:
8548 # stack: [arg, arg]
8550 # 1:
8551 PUSH_CONST 2
8552 # stack: [arg, arg, 2]
8554 # 2:
8555 BINARY_COMPARE_LT
8556 # stack: [arg, (arg < 2)]
8558 # 3:
8559 JUMP_ABS_IF_TRUE 9
8560 # stack: [arg]
8562 # 4:
8564 # stack: [arg, arg]
8566 # 5:
8567 PUSH_CONST 1
8568 # stack: [arg, arg, 1]
8570 # 6:
8571 BINARY_SUBTRACT
8572 # stack: [arg,  (arg - 1)
8574 # 7:
8575 RECURSE
8576 # stack: [arg, factorial(arg - 1)]
8578 # 8:
8579 BINARY_MULT
8580 # stack: [arg * factorial(arg - 1)]
8582 # 9:
8583 RETURN
8585 @end example
8587 @noindent
8588 @end quotation
8590 The interpreter is a simple infinite loop with a big @code{switch} statement
8591 based on what the next opcode is:
8593 @quotation
8595 @example
8598 toyvm_function::interpret (int arg, FILE *trace)
8600   toyvm_frame frame;
8601 #define PUSH(ARG) (frame.push (ARG))
8602 #define POP(ARG) (frame.pop ())
8604   frame.frm_function = this;
8605   frame.frm_pc = 0;
8606   frame.frm_cur_depth = 0;
8608   PUSH (arg);
8610   while (1)
8611     @{
8612       toyvm_op *op;
8613       int x, y;
8614       assert (frame.frm_pc < fn_num_ops);
8615       op = &fn_ops[frame.frm_pc++];
8617       if (trace)
8618         @{
8619           frame.dump_stack (trace);
8620           disassemble_op (op, frame.frm_pc, trace);
8621         @}
8623       switch (op->op_opcode)
8624         @{
8625           /* Ops taking no operand.  */
8626         case DUP:
8627           x = POP ();
8628           PUSH (x);
8629           PUSH (x);
8630           break;
8632         case ROT:
8633           y = POP ();
8634           x = POP ();
8635           PUSH (y);
8636           PUSH (x);
8637           break;
8639         case BINARY_ADD:
8640           y = POP ();
8641           x = POP ();
8642           PUSH (x + y);
8643           break;
8645         case BINARY_SUBTRACT:
8646           y = POP ();
8647           x = POP ();
8648           PUSH (x - y);
8649           break;
8651         case BINARY_MULT:
8652           y = POP ();
8653           x = POP ();
8654           PUSH (x * y);
8655           break;
8657         case BINARY_COMPARE_LT:
8658           y = POP ();
8659           x = POP ();
8660           PUSH (x < y);
8661           break;
8663         case RECURSE:
8664           x = POP ();
8665           x = interpret (x, trace);
8666           PUSH (x);
8667           break;
8669         case RETURN:
8670           return POP ();
8672           /* Ops taking an operand.  */
8673         case PUSH_CONST:
8674           PUSH (op->op_operand);
8675           break;
8677         case JUMP_ABS_IF_TRUE:
8678           x = POP ();
8679           if (x)
8680             frame.frm_pc = op->op_operand;
8681           break;
8683         default:
8684           assert (0); /* unknown opcode */
8686         @} /* end of switch on opcode */
8687     @} /* end of while loop */
8689 #undef PUSH
8690 #undef POP
8694 @end example
8696 @noindent
8697 @end quotation
8699 @node Compiling to machine code<2>,Setting things up<2>,Our toy interpreter<2>,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
8700 @anchor{cp/intro/tutorial04 compiling-to-machine-code}@anchor{f0}
8701 @subsubsection Compiling to machine code
8704 We want to generate machine code that can be cast to this type and
8705 then directly executed in-process:
8707 @quotation
8709 @example
8710 typedef int (*toyvm_compiled_func) (int);
8713 @end example
8715 @noindent
8716 @end quotation
8718 Our compiler isn't very sophisticated; it takes the implementation of
8719 each opcode above, and maps it directly to the operations supported by
8720 the libgccjit API.
8722 How should we handle the stack?  In theory we could calculate what the
8723 stack depth will be at each opcode, and optimize away the stack
8724 manipulation "by hand".  We'll see below that libgccjit is able to do
8725 this for us, so we'll implement stack manipulation
8726 in a direct way, by creating a @code{stack} array and @code{stack_depth}
8727 variables, local within the generated function, equivalent to this C code:
8729 @example
8730 int stack_depth;
8731 int stack[MAX_STACK_DEPTH];
8732 @end example
8734 @noindent
8736 We'll also have local variables @code{x} and @code{y} for use when implementing
8737 the opcodes, equivalent to this:
8739 @example
8740 int x;
8741 int y;
8742 @end example
8744 @noindent
8746 This means our compiler has the following state:
8748 @quotation
8750 @example
8752   toyvm_function &toyvmfn;
8754   gccjit::context ctxt;
8756   gccjit::type int_type;
8757   gccjit::type bool_type;
8758   gccjit::type stack_type; /* int[MAX_STACK_DEPTH] */
8760   gccjit::rvalue const_one;
8762   gccjit::function fn;
8763   gccjit::param param_arg;
8764   gccjit::lvalue stack;
8765   gccjit::lvalue stack_depth;
8766   gccjit::lvalue x;
8767   gccjit::lvalue y;
8769   gccjit::location op_locs[MAX_OPS];
8770   gccjit::block initial_block;
8771   gccjit::block op_blocks[MAX_OPS];
8774 @end example
8776 @noindent
8777 @end quotation
8779 @node Setting things up<2>,Populating the function<2>,Compiling to machine code<2>,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
8780 @anchor{cp/intro/tutorial04 setting-things-up}@anchor{f1}
8781 @subsubsection Setting things up
8784 First we create our types:
8786 @quotation
8788 @example
8790 void
8791 compilation_state::create_types ()
8793   /* Create types.  */
8794   int_type = ctxt.get_type (GCC_JIT_TYPE_INT);
8795   bool_type = ctxt.get_type (GCC_JIT_TYPE_BOOL);
8796   stack_type = ctxt.new_array_type (int_type, MAX_STACK_DEPTH);
8799 @end example
8801 @noindent
8802 @end quotation
8804 along with extracting a useful @cite{int} constant:
8806 @quotation
8808 @example
8809   const_one = ctxt.one (int_type);
8814 @end example
8816 @noindent
8817 @end quotation
8819 We'll implement push and pop in terms of the @code{stack} array and
8820 @code{stack_depth}.  Here are helper functions for adding statements to
8821 a block, implementing pushing and popping values:
8823 @quotation
8825 @example
8827 void
8828 compilation_state::add_push (gccjit::block block,
8829                              gccjit::rvalue rvalue,
8830                              gccjit::location loc)
8832   /* stack[stack_depth] = RVALUE */
8833   block.add_assignment (
8834     /* stack[stack_depth] */
8835     ctxt.new_array_access (
8836       stack,
8837       stack_depth,
8838       loc),
8839     rvalue,
8840     loc);
8842   /* "stack_depth++;".  */
8843   block.add_assignment_op (
8844     stack_depth,
8845     GCC_JIT_BINARY_OP_PLUS,
8846     const_one,
8847     loc);
8850 void
8851 compilation_state::add_pop (gccjit::block block,
8852                             gccjit::lvalue lvalue,
8853                             gccjit::location loc)
8855   /* "--stack_depth;".  */
8856   block.add_assignment_op (
8857     stack_depth,
8858     GCC_JIT_BINARY_OP_MINUS,
8859     const_one,
8860     loc);
8862   /* "LVALUE = stack[stack_depth];".  */
8863   block.add_assignment (
8864     lvalue,
8865     /* stack[stack_depth] */
8866     ctxt.new_array_access (stack,
8867                            stack_depth,
8868                            loc),
8869     loc);
8873 @end example
8875 @noindent
8876 @end quotation
8878 We will support single-stepping through the generated code in the
8879 debugger, so we need to create @code{gccjit::location} instances, one
8880 per operation in the source code.  These will reference the lines of
8881 e.g. @code{factorial.toy}.
8883 @quotation
8885 @example
8887 void
8888 compilation_state::create_locations ()
8890   for (int pc = 0; pc < toyvmfn.fn_num_ops; pc++)
8891     @{
8892       toyvm_op *op = &toyvmfn.fn_ops[pc];
8894       op_locs[pc] = ctxt.new_location (toyvmfn.fn_filename,
8895                                        op->op_linenum,
8896                                        0); /* column */
8897     @}
8901 @end example
8903 @noindent
8904 @end quotation
8906 Let's create the function itself.  As usual, we create its parameter
8907 first, then use the parameter to create the function:
8909 @quotation
8911 @example
8913 void
8914 compilation_state::create_function (const char *funcname)
8916   std::vector <gccjit::param> params;
8917   param_arg = ctxt.new_param (int_type, "arg", op_locs[0]);
8918   params.push_back (param_arg);
8919   fn = ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
8920                           int_type,
8921                           funcname,
8922                           params, 0,
8923                           op_locs[0]);
8926 @end example
8928 @noindent
8929 @end quotation
8931 We create the locals within the function.
8933 @quotation
8935 @example
8936   stack = fn.new_local (stack_type, "stack");
8937   stack_depth = fn.new_local (int_type, "stack_depth");
8938   x = fn.new_local (int_type, "x");
8939   y = fn.new_local (int_type, "y");
8942 @end example
8944 @noindent
8945 @end quotation
8947 @node Populating the function<2>,Verifying the control flow graph<2>,Setting things up<2>,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
8948 @anchor{cp/intro/tutorial04 populating-the-function}@anchor{f2}
8949 @subsubsection Populating the function
8952 There's some one-time initialization, and the API treats the first block
8953 you create as the entrypoint of the function, so we need to create that
8954 block first:
8956 @quotation
8958 @example
8959   initial_block = fn.new_block ("initial");
8962 @end example
8964 @noindent
8965 @end quotation
8967 We can now create blocks for each of the operations.  Most of these will
8968 be consolidated into larger blocks when the optimizer runs.
8970 @quotation
8972 @example
8973   for (int pc = 0; pc < toyvmfn.fn_num_ops; pc++)
8974     @{
8975       char buf[16];
8976       sprintf (buf, "instr%i", pc);
8977       op_blocks[pc] = fn.new_block (buf);
8978     @}
8981 @end example
8983 @noindent
8984 @end quotation
8986 Now that we have a block it can jump to when it's done, we can populate
8987 the initial block:
8989 @quotation
8991 @example
8993   /* "stack_depth = 0;".  */
8994   initial_block.add_assignment (stack_depth,
8995                                 ctxt.zero (int_type),
8996                                 op_locs[0]);
8998   /* "PUSH (arg);".  */
8999   add_push (initial_block,
9000             param_arg,
9001             op_locs[0]);
9003   /* ...and jump to insn 0.  */
9004   initial_block.end_with_jump (op_blocks[0],
9005                                op_locs[0]);
9008 @end example
9010 @noindent
9011 @end quotation
9013 We can now populate the blocks for the individual operations.  We loop
9014 through them, adding instructions to their blocks:
9016 @quotation
9018 @example
9019   for (int pc = 0; pc < toyvmfn.fn_num_ops; pc++)
9020     @{
9021       gccjit::location loc = op_locs[pc];
9023       gccjit::block block = op_blocks[pc];
9024       gccjit::block next_block = (pc < toyvmfn.fn_num_ops
9025                                   ? op_blocks[pc + 1]
9026                                   : NULL);
9028       toyvm_op *op;
9029       op = &toyvmfn.fn_ops[pc];
9032 @end example
9034 @noindent
9035 @end quotation
9037 We're going to have another big @code{switch} statement for implementing
9038 the opcodes, this time for compiling them, rather than interpreting
9039 them.  It's helpful to have macros for implementing push and pop, so that
9040 we can make the @code{switch} statement that's coming up look as much as
9041 possible like the one above within the interpreter:
9043 @example
9045 #define X_EQUALS_POP()\
9046       add_pop (block, x, loc)
9047 #define Y_EQUALS_POP()\
9048       add_pop (block, y, loc)
9049 #define PUSH_RVALUE(RVALUE)\
9050       add_push (block, (RVALUE), loc)
9051 #define PUSH_X()\
9052       PUSH_RVALUE (x)
9053 #define PUSH_Y() \
9054       PUSH_RVALUE (y)
9057 @end example
9059 @noindent
9061 @cartouche
9062 @quotation Note 
9063 A particularly clever implementation would have an @emph{identical}
9064 @code{switch} statement shared by the interpreter and the compiler, with
9065 some preprocessor "magic".  We're not doing that here, for the sake
9066 of simplicity.
9067 @end quotation
9068 @end cartouche
9070 When I first implemented this compiler, I accidentally missed an edit
9071 when copying and pasting the @code{Y_EQUALS_POP} macro, so that popping the
9072 stack into @code{y} instead erroneously assigned it to @code{x}, leaving @code{y}
9073 uninitialized.
9075 To track this kind of thing down, we can use
9076 @pxref{f3,,gccjit;;block;;add_comment()} to add descriptive comments
9077 to the internal representation.  This is invaluable when looking through
9078 the generated IR for, say @code{factorial}:
9080 @quotation
9082 @example
9084       block.add_comment (opcode_names[op->op_opcode], loc);
9087 @end example
9089 @noindent
9090 @end quotation
9092 We can now write the big @code{switch} statement that implements the
9093 individual opcodes, populating the relevant block with statements:
9095 @quotation
9097 @example
9099       switch (op->op_opcode)
9100         @{
9101         case DUP:
9102           X_EQUALS_POP ();
9103           PUSH_X ();
9104           PUSH_X ();
9105           break;
9107         case ROT:
9108           Y_EQUALS_POP ();
9109           X_EQUALS_POP ();
9110           PUSH_Y ();
9111           PUSH_X ();
9112           break;
9114         case BINARY_ADD:
9115           Y_EQUALS_POP ();
9116           X_EQUALS_POP ();
9117           PUSH_RVALUE (
9118            ctxt.new_binary_op (
9119              GCC_JIT_BINARY_OP_PLUS,
9120              int_type,
9121              x, y,
9122              loc));
9123           break;
9125         case BINARY_SUBTRACT:
9126           Y_EQUALS_POP ();
9127           X_EQUALS_POP ();
9128           PUSH_RVALUE (
9129            ctxt.new_binary_op (
9130              GCC_JIT_BINARY_OP_MINUS,
9131              int_type,
9132              x, y,
9133              loc));
9134           break;
9136         case BINARY_MULT:
9137           Y_EQUALS_POP ();
9138           X_EQUALS_POP ();
9139           PUSH_RVALUE (
9140            ctxt.new_binary_op (
9141              GCC_JIT_BINARY_OP_MULT,
9142              int_type,
9143              x, y,
9144              loc));
9145           break;
9147         case BINARY_COMPARE_LT:
9148           Y_EQUALS_POP ();
9149           X_EQUALS_POP ();
9150           PUSH_RVALUE (
9151              /* cast of bool to int */
9152              ctxt.new_cast (
9153                /* (x < y) as a bool */
9154                ctxt.new_comparison (
9155                  GCC_JIT_COMPARISON_LT,
9156                  x, y,
9157                  loc),
9158                int_type,
9159                loc));
9160           break;
9162         case RECURSE:
9163           @{
9164             X_EQUALS_POP ();
9165             PUSH_RVALUE (
9166               ctxt.new_call (
9167                 fn,
9168                 x,
9169                 loc));
9170             break;
9171           @}
9173         case RETURN:
9174           X_EQUALS_POP ();
9175           block.end_with_return (x, loc);
9176           break;
9178           /* Ops taking an operand.  */
9179         case PUSH_CONST:
9180           PUSH_RVALUE (
9181             ctxt.new_rvalue (int_type, op->op_operand));
9182           break;
9184         case JUMP_ABS_IF_TRUE:
9185           X_EQUALS_POP ();
9186           block.end_with_conditional (
9187             /* "(bool)x".  */
9188             ctxt.new_cast (x, bool_type, loc),
9189             op_blocks[op->op_operand], /* on_true */
9190             next_block, /* on_false */
9191             loc); 
9192           break;
9194         default:
9195           assert(0);
9196         @} /* end of switch on opcode */
9199 @end example
9201 @noindent
9202 @end quotation
9204 Every block must be terminated, via a call to one of the
9205 @code{gccjit::block::end_with_} entrypoints.  This has been done for two
9206 of the opcodes, but we need to do it for the other ones, by jumping
9207 to the next block.
9209 @quotation
9211 @example
9212       if (op->op_opcode != JUMP_ABS_IF_TRUE
9213           && op->op_opcode != RETURN)
9214         block.end_with_jump (next_block, loc);
9217 @end example
9219 @noindent
9220 @end quotation
9222 This is analogous to simply incrementing the program counter.
9224 @node Verifying the control flow graph<2>,Compiling the context<2>,Populating the function<2>,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
9225 @anchor{cp/intro/tutorial04 verifying-the-control-flow-graph}@anchor{f4}
9226 @subsubsection Verifying the control flow graph
9229 Having finished looping over the blocks, the context is complete.
9231 As before, we can verify that the control flow and statements are sane by
9232 using @pxref{eb,,gccjit;;function;;dump_to_dot()}:
9234 @example
9235 fn.dump_to_dot ("/tmp/factorial.dot");
9236 @end example
9238 @noindent
9240 and viewing the result.  Note how the label names, comments, and
9241 variable names show up in the dump, to make it easier to spot
9242 errors in our compiler.
9244 @quotation
9247 @float Figure
9249 @image{factorial,,,image of a control flow graph,png}
9251 @end float
9253 @end quotation
9255 @node Compiling the context<2>,Single-stepping through the generated code<2>,Verifying the control flow graph<2>,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
9256 @anchor{cp/intro/tutorial04 compiling-the-context}@anchor{f5}
9257 @subsubsection Compiling the context
9260 Having finished looping over the blocks and populating them with
9261 statements, the context is complete.
9263 We can now compile it, and extract machine code from the result:
9265 @quotation
9267 @example
9268   gcc_jit_result *result = state.compile ();
9270   return (toyvm_compiled_func)gcc_jit_result_get_code (result, funcname);
9272 @end example
9274 @noindent
9275 @end quotation
9277 We can now run the result:
9279 @quotation
9281 @example
9282   toyvm_compiled_func code = fn->compile ();
9283   printf ("compiler result: %d\n",
9284           code (atoi (argv[2])));
9287 @end example
9289 @noindent
9290 @end quotation
9292 @node Single-stepping through the generated code<2>,Examining the generated code<2>,Compiling the context<2>,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
9293 @anchor{cp/intro/tutorial04 single-stepping-through-the-generated-code}@anchor{f6}
9294 @subsubsection Single-stepping through the generated code
9297 It's possible to debug the generated code.  To do this we need to both:
9299 @quotation
9302 @itemize *
9304 @item 
9305 Set up source code locations for our statements, so that we can
9306 meaningfully step through the code.  We did this above by
9307 calling @pxref{f7,,gccjit;;context;;new_location()} and using the
9308 results.
9310 @item 
9311 Enable the generation of debugging information, by setting
9312 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} on the
9313 @code{gccjit::context} via
9314 @pxref{dc,,gccjit;;context;;set_bool_option()}:
9316 @example
9317 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DEBUGINFO, 1);
9318 @end example
9320 @noindent
9321 @end itemize
9322 @end quotation
9324 Having done this, we can put a breakpoint on the generated function:
9326 @example
9327 $ gdb --args ./toyvm factorial.toy 10
9328 (gdb) break factorial
9329 Function "factorial" not defined.
9330 Make breakpoint pending on future shared library load? (y or [n]) y
9331 Breakpoint 1 (factorial) pending.
9332 (gdb) run
9333 Breakpoint 1, factorial (arg=10) at factorial.toy:14
9334 14    DUP
9335 @end example
9337 @noindent
9339 We've set up location information, which references @code{factorial.toy}.
9340 This allows us to use e.g. @code{list} to see where we are in the script:
9342 @example
9343 (gdb) list
9345 10    # Initial state:
9346 11    # stack: [arg]
9348 13    # 0:
9349 14    DUP
9350 15    # stack: [arg, arg]
9352 17    # 1:
9353 18    PUSH_CONST 2
9354 @end example
9356 @noindent
9358 and to step through the function, examining the data:
9360 @example
9361 (gdb) n
9362 18    PUSH_CONST 2
9363 (gdb) n
9364 22    BINARY_COMPARE_LT
9365 (gdb) print stack
9366 $5 = @{10, 10, 2, 0, -7152, 32767, 0, 0@}
9367 (gdb) print stack_depth
9368 $6 = 3
9369 @end example
9371 @noindent
9373 You'll see that the parts of the @code{stack} array that haven't been
9374 touched yet are uninitialized.
9376 @cartouche
9377 @quotation Note 
9378 Turning on optimizations may lead to unpredictable results when
9379 stepping through the generated code: the execution may appear to
9380 "jump around" the source code.  This is analogous to turning up the
9381 optimization level in a regular compiler.
9382 @end quotation
9383 @end cartouche
9385 @node Examining the generated code<2>,Putting it all together<2>,Single-stepping through the generated code<2>,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
9386 @anchor{cp/intro/tutorial04 examining-the-generated-code}@anchor{f8}
9387 @subsubsection Examining the generated code
9390 How good is the optimized code?
9392 We can turn up optimizations, by calling
9393 @pxref{dd,,gccjit;;context;;set_int_option()} with
9394 @pxref{1f,,GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}:
9396 @example
9397 ctxt.set_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL, 3);
9398 @end example
9400 @noindent
9402 One of GCC's internal representations is called "gimple".  A dump of the
9403 initial gimple representation of the code can be seen by setting:
9405 @example
9406 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE, 1);
9407 @end example
9409 @noindent
9411 With optimization on and source locations displayed, this gives:
9413 @c We'll use "c" for gimple dumps
9415 @example
9416 factorial (signed int arg)
9418   <unnamed type> D.80;
9419   signed int D.81;
9420   signed int D.82;
9421   signed int D.83;
9422   signed int D.84;
9423   signed int D.85;
9424   signed int y;
9425   signed int x;
9426   signed int stack_depth;
9427   signed int stack[8];
9429   try
9430     @{
9431       initial:
9432       stack_depth = 0;
9433       stack[stack_depth] = arg;
9434       stack_depth = stack_depth + 1;
9435       goto instr0;
9436       instr0:
9437       /* DUP */:
9438       stack_depth = stack_depth + -1;
9439       x = stack[stack_depth];
9440       stack[stack_depth] = x;
9441       stack_depth = stack_depth + 1;
9442       stack[stack_depth] = x;
9443       stack_depth = stack_depth + 1;
9444       goto instr1;
9445       instr1:
9446       /* PUSH_CONST */:
9447       stack[stack_depth] = 2;
9448       stack_depth = stack_depth + 1;
9449       goto instr2;
9451       /* etc */
9452 @end example
9454 @noindent
9456 You can see the generated machine code in assembly form via:
9458 @example
9459 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE, 1);
9460 result = ctxt.compile ();
9461 @end example
9463 @noindent
9465 which shows that (on this x86_64 box) the compiler has unrolled the loop
9466 and is using MMX instructions to perform several multiplications
9467 simultaneously:
9469 @example
9470         .file   "fake.c"
9471         .text
9472 .Ltext0:
9473         .p2align 4,,15
9474         .globl  factorial
9475         .type   factorial, @@function
9476 factorial:
9477 .LFB0:
9478         .file 1 "factorial.toy"
9479         .loc 1 14 0
9480         .cfi_startproc
9481 .LVL0:
9482 .L2:
9483         .loc 1 26 0
9484         cmpl    $1, %edi
9485         jle     .L13
9486         leal    -1(%rdi), %edx
9487         movl    %edx, %ecx
9488         shrl    $2, %ecx
9489         leal    0(,%rcx,4), %esi
9490         testl   %esi, %esi
9491         je      .L14
9492         cmpl    $9, %edx
9493         jbe     .L14
9494         leal    -2(%rdi), %eax
9495         movl    %eax, -16(%rsp)
9496         leal    -3(%rdi), %eax
9497         movd    -16(%rsp), %xmm0
9498         movl    %edi, -16(%rsp)
9499         movl    %eax, -12(%rsp)
9500         movd    -16(%rsp), %xmm1
9501         xorl    %eax, %eax
9502         movl    %edx, -16(%rsp)
9503         movd    -12(%rsp), %xmm4
9504         movd    -16(%rsp), %xmm6
9505         punpckldq       %xmm4, %xmm0
9506         movdqa  .LC1(%rip), %xmm4
9507         punpckldq       %xmm6, %xmm1
9508         punpcklqdq      %xmm0, %xmm1
9509         movdqa  .LC0(%rip), %xmm0
9510         jmp     .L5
9511         # etc - edited for brevity
9512 @end example
9514 @noindent
9516 This is clearly overkill for a function that will likely overflow the
9517 @code{int} type before the vectorization is worthwhile - but then again, this
9518 is a toy example.
9520 Turning down the optimization level to 2:
9522 @example
9523 ctxt.set_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL, 2);
9524 @end example
9526 @noindent
9528 yields this code, which is simple enough to quote in its entirety:
9530 @example
9531         .file   "fake.c"
9532         .text
9533         .p2align 4,,15
9534         .globl  factorial
9535         .type   factorial, @@function
9536 factorial:
9537 .LFB0:
9538         .cfi_startproc
9539 .L2:
9540         cmpl    $1, %edi
9541         jle     .L8
9542         movl    $1, %edx
9543         jmp     .L4
9544         .p2align 4,,10
9545         .p2align 3
9546 .L6:
9547         movl    %eax, %edi
9548 .L4:
9549 .L5:
9550         leal    -1(%rdi), %eax
9551         imull   %edi, %edx
9552         cmpl    $1, %eax
9553         jne     .L6
9554 .L3:
9555 .L7:
9556         imull   %edx, %eax
9557         ret
9558 .L8:
9559         movl    %edi, %eax
9560         movl    $1, %edx
9561         jmp     .L7
9562         .cfi_endproc
9563 .LFE0:
9564         .size   factorial, .-factorial
9565         .ident  "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-%@{gcc_release@})"
9566         .section        .note.GNU-stack,"",@@progbits
9567 @end example
9569 @noindent
9571 Note that the stack pushing and popping have been eliminated, as has the
9572 recursive call (in favor of an iteration).
9574 @node Putting it all together<2>,Behind the curtain How does our code get optimized?<2>,Examining the generated code<2>,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
9575 @anchor{cp/intro/tutorial04 putting-it-all-together}@anchor{f9}
9576 @subsubsection Putting it all together
9579 The complete example can be seen in the source tree at
9580 @code{gcc/jit/docs/examples/tut04-toyvm/toyvm.cc}
9582 along with a Makefile and a couple of sample .toy scripts:
9584 @example
9585 $ ls -al
9586 drwxrwxr-x. 2 david david   4096 Sep 19 17:46 .
9587 drwxrwxr-x. 3 david david   4096 Sep 19 15:26 ..
9588 -rw-rw-r--. 1 david david    615 Sep 19 12:43 factorial.toy
9589 -rw-rw-r--. 1 david david    834 Sep 19 13:08 fibonacci.toy
9590 -rw-rw-r--. 1 david david    238 Sep 19 14:22 Makefile
9591 -rw-rw-r--. 1 david david  16457 Sep 19 17:07 toyvm.cc
9593 $ make toyvm
9594 g++ -Wall -g -o toyvm toyvm.cc -lgccjit
9596 $ ./toyvm factorial.toy 10
9597 interpreter result: 3628800
9598 compiler result: 3628800
9600 $ ./toyvm fibonacci.toy 10
9601 interpreter result: 55
9602 compiler result: 55
9603 @end example
9605 @noindent
9607 @node Behind the curtain How does our code get optimized?<2>,,Putting it all together<2>,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
9608 @anchor{cp/intro/tutorial04 behind-the-curtain-how-does-our-code-get-optimized}@anchor{fa}
9609 @subsubsection Behind the curtain: How does our code get optimized?
9612 Our example is done, but you may be wondering about exactly how the
9613 compiler turned what we gave it into the machine code seen above.
9615 We can examine what the compiler is doing in detail by setting:
9617 @example
9618 state.ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING, 1);
9619 state.ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES, 1);
9620 @end example
9622 @noindent
9624 This will dump detailed information about the compiler's state to a
9625 directory under @code{/tmp}, and keep it from being cleaned up.
9627 The precise names and their formats of these files is subject to change.
9628 Higher optimization levels lead to more files.
9629 Here's what I saw (edited for brevity; there were almost 200 files):
9631 @example
9632 intermediate files written to /tmp/libgccjit-KPQbGw
9633 $ ls /tmp/libgccjit-KPQbGw/
9634 fake.c.000i.cgraph
9635 fake.c.000i.type-inheritance
9636 fake.c.004t.gimple
9637 fake.c.007t.omplower
9638 fake.c.008t.lower
9639 fake.c.011t.eh
9640 fake.c.012t.cfg
9641 fake.c.014i.visibility
9642 fake.c.015i.early_local_cleanups
9643 fake.c.016t.ssa
9644 # etc
9645 @end example
9647 @noindent
9649 The gimple code is converted into Static Single Assignment form,
9650 with annotations for use when generating the debuginfo:
9652 @example
9653 $ less /tmp/libgccjit-KPQbGw/fake.c.016t.ssa
9654 @end example
9656 @noindent
9658 @example
9659 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9661 factorial (signed int arg)
9663   signed int stack[8];
9664   signed int stack_depth;
9665   signed int x;
9666   signed int y;
9667   <unnamed type> _20;
9668   signed int _21;
9669   signed int _38;
9670   signed int _44;
9671   signed int _51;
9672   signed int _56;
9674 initial:
9675   stack_depth_3 = 0;
9676   # DEBUG stack_depth => stack_depth_3
9677   stack[stack_depth_3] = arg_5(D);
9678   stack_depth_7 = stack_depth_3 + 1;
9679   # DEBUG stack_depth => stack_depth_7
9680   # DEBUG instr0 => NULL
9681   # DEBUG /* DUP */ => NULL
9682   stack_depth_8 = stack_depth_7 + -1;
9683   # DEBUG stack_depth => stack_depth_8
9684   x_9 = stack[stack_depth_8];
9685   # DEBUG x => x_9
9686   stack[stack_depth_8] = x_9;
9687   stack_depth_11 = stack_depth_8 + 1;
9688   # DEBUG stack_depth => stack_depth_11
9689   stack[stack_depth_11] = x_9;
9690   stack_depth_13 = stack_depth_11 + 1;
9691   # DEBUG stack_depth => stack_depth_13
9692   # DEBUG instr1 => NULL
9693   # DEBUG /* PUSH_CONST */ => NULL
9694   stack[stack_depth_13] = 2;
9696   /* etc; edited for brevity */
9697 @end example
9699 @noindent
9701 We can perhaps better see the code by turning off
9702 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} to suppress all those @code{DEBUG}
9703 statements, giving:
9705 @example
9706 $ less /tmp/libgccjit-1Hywc0/fake.c.016t.ssa
9707 @end example
9709 @noindent
9711 @example
9712 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9714 factorial (signed int arg)
9716   signed int stack[8];
9717   signed int stack_depth;
9718   signed int x;
9719   signed int y;
9720   <unnamed type> _20;
9721   signed int _21;
9722   signed int _38;
9723   signed int _44;
9724   signed int _51;
9725   signed int _56;
9727 initial:
9728   stack_depth_3 = 0;
9729   stack[stack_depth_3] = arg_5(D);
9730   stack_depth_7 = stack_depth_3 + 1;
9731   stack_depth_8 = stack_depth_7 + -1;
9732   x_9 = stack[stack_depth_8];
9733   stack[stack_depth_8] = x_9;
9734   stack_depth_11 = stack_depth_8 + 1;
9735   stack[stack_depth_11] = x_9;
9736   stack_depth_13 = stack_depth_11 + 1;
9737   stack[stack_depth_13] = 2;
9738   stack_depth_15 = stack_depth_13 + 1;
9739   stack_depth_16 = stack_depth_15 + -1;
9740   y_17 = stack[stack_depth_16];
9741   stack_depth_18 = stack_depth_16 + -1;
9742   x_19 = stack[stack_depth_18];
9743   _20 = x_19 < y_17;
9744   _21 = (signed int) _20;
9745   stack[stack_depth_18] = _21;
9746   stack_depth_23 = stack_depth_18 + 1;
9747   stack_depth_24 = stack_depth_23 + -1;
9748   x_25 = stack[stack_depth_24];
9749   if (x_25 != 0)
9750     goto <bb 4> (instr9);
9751   else
9752     goto <bb 3> (instr4);
9754 instr4:
9755 /* DUP */:
9756   stack_depth_26 = stack_depth_24 + -1;
9757   x_27 = stack[stack_depth_26];
9758   stack[stack_depth_26] = x_27;
9759   stack_depth_29 = stack_depth_26 + 1;
9760   stack[stack_depth_29] = x_27;
9761   stack_depth_31 = stack_depth_29 + 1;
9762   stack[stack_depth_31] = 1;
9763   stack_depth_33 = stack_depth_31 + 1;
9764   stack_depth_34 = stack_depth_33 + -1;
9765   y_35 = stack[stack_depth_34];
9766   stack_depth_36 = stack_depth_34 + -1;
9767   x_37 = stack[stack_depth_36];
9768   _38 = x_37 - y_35;
9769   stack[stack_depth_36] = _38;
9770   stack_depth_40 = stack_depth_36 + 1;
9771   stack_depth_41 = stack_depth_40 + -1;
9772   x_42 = stack[stack_depth_41];
9773   _44 = factorial (x_42);
9774   stack[stack_depth_41] = _44;
9775   stack_depth_46 = stack_depth_41 + 1;
9776   stack_depth_47 = stack_depth_46 + -1;
9777   y_48 = stack[stack_depth_47];
9778   stack_depth_49 = stack_depth_47 + -1;
9779   x_50 = stack[stack_depth_49];
9780   _51 = x_50 * y_48;
9781   stack[stack_depth_49] = _51;
9782   stack_depth_53 = stack_depth_49 + 1;
9784   # stack_depth_1 = PHI <stack_depth_24(2), stack_depth_53(3)>
9785 instr9:
9786 /* RETURN */:
9787   stack_depth_54 = stack_depth_1 + -1;
9788   x_55 = stack[stack_depth_54];
9789   _56 = x_55;
9790   stack =@{v@} @{CLOBBER@};
9791   return _56;
9794 @end example
9796 @noindent
9798 Note in the above how all the @code{gccjit::block} instances we
9799 created have been consolidated into just 3 blocks in GCC's internal
9800 representation: @code{initial}, @code{instr4} and @code{instr9}.
9802 @menu
9803 * Optimizing away stack manipulation: Optimizing away stack manipulation<2>. 
9804 * Elimination of tail recursion: Elimination of tail recursion<2>. 
9806 @end menu
9808 @node Optimizing away stack manipulation<2>,Elimination of tail recursion<2>,,Behind the curtain How does our code get optimized?<2>
9809 @anchor{cp/intro/tutorial04 optimizing-away-stack-manipulation}@anchor{fb}
9810 @subsubsection Optimizing away stack manipulation
9813 Recall our simple implementation of stack operations.  Let's examine
9814 how the stack operations are optimized away.
9816 After a pass of constant-propagation, the depth of the stack at each
9817 opcode can be determined at compile-time:
9819 @example
9820 $ less /tmp/libgccjit-1Hywc0/fake.c.021t.ccp1
9821 @end example
9823 @noindent
9825 @example
9826 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9828 factorial (signed int arg)
9830   signed int stack[8];
9831   signed int stack_depth;
9832   signed int x;
9833   signed int y;
9834   <unnamed type> _20;
9835   signed int _21;
9836   signed int _38;
9837   signed int _44;
9838   signed int _51;
9840 initial:
9841   stack[0] = arg_5(D);
9842   x_9 = stack[0];
9843   stack[0] = x_9;
9844   stack[1] = x_9;
9845   stack[2] = 2;
9846   y_17 = stack[2];
9847   x_19 = stack[1];
9848   _20 = x_19 < y_17;
9849   _21 = (signed int) _20;
9850   stack[1] = _21;
9851   x_25 = stack[1];
9852   if (x_25 != 0)
9853     goto <bb 4> (instr9);
9854   else
9855     goto <bb 3> (instr4);
9857 instr4:
9858 /* DUP */:
9859   x_27 = stack[0];
9860   stack[0] = x_27;
9861   stack[1] = x_27;
9862   stack[2] = 1;
9863   y_35 = stack[2];
9864   x_37 = stack[1];
9865   _38 = x_37 - y_35;
9866   stack[1] = _38;
9867   x_42 = stack[1];
9868   _44 = factorial (x_42);
9869   stack[1] = _44;
9870   y_48 = stack[1];
9871   x_50 = stack[0];
9872   _51 = x_50 * y_48;
9873   stack[0] = _51;
9875 instr9:
9876 /* RETURN */:
9877   x_55 = stack[0];
9878   x_56 = x_55;
9879   stack =@{v@} @{CLOBBER@};
9880   return x_56;
9883 @end example
9885 @noindent
9887 Note how, in the above, all those @code{stack_depth} values are now just
9888 constants: we're accessing specific stack locations at each opcode.
9890 The "esra" pass ("Early Scalar Replacement of Aggregates") breaks
9891 out our "stack" array into individual elements:
9893 @example
9894 $ less /tmp/libgccjit-1Hywc0/fake.c.024t.esra
9895 @end example
9897 @noindent
9899 @example
9900 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9902 Created a replacement for stack offset: 0, size: 32: stack$0
9903 Created a replacement for stack offset: 32, size: 32: stack$1
9904 Created a replacement for stack offset: 64, size: 32: stack$2
9906 Symbols to be put in SSA form
9907 @{ D.89 D.90 D.91 @}
9908 Incremental SSA update started at block: 0
9909 Number of blocks in CFG: 5
9910 Number of blocks to update: 4 ( 80%)
9913 factorial (signed int arg)
9915   signed int stack$2;
9916   signed int stack$1;
9917   signed int stack$0;
9918   signed int stack[8];
9919   signed int stack_depth;
9920   signed int x;
9921   signed int y;
9922   <unnamed type> _20;
9923   signed int _21;
9924   signed int _38;
9925   signed int _44;
9926   signed int _51;
9928 initial:
9929   stack$0_45 = arg_5(D);
9930   x_9 = stack$0_45;
9931   stack$0_39 = x_9;
9932   stack$1_32 = x_9;
9933   stack$2_30 = 2;
9934   y_17 = stack$2_30;
9935   x_19 = stack$1_32;
9936   _20 = x_19 < y_17;
9937   _21 = (signed int) _20;
9938   stack$1_28 = _21;
9939   x_25 = stack$1_28;
9940   if (x_25 != 0)
9941     goto <bb 4> (instr9);
9942   else
9943     goto <bb 3> (instr4);
9945 instr4:
9946 /* DUP */:
9947   x_27 = stack$0_39;
9948   stack$0_22 = x_27;
9949   stack$1_14 = x_27;
9950   stack$2_12 = 1;
9951   y_35 = stack$2_12;
9952   x_37 = stack$1_14;
9953   _38 = x_37 - y_35;
9954   stack$1_10 = _38;
9955   x_42 = stack$1_10;
9956   _44 = factorial (x_42);
9957   stack$1_6 = _44;
9958   y_48 = stack$1_6;
9959   x_50 = stack$0_22;
9960   _51 = x_50 * y_48;
9961   stack$0_1 = _51;
9963   # stack$0_52 = PHI <stack$0_39(2), stack$0_1(3)>
9964 instr9:
9965 /* RETURN */:
9966   x_55 = stack$0_52;
9967   x_56 = x_55;
9968   stack =@{v@} @{CLOBBER@};
9969   return x_56;
9972 @end example
9974 @noindent
9976 Hence at this point, all those pushes and pops of the stack are now
9977 simply assignments to specific temporary variables.
9979 After some copy propagation, the stack manipulation has been completely
9980 optimized away:
9982 @example
9983 $ less /tmp/libgccjit-1Hywc0/fake.c.026t.copyprop1
9984 @end example
9986 @noindent
9988 @example
9989 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9991 factorial (signed int arg)
9993   signed int stack$2;
9994   signed int stack$1;
9995   signed int stack$0;
9996   signed int stack[8];
9997   signed int stack_depth;
9998   signed int x;
9999   signed int y;
10000   <unnamed type> _20;
10001   signed int _21;
10002   signed int _38;
10003   signed int _44;
10004   signed int _51;
10006 initial:
10007   stack$0_39 = arg_5(D);
10008   _20 = arg_5(D) <= 1;
10009   _21 = (signed int) _20;
10010   if (_21 != 0)
10011     goto <bb 4> (instr9);
10012   else
10013     goto <bb 3> (instr4);
10015 instr4:
10016 /* DUP */:
10017   _38 = arg_5(D) + -1;
10018   _44 = factorial (_38);
10019   _51 = arg_5(D) * _44;
10020   stack$0_1 = _51;
10022   # stack$0_52 = PHI <arg_5(D)(2), _51(3)>
10023 instr9:
10024 /* RETURN */:
10025   stack =@{v@} @{CLOBBER@};
10026   return stack$0_52;
10029 @end example
10031 @noindent
10033 Later on, another pass finally eliminated @code{stack_depth} local and the
10034 unused parts of the @cite{stack`} array altogether:
10036 @example
10037 $ less /tmp/libgccjit-1Hywc0/fake.c.036t.release_ssa
10038 @end example
10040 @noindent
10042 @example
10043 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
10045 Released 44 names, 314.29%, removed 44 holes
10046 factorial (signed int arg)
10048   signed int stack$0;
10049   signed int mult_acc_1;
10050   <unnamed type> _5;
10051   signed int _6;
10052   signed int _7;
10053   signed int mul_tmp_10;
10054   signed int mult_acc_11;
10055   signed int mult_acc_13;
10057   # arg_9 = PHI <arg_8(D)(0)>
10058   # mult_acc_13 = PHI <1(0)>
10059 initial:
10061   <bb 5>:
10062   # arg_4 = PHI <arg_9(2), _7(3)>
10063   # mult_acc_1 = PHI <mult_acc_13(2), mult_acc_11(3)>
10064   _5 = arg_4 <= 1;
10065   _6 = (signed int) _5;
10066   if (_6 != 0)
10067     goto <bb 4> (instr9);
10068   else
10069     goto <bb 3> (instr4);
10071 instr4:
10072 /* DUP */:
10073   _7 = arg_4 + -1;
10074   mult_acc_11 = mult_acc_1 * arg_4;
10075   goto <bb 5>;
10077   # stack$0_12 = PHI <arg_4(5)>
10078 instr9:
10079 /* RETURN */:
10080   mul_tmp_10 = mult_acc_1 * stack$0_12;
10081   return mul_tmp_10;
10084 @end example
10086 @noindent
10088 @node Elimination of tail recursion<2>,,Optimizing away stack manipulation<2>,Behind the curtain How does our code get optimized?<2>
10089 @anchor{cp/intro/tutorial04 elimination-of-tail-recursion}@anchor{fc}
10090 @subsubsection Elimination of tail recursion
10093 Another significant optimization is the detection that the call to
10094 @code{factorial} is tail recursion, which can be eliminated in favor of
10095 an iteration:
10097 @example
10098 $ less /tmp/libgccjit-1Hywc0/fake.c.030t.tailr1
10099 @end example
10101 @noindent
10103 @example
10104 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
10107 Symbols to be put in SSA form
10108 @{ D.88 @}
10109 Incremental SSA update started at block: 0
10110 Number of blocks in CFG: 5
10111 Number of blocks to update: 4 ( 80%)
10114 factorial (signed int arg)
10116   signed int stack$2;
10117   signed int stack$1;
10118   signed int stack$0;
10119   signed int stack[8];
10120   signed int stack_depth;
10121   signed int x;
10122   signed int y;
10123   signed int mult_acc_1;
10124   <unnamed type> _20;
10125   signed int _21;
10126   signed int _38;
10127   signed int mul_tmp_44;
10128   signed int mult_acc_51;
10130   # arg_5 = PHI <arg_39(D)(0), _38(3)>
10131   # mult_acc_1 = PHI <1(0), mult_acc_51(3)>
10132 initial:
10133   _20 = arg_5 <= 1;
10134   _21 = (signed int) _20;
10135   if (_21 != 0)
10136     goto <bb 4> (instr9);
10137   else
10138     goto <bb 3> (instr4);
10140 instr4:
10141 /* DUP */:
10142   _38 = arg_5 + -1;
10143   mult_acc_51 = mult_acc_1 * arg_5;
10144   goto <bb 2> (initial);
10146   # stack$0_52 = PHI <arg_5(2)>
10147 instr9:
10148 /* RETURN */:
10149   stack =@{v@} @{CLOBBER@};
10150   mul_tmp_44 = mult_acc_1 * stack$0_52;
10151   return mul_tmp_44;
10154 @end example
10156 @noindent
10158 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
10159 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
10160 @c 
10161 @c This is free software: you can redistribute it and/or modify it
10162 @c under the terms of the GNU General Public License as published by
10163 @c the Free Software Foundation, either version 3 of the License, or
10164 @c (at your option) any later version.
10165 @c 
10166 @c This program is distributed in the hope that it will be useful, but
10167 @c WITHOUT ANY WARRANTY; without even the implied warranty of
10168 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10169 @c General Public License for more details.
10170 @c 
10171 @c You should have received a copy of the GNU General Public License
10172 @c along with this program.  If not, see
10173 @c <http://www.gnu.org/licenses/>.
10175 @node Topic Reference<2>,,Tutorial<2>,C++ bindings for libgccjit
10176 @anchor{cp/topics/index doc}@anchor{fd}@anchor{cp/topics/index topic-reference}@anchor{fe}
10177 @section Topic Reference
10180 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
10181 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
10182 @c 
10183 @c This is free software: you can redistribute it and/or modify it
10184 @c under the terms of the GNU General Public License as published by
10185 @c the Free Software Foundation, either version 3 of the License, or
10186 @c (at your option) any later version.
10187 @c 
10188 @c This program is distributed in the hope that it will be useful, but
10189 @c WITHOUT ANY WARRANTY; without even the implied warranty of
10190 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10191 @c General Public License for more details.
10192 @c 
10193 @c You should have received a copy of the GNU General Public License
10194 @c along with this program.  If not, see
10195 @c <http://www.gnu.org/licenses/>.
10197 @menu
10198 * Compilation contexts: Compilation contexts<2>. 
10199 * Objects: Objects<2>. 
10200 * Types: Types<2>. 
10201 * Expressions: Expressions<2>. 
10202 * Creating and using functions: Creating and using functions<2>. 
10203 * Source Locations: Source Locations<2>. 
10204 * Compilation results: Compilation results<2>. 
10206 Compilation contexts
10208 * Lifetime-management: Lifetime-management<2>. 
10209 * Thread-safety: Thread-safety<2>. 
10210 * Error-handling: Error-handling<3>. 
10211 * Debugging: Debugging<2>. 
10212 * Options: Options<4>. 
10214 Options
10216 * String Options: String Options<2>. 
10217 * Boolean options: Boolean options<2>. 
10218 * Integer options: Integer options<2>. 
10220 Types
10222 * Standard types: Standard types<2>. 
10223 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile<2>. 
10224 * Structures and unions: Structures and unions<2>. 
10226 Expressions
10228 * Rvalues: Rvalues<2>. 
10229 * Lvalues: Lvalues<2>. 
10230 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions<2>. 
10232 Rvalues
10234 * Simple expressions: Simple expressions<2>. 
10235 * Unary Operations: Unary Operations<2>. 
10236 * Binary Operations: Binary Operations<2>. 
10237 * Comparisons: Comparisons<2>. 
10238 * Function calls: Function calls<2>. 
10239 * Type-coercion: Type-coercion<2>. 
10241 Lvalues
10243 * Global variables: Global variables<2>. 
10245 Creating and using functions
10247 * Params: Params<2>. 
10248 * Functions: Functions<2>. 
10249 * Blocks: Blocks<2>. 
10250 * Statements: Statements<2>. 
10252 Source Locations
10254 * Faking it: Faking it<2>. 
10256 @end menu
10259 @node Compilation contexts<2>,Objects<2>,,Topic Reference<2>
10260 @anchor{cp/topics/contexts compilation-contexts}@anchor{ff}@anchor{cp/topics/contexts doc}@anchor{100}
10261 @subsection Compilation contexts
10264 @geindex gccjit;;context (C++ class)
10265 @anchor{cp/topics/contexts gccjit context}@anchor{101}
10266 @deffn {C++ Class} gccjit::context
10267 @end deffn
10269 The top-level of the C++ API is the @pxref{101,,gccjit;;context} type.
10271 A @pxref{101,,gccjit;;context} instance encapsulates the state of a
10272 compilation.
10274 You can set up options on it, and add types, functions and code.
10275 Invoking @pxref{da,,gccjit;;context;;compile()} on it gives you a
10276 @pxref{16,,gcc_jit_result *}.
10278 It is a thin wrapper around the C API's @pxref{8,,gcc_jit_context *}.
10280 @menu
10281 * Lifetime-management: Lifetime-management<2>. 
10282 * Thread-safety: Thread-safety<2>. 
10283 * Error-handling: Error-handling<3>. 
10284 * Debugging: Debugging<2>. 
10285 * Options: Options<4>. 
10287 @end menu
10289 @node Lifetime-management<2>,Thread-safety<2>,,Compilation contexts<2>
10290 @anchor{cp/topics/contexts lifetime-management}@anchor{102}
10291 @subsubsection Lifetime-management
10294 Contexts are the unit of lifetime-management within the API: objects
10295 have their lifetime bounded by the context they are created within, and
10296 cleanup of such objects is done for you when the context is released.
10298 @geindex gccjit;;context;;acquire (C++ function)
10299 @anchor{cp/topics/contexts gccjit context acquire}@anchor{d4}
10300 @deffn {C++ Function} gccjit::context gccjit::context::acquire ()
10302 This function acquires a new @pxref{101,,gccjit;;context} instance,
10303 which is independent of any others that may be present within this
10304 process.
10305 @end deffn
10307 @geindex gccjit;;context;;release (C++ function)
10308 @anchor{cp/topics/contexts gccjit context release}@anchor{d6}
10309 @deffn {C++ Function} void gccjit::context::release ()
10311 This function releases all resources associated with the given context.
10312 Both the context itself and all of its @code{gccjit::object *}
10313 instances are cleaned up.  It should be called exactly once on a given
10314 context.
10316 It is invalid to use the context or any of its "contextual" objects
10317 after calling this.
10319 @example
10320 ctxt.release ();
10321 @end example
10323 @noindent
10324 @end deffn
10326 @geindex gccjit;;context;;new_child_context (C++ function)
10327 @anchor{cp/topics/contexts gccjit context new_child_context}@anchor{103}
10328 @deffn {C++ Function} gccjit::context gccjit::context::new_child_context ()
10330 Given an existing JIT context, create a child context.
10332 The child inherits a copy of all option-settings from the parent.
10334 The child can reference objects created within the parent, but not
10335 vice-versa.
10337 The lifetime of the child context must be bounded by that of the
10338 parent: you should release a child context before releasing the parent
10339 context.
10341 If you use a function from a parent context within a child context,
10342 you have to compile the parent context before you can compile the
10343 child context, and the gccjit::result of the parent context must
10344 outlive the gccjit::result of the child context.
10346 This allows caching of shared initializations.  For example, you could
10347 create types and declarations of global functions in a parent context
10348 once within a process, and then create child contexts whenever a
10349 function or loop becomes hot. Each such child context can be used for
10350 JIT-compiling just one function or loop, but can reference types
10351 and helper functions created within the parent context.
10353 Contexts can be arbitrarily nested, provided the above rules are
10354 followed, but it's probably not worth going above 2 or 3 levels, and
10355 there will likely be a performance hit for such nesting.
10356 @end deffn
10358 @node Thread-safety<2>,Error-handling<3>,Lifetime-management<2>,Compilation contexts<2>
10359 @anchor{cp/topics/contexts thread-safety}@anchor{104}
10360 @subsubsection Thread-safety
10363 Instances of @pxref{101,,gccjit;;context} created via
10364 @pxref{d4,,gccjit;;context;;acquire()} are independent from each other:
10365 only one thread may use a given context at once, but multiple threads
10366 could each have their own contexts without needing locks.
10368 Contexts created via @pxref{103,,gccjit;;context;;new_child_context()} are
10369 related to their parent context.  They can be partitioned by their
10370 ultimate ancestor into independent "family trees".   Only one thread
10371 within a process may use a given "family tree" of such contexts at once,
10372 and if you're using multiple threads you should provide your own locking
10373 around entire such context partitions.
10375 @node Error-handling<3>,Debugging<2>,Thread-safety<2>,Compilation contexts<2>
10376 @anchor{cp/topics/contexts error-handling}@anchor{105}
10377 @subsubsection Error-handling
10380 @c FIXME: How does error-handling work for C++ API?
10382 You can only compile and get code from a context if no errors occur.
10384 In general, if an error occurs when using an API entrypoint, it returns
10385 NULL.  You don't have to check everywhere for NULL results, since the
10386 API gracefully handles a NULL being passed in for any argument.
10388 Errors are printed on stderr and can be queried using
10389 @pxref{106,,gccjit;;context;;get_first_error()}.
10391 @geindex gccjit;;context;;get_first_error (C++ function)
10392 @anchor{cp/topics/contexts gccjit context get_first_error__gccjit contextP}@anchor{106}
10393 @deffn {C++ Function} const char* gccjit::context::get_first_error (gccjit::context* ctxt)
10395 Returns the first error message that occurred on the context.
10397 The returned string is valid for the rest of the lifetime of the
10398 context.
10400 If no errors occurred, this will be NULL.
10401 @end deffn
10403 @node Debugging<2>,Options<4>,Error-handling<3>,Compilation contexts<2>
10404 @anchor{cp/topics/contexts debugging}@anchor{107}
10405 @subsubsection Debugging
10408 @geindex gccjit;;context;;dump_to_file (C++ function)
10409 @anchor{cp/topics/contexts gccjit context dump_to_file__ssCR i}@anchor{108}
10410 @deffn {C++ Function} void gccjit::context::dump_to_file (const std::string& path, int update_locations)
10412 To help with debugging: dump a C-like representation to the given path,
10413 describing what's been set up on the context.
10415 If "update_locations" is true, then also set up @pxref{109,,gccjit;;location}
10416 information throughout the context, pointing at the dump file as if it
10417 were a source file.  This may be of use in conjunction with
10418 @code{GCCJIT::BOOL_OPTION_DEBUGINFO} to allow stepping through the
10419 code in a debugger.
10420 @end deffn
10422 @geindex gccjit;;context;;dump_reproducer_to_file (C++ function)
10423 @anchor{cp/topics/contexts gccjit context dump_reproducer_to_file__gcc_jit_contextP cCP}@anchor{10a}
10424 @deffn {C++ Function} void gccjit::context::dump_reproducer_to_file (gcc_jit_context* ctxt, const char* path)
10426 This is a thin wrapper around the C API
10427 @pxref{56,,gcc_jit_context_dump_reproducer_to_file()}, and hence works the
10428 same way.
10430 Note that the generated source is C code, not C++; this might be of use
10431 for seeing what the C++ bindings are doing at the C level.
10432 @end deffn
10434 @node Options<4>,,Debugging<2>,Compilation contexts<2>
10435 @anchor{cp/topics/contexts options}@anchor{10b}
10436 @subsubsection Options
10439 @menu
10440 * String Options: String Options<2>. 
10441 * Boolean options: Boolean options<2>. 
10442 * Integer options: Integer options<2>. 
10444 @end menu
10446 @node String Options<2>,Boolean options<2>,,Options<4>
10447 @anchor{cp/topics/contexts string-options}@anchor{10c}
10448 @subsubsection String Options
10451 @geindex gccjit;;context;;set_str_option (C++ function)
10452 @anchor{cp/topics/contexts gccjit context set_str_option__enum cCP}@anchor{10d}
10453 @deffn {C++ Function} void gccjit::context::set_str_option (enum gcc_jit_str_option, const char* value)
10455 Set a string option of the context.
10457 This is a thin wrapper around the C API
10458 @pxref{5a,,gcc_jit_context_set_str_option()}; the options have the same
10459 meaning.
10460 @end deffn
10462 @node Boolean options<2>,Integer options<2>,String Options<2>,Options<4>
10463 @anchor{cp/topics/contexts boolean-options}@anchor{10e}
10464 @subsubsection Boolean options
10467 @geindex gccjit;;context;;set_bool_option (C++ function)
10468 @anchor{cp/topics/contexts gccjit context set_bool_option__enum i}@anchor{dc}
10469 @deffn {C++ Function} void gccjit::context::set_bool_option (enum gcc_jit_bool_option, int value)
10471 Set a boolean option of the context.
10473 This is a thin wrapper around the C API
10474 @pxref{1b,,gcc_jit_context_set_bool_option()}; the options have the same
10475 meaning.
10476 @end deffn
10478 @node Integer options<2>,,Boolean options<2>,Options<4>
10479 @anchor{cp/topics/contexts integer-options}@anchor{10f}
10480 @subsubsection Integer options
10483 @geindex gccjit;;context;;set_int_option (C++ function)
10484 @anchor{cp/topics/contexts gccjit context set_int_option__enum i}@anchor{dd}
10485 @deffn {C++ Function} void gccjit::context::set_int_option (enum gcc_jit_int_option, int value)
10487 Set an integer option of the context.
10489 This is a thin wrapper around the C API
10490 @pxref{1e,,gcc_jit_context_set_int_option()}; the options have the same
10491 meaning.
10492 @end deffn
10494 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
10495 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
10496 @c 
10497 @c This is free software: you can redistribute it and/or modify it
10498 @c under the terms of the GNU General Public License as published by
10499 @c the Free Software Foundation, either version 3 of the License, or
10500 @c (at your option) any later version.
10501 @c 
10502 @c This program is distributed in the hope that it will be useful, but
10503 @c WITHOUT ANY WARRANTY; without even the implied warranty of
10504 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10505 @c General Public License for more details.
10506 @c 
10507 @c You should have received a copy of the GNU General Public License
10508 @c along with this program.  If not, see
10509 @c <http://www.gnu.org/licenses/>.
10511 @node Objects<2>,Types<2>,Compilation contexts<2>,Topic Reference<2>
10512 @anchor{cp/topics/objects objects}@anchor{110}@anchor{cp/topics/objects doc}@anchor{111}
10513 @subsection Objects
10516 @geindex gccjit;;object (C++ class)
10517 @anchor{cp/topics/objects gccjit object}@anchor{112}
10518 @deffn {C++ Class} gccjit::object
10519 @end deffn
10521 Almost every entity in the API (with the exception of
10522 @pxref{101,,gccjit;;context} and @pxref{16,,gcc_jit_result *}) is a
10523 "contextual" object, a @pxref{112,,gccjit;;object}.
10525 A JIT object:
10527 @quotation
10530 @itemize *
10532 @item 
10533 is associated with a @pxref{101,,gccjit;;context}.
10535 @item 
10536 is automatically cleaned up for you when its context is released so
10537 you don't need to manually track and cleanup all objects, just the
10538 contexts.
10539 @end itemize
10540 @end quotation
10542 The C++ class hierarchy within the @code{gccjit} namespace looks like this:
10544 @example
10545 +- object
10546     +- location
10547     +- type
10548        +- struct
10549     +- field
10550     +- function
10551     +- block
10552     +- rvalue
10553         +- lvalue
10554            +- param
10555 @end example
10557 @noindent
10559 The @pxref{112,,gccjit;;object} base class has the following operations:
10561 @geindex gccjit;;object;;get_context (C++ function)
10562 @anchor{cp/topics/objects gccjit object get_contextC}@anchor{113}
10563 @deffn {C++ Function} gccjit::context gccjit::object::get_context () const
10565 Which context is the obj within?
10566 @end deffn
10568 @geindex gccjit;;object;;get_debug_string (C++ function)
10569 @anchor{cp/topics/objects gccjit object get_debug_stringC}@anchor{d7}
10570 @deffn {C++ Function} std::string gccjit::object::get_debug_string () const
10572 Generate a human-readable description for the given object.
10574 For example,
10576 @example
10577 printf ("obj: %s\n", obj.get_debug_string ().c_str ());
10578 @end example
10580 @noindent
10582 might give this text on stdout:
10584 @example
10585 obj: 4.0 * (float)i
10586 @end example
10588 @noindent
10589 @end deffn
10591 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
10592 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
10593 @c 
10594 @c This is free software: you can redistribute it and/or modify it
10595 @c under the terms of the GNU General Public License as published by
10596 @c the Free Software Foundation, either version 3 of the License, or
10597 @c (at your option) any later version.
10598 @c 
10599 @c This program is distributed in the hope that it will be useful, but
10600 @c WITHOUT ANY WARRANTY; without even the implied warranty of
10601 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10602 @c General Public License for more details.
10603 @c 
10604 @c You should have received a copy of the GNU General Public License
10605 @c along with this program.  If not, see
10606 @c <http://www.gnu.org/licenses/>.
10608 @node Types<2>,Expressions<2>,Objects<2>,Topic Reference<2>
10609 @anchor{cp/topics/types doc}@anchor{114}@anchor{cp/topics/types types}@anchor{115}
10610 @subsection Types
10613 @geindex gccjit;;type (C++ class)
10614 @anchor{cp/topics/types gccjit type}@anchor{116}
10615 @deffn {C++ Class} gccjit::type
10617 gccjit::type represents a type within the library.  It is a subclass
10618 of @pxref{112,,gccjit;;object}.
10619 @end deffn
10621 Types can be created in several ways:
10624 @itemize *
10626 @item 
10627 fundamental types can be accessed using
10628 @pxref{d5,,gccjit;;context;;get_type()}:
10630 @example
10631 gccjit::type int_type = ctxt.get_type (GCC_JIT_TYPE_INT);
10632 @end example
10634 @noindent
10636 or using the @code{gccjit::context::get_int_type} template:
10638 @example
10639 gccjit::type t = ctxt.get_int_type <unsigned short> ();
10640 @end example
10642 @noindent
10644 See @pxref{b,,gcc_jit_context_get_type()} for the available types.
10646 @item 
10647 derived types can be accessed by using functions such as
10648 @pxref{117,,gccjit;;type;;get_pointer()} and @pxref{118,,gccjit;;type;;get_const()}:
10650 @example
10651 gccjit::type const_int_star = int_type.get_const ().get_pointer ();
10652 gccjit::type int_const_star = int_type.get_pointer ().get_const ();
10653 @end example
10655 @noindent
10657 @item 
10658 by creating structures (see below).
10659 @end itemize
10661 @menu
10662 * Standard types: Standard types<2>. 
10663 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile<2>. 
10664 * Structures and unions: Structures and unions<2>. 
10666 @end menu
10668 @node Standard types<2>,Pointers const and volatile<2>,,Types<2>
10669 @anchor{cp/topics/types standard-types}@anchor{119}
10670 @subsubsection Standard types
10673 @geindex gccjit;;context;;get_type (C++ function)
10674 @anchor{cp/topics/types gccjit context get_type__enum}@anchor{d5}
10675 @deffn {C++ Function} gccjit::type gccjit::context::get_type (enum gcc_jit_types)
10677 Access a specific type.  This is a thin wrapper around
10678 @pxref{b,,gcc_jit_context_get_type()}; the parameter has the same meaning.
10679 @end deffn
10681 @geindex gccjit;;context;;get_int_type (C++ function)
10682 @anchor{cp/topics/types gccjit context get_int_type__s i}@anchor{11a}
10683 @deffn {C++ Function} gccjit::type gccjit::context::get_int_type (size_t num_bytes, int is_signed)
10685 Access the integer type of the given size.
10686 @end deffn
10688 @geindex gccjit;;context;;get_int_type<T> (C++ function)
10689 @anchor{cp/topics/types gccjit context get_int_type T}@anchor{11b}
10690 @deffn {C++ Function} gccjit::type gccjit::context::get_int_type<T> ()
10692 Access the given integer type.  For example, you could map the
10693 @code{unsigned short} type into a gccjit::type via:
10695 @example
10696 gccjit::type t = ctxt.get_int_type <unsigned short> ();
10697 @end example
10699 @noindent
10700 @end deffn
10702 @node Pointers const and volatile<2>,Structures and unions<2>,Standard types<2>,Types<2>
10703 @anchor{cp/topics/types pointers-const-and-volatile}@anchor{11c}
10704 @subsubsection Pointers, @cite{const}, and @cite{volatile}
10707 @geindex gccjit;;type;;get_pointer (C++ function)
10708 @anchor{cp/topics/types gccjit type get_pointer}@anchor{117}
10709 @deffn {C++ Function} gccjit::type gccjit::type::get_pointer ()
10711 Given type "T", get type "T*".
10712 @end deffn
10714 @c FIXME: get_const doesn't seem to exist
10716 @geindex gccjit;;type;;get_const (C++ function)
10717 @anchor{cp/topics/types gccjit type get_const}@anchor{118}
10718 @deffn {C++ Function} gccjit::type gccjit::type::get_const ()
10720 Given type "T", get type "const T".
10721 @end deffn
10723 @geindex gccjit;;type;;get_volatile (C++ function)
10724 @anchor{cp/topics/types gccjit type get_volatile}@anchor{11d}
10725 @deffn {C++ Function} gccjit::type gccjit::type::get_volatile ()
10727 Given type "T", get type "volatile T".
10728 @end deffn
10730 @geindex gccjit;;context;;new_array_type (C++ function)
10731 @anchor{cp/topics/types gccjit context new_array_type__gccjit type i gccjit location}@anchor{11e}
10732 @deffn {C++ Function} gccjit::type gccjit::context::new_array_type (gccjit::type element_type, int num_elements, gccjit::location loc)
10734 Given type "T", get type "T[N]" (for a constant N).
10735 Param "loc" is optional.
10736 @end deffn
10738 @node Structures and unions<2>,,Pointers const and volatile<2>,Types<2>
10739 @anchor{cp/topics/types structures-and-unions}@anchor{11f}
10740 @subsubsection Structures and unions
10743 @geindex gccjit;;struct_ (C++ class)
10744 @anchor{cp/topics/types gccjit struct_}@anchor{120}
10745 @deffn {C++ Class} gccjit::struct_
10746 @end deffn
10748 A compound type analagous to a C @cite{struct}.
10750 @pxref{120,,gccjit;;struct_} is a subclass of @pxref{116,,gccjit;;type} (and thus
10751 of @pxref{112,,gccjit;;object} in turn).
10753 @geindex gccjit;;field (C++ class)
10754 @anchor{cp/topics/types gccjit field}@anchor{121}
10755 @deffn {C++ Class} gccjit::field
10756 @end deffn
10758 A field within a @pxref{120,,gccjit;;struct_}.
10760 @pxref{121,,gccjit;;field} is a subclass of @pxref{112,,gccjit;;object}.
10762 You can model C @cite{struct} types by creating @pxref{120,,gccjit;;struct_} and
10763 @pxref{121,,gccjit;;field} instances, in either order:
10766 @itemize *
10768 @item 
10769 by creating the fields, then the structure.  For example, to model:
10771 @example
10772 struct coord @{double x; double y; @};
10773 @end example
10775 @noindent
10777 you could call:
10779 @example
10780 gccjit::field field_x = ctxt.new_field (double_type, "x");
10781 gccjit::field field_y = ctxt.new_field (double_type, "y");
10782 std::vector fields;
10783 fields.push_back (field_x);
10784 fields.push_back (field_y);
10785 gccjit::struct_ coord = ctxt.new_struct_type ("coord", fields);
10786 @end example
10788 @noindent
10790 @item 
10791 by creating the structure, then populating it with fields, typically
10792 to allow modelling self-referential structs such as:
10794 @example
10795 struct node @{ int m_hash; struct node *m_next; @};
10796 @end example
10798 @noindent
10800 like this:
10802 @example
10803 gccjit::struct_ node = ctxt.new_opaque_struct_type ("node");
10804 gccjit::type node_ptr = node.get_pointer ();
10805 gccjit::field field_hash = ctxt.new_field (int_type, "m_hash");
10806 gccjit::field field_next = ctxt.new_field (node_ptr, "m_next");
10807 std::vector fields;
10808 fields.push_back (field_hash);
10809 fields.push_back (field_next);
10810 node.set_fields (fields);
10811 @end example
10813 @noindent
10814 @end itemize
10816 @c FIXME: the above API doesn't seem to exist yet
10818 @geindex gccjit;;context;;new_field (C++ function)
10819 @anchor{cp/topics/types gccjit context new_field__gccjit type cCP gccjit location}@anchor{122}
10820 @deffn {C++ Function} gccjit::field gccjit::context::new_field (gccjit::type type, const char* name, gccjit::location loc)
10822 Construct a new field, with the given type and name.
10823 @end deffn
10825 @geindex gccjit;;context;;new_struct_type (C++ function)
10826 @anchor{cp/topics/types gccjit context new_struct_type__ssCR std vector field R gccjit location}@anchor{123}
10827 @deffn {C++ Function} gccjit::struct_ gccjit::context::new_struct_type (const std::string& name, std::vector<field>& fields, gccjit::location loc)
10829 @quotation
10831 Construct a new struct type, with the given name and fields.
10832 @end quotation
10833 @end deffn
10835 @geindex gccjit;;context;;new_opaque_struct (C++ function)
10836 @anchor{cp/topics/types gccjit context new_opaque_struct__ssCR gccjit location}@anchor{124}
10837 @deffn {C++ Function} gccjit::struct_ gccjit::context::new_opaque_struct (const std::string& name, gccjit::location loc)
10839 Construct a new struct type, with the given name, but without
10840 specifying the fields.   The fields can be omitted (in which case the
10841 size of the struct is not known), or later specified using
10842 @pxref{79,,gcc_jit_struct_set_fields()}.
10843 @end deffn
10845 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
10846 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
10847 @c 
10848 @c This is free software: you can redistribute it and/or modify it
10849 @c under the terms of the GNU General Public License as published by
10850 @c the Free Software Foundation, either version 3 of the License, or
10851 @c (at your option) any later version.
10852 @c 
10853 @c This program is distributed in the hope that it will be useful, but
10854 @c WITHOUT ANY WARRANTY; without even the implied warranty of
10855 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10856 @c General Public License for more details.
10857 @c 
10858 @c You should have received a copy of the GNU General Public License
10859 @c along with this program.  If not, see
10860 @c <http://www.gnu.org/licenses/>.
10862 @node Expressions<2>,Creating and using functions<2>,Types<2>,Topic Reference<2>
10863 @anchor{cp/topics/expressions expressions}@anchor{125}@anchor{cp/topics/expressions doc}@anchor{126}
10864 @subsection Expressions
10867 @menu
10868 * Rvalues: Rvalues<2>. 
10869 * Lvalues: Lvalues<2>. 
10870 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions<2>. 
10872 Rvalues
10874 * Simple expressions: Simple expressions<2>. 
10875 * Unary Operations: Unary Operations<2>. 
10876 * Binary Operations: Binary Operations<2>. 
10877 * Comparisons: Comparisons<2>. 
10878 * Function calls: Function calls<2>. 
10879 * Type-coercion: Type-coercion<2>. 
10881 Lvalues
10883 * Global variables: Global variables<2>. 
10885 @end menu
10888 @node Rvalues<2>,Lvalues<2>,,Expressions<2>
10889 @anchor{cp/topics/expressions rvalues}@anchor{127}
10890 @subsubsection Rvalues
10893 @geindex gccjit;;rvalue (C++ class)
10894 @anchor{cp/topics/expressions gccjit rvalue}@anchor{128}
10895 @deffn {C++ Class} gccjit::rvalue
10896 @end deffn
10898 A @pxref{128,,gccjit;;rvalue} is an expression that can be computed.  It is a
10899 subclass of @pxref{112,,gccjit;;object}, and is a thin wrapper around
10900 @pxref{13,,gcc_jit_rvalue *} from the C API.
10902 It can be simple, e.g.:
10904 @quotation
10907 @itemize *
10909 @item 
10910 an integer value e.g. @cite{0} or @cite{42}
10912 @item 
10913 a string literal e.g. @cite{"Hello world"}
10915 @item 
10916 a variable e.g. @cite{i}.  These are also lvalues (see below).
10917 @end itemize
10918 @end quotation
10920 or compound e.g.:
10922 @quotation
10925 @itemize *
10927 @item 
10928 a unary expression e.g. @cite{!cond}
10930 @item 
10931 a binary expression e.g. @cite{(a + b)}
10933 @item 
10934 a function call e.g. @cite{get_distance (&player_ship@comma{} &target)}
10936 @item 
10937 etc.
10938 @end itemize
10939 @end quotation
10941 Every rvalue has an associated type, and the API will check to ensure
10942 that types match up correctly (otherwise the context will emit an error).
10944 @geindex gccjit;;rvalue;;get_type (C++ function)
10945 @anchor{cp/topics/expressions gccjit rvalue get_type}@anchor{129}
10946 @deffn {C++ Function} gccjit::type gccjit::rvalue::get_type ()
10948 Get the type of this rvalue.
10949 @end deffn
10951 @menu
10952 * Simple expressions: Simple expressions<2>. 
10953 * Unary Operations: Unary Operations<2>. 
10954 * Binary Operations: Binary Operations<2>. 
10955 * Comparisons: Comparisons<2>. 
10956 * Function calls: Function calls<2>. 
10957 * Type-coercion: Type-coercion<2>. 
10959 @end menu
10961 @node Simple expressions<2>,Unary Operations<2>,,Rvalues<2>
10962 @anchor{cp/topics/expressions simple-expressions}@anchor{12a}
10963 @subsubsection Simple expressions
10966 @geindex gccjit;;context;;new_rvalue (C++ function)
10967 @anchor{cp/topics/expressions gccjit context new_rvalue__gccjit type iC}@anchor{e9}
10968 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (gccjit::type numeric_type, int value) const
10970 Given a numeric type (integer or floating point), build an rvalue for
10971 the given constant @code{int} value.
10972 @end deffn
10974 @geindex gccjit;;context;;new_rvalue (C++ function)
10975 @anchor{cp/topics/expressions gccjit context new_rvalue__gccjit type lC}@anchor{12b}
10976 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (gccjit::type numeric_type, long value) const
10978 Given a numeric type (integer or floating point), build an rvalue for
10979 the given constant @code{long} value.
10980 @end deffn
10982 @geindex gccjit;;context;;zero (C++ function)
10983 @anchor{cp/topics/expressions gccjit context zero__gccjit typeC}@anchor{e5}
10984 @deffn {C++ Function} gccjit::rvalue gccjit::context::zero (gccjit::type numeric_type) const
10986 Given a numeric type (integer or floating point), get the rvalue for
10987 zero.  Essentially this is just a shortcut for:
10989 @example
10990 ctxt.new_rvalue (numeric_type, 0)
10991 @end example
10993 @noindent
10994 @end deffn
10996 @geindex gccjit;;context;;one (C++ function)
10997 @anchor{cp/topics/expressions gccjit context one__gccjit typeC}@anchor{12c}
10998 @deffn {C++ Function} gccjit::rvalue gccjit::context::one (gccjit::type numeric_type) const
11000 Given a numeric type (integer or floating point), get the rvalue for
11001 zero.  Essentially this is just a shortcut for:
11003 @example
11004 ctxt.new_rvalue (numeric_type, 1)
11005 @end example
11007 @noindent
11008 @end deffn
11010 @geindex gccjit;;context;;new_rvalue (C++ function)
11011 @anchor{cp/topics/expressions gccjit context new_rvalue__gccjit type doubleC}@anchor{12d}
11012 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (gccjit::type numeric_type, double value) const
11014 Given a numeric type (integer or floating point), build an rvalue for
11015 the given constant @code{double} value.
11016 @end deffn
11018 @geindex gccjit;;context;;new_rvalue (C++ function)
11019 @anchor{cp/topics/expressions gccjit context new_rvalue__gccjit type voidPC}@anchor{12e}
11020 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (gccjit::type pointer_type, void* value) const
11022 Given a pointer type, build an rvalue for the given address.
11023 @end deffn
11025 @geindex gccjit;;context;;new_rvalue (C++ function)
11026 @anchor{cp/topics/expressions gccjit context new_rvalue__ssCRC}@anchor{12f}
11027 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (const std::string& value) const
11029 Generate an rvalue of type @code{GCC_JIT_TYPE_CONST_CHAR_PTR} for
11030 the given string.  This is akin to a string literal.
11031 @end deffn
11033 @node Unary Operations<2>,Binary Operations<2>,Simple expressions<2>,Rvalues<2>
11034 @anchor{cp/topics/expressions unary-operations}@anchor{130}
11035 @subsubsection Unary Operations
11038 @geindex gccjit;;context;;new_unary_op (C++ function)
11039 @anchor{cp/topics/expressions gccjit context new_unary_op__enum gccjit type gccjit rvalue gccjit location}@anchor{131}
11040 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_unary_op (enum gcc_jit_unary_op, gccjit::type result_type, gccjit::rvalue rvalue, gccjit::location loc)
11042 Build a unary operation out of an input rvalue.
11044 Parameter @code{loc} is optional.
11046 This is a thin wrapper around the C API's
11047 @pxref{85,,gcc_jit_context_new_unary_op()} and the available unary
11048 operations are documented there.
11049 @end deffn
11051 There are shorter ways to spell the various specific kinds of unary
11052 operation:
11054 @geindex gccjit;;context;;new_minus (C++ function)
11055 @anchor{cp/topics/expressions gccjit context new_minus__gccjit type gccjit rvalue gccjit location}@anchor{132}
11056 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_minus (gccjit::type result_type, gccjit::rvalue a, gccjit::location loc)
11058 Negate an arithmetic value; for example:
11060 @example
11061 gccjit::rvalue negpi = ctxt.new_minus (t_double, pi);
11062 @end example
11064 @noindent
11066 builds the equivalent of this C expression:
11068 @example
11070 @end example
11072 @noindent
11073 @end deffn
11075 @geindex new_bitwise_negate (C++ function)
11076 @anchor{cp/topics/expressions new_bitwise_negate__gccjit type gccjit rvalue gccjit location}@anchor{133}
11077 @deffn {C++ Function} gccjit::rvalue new_bitwise_negate (gccjit::type result_type, gccjit::rvalue a, gccjit::location loc)
11079 Bitwise negation of an integer value (one's complement); for example:
11081 @example
11082 gccjit::rvalue mask = ctxt.new_bitwise_negate (t_int, a);
11083 @end example
11085 @noindent
11087 builds the equivalent of this C expression:
11089 @example
11091 @end example
11093 @noindent
11094 @end deffn
11096 @geindex new_logical_negate (C++ function)
11097 @anchor{cp/topics/expressions new_logical_negate__gccjit type gccjit rvalue gccjit location}@anchor{134}
11098 @deffn {C++ Function} gccjit::rvalue new_logical_negate (gccjit::type result_type, gccjit::rvalue a, gccjit::location loc)
11100 Logical negation of an arithmetic or pointer value; for example:
11102 @example
11103 gccjit::rvalue guard = ctxt.new_logical_negate (t_bool, cond);
11104 @end example
11106 @noindent
11108 builds the equivalent of this C expression:
11110 @example
11111 !cond
11112 @end example
11114 @noindent
11115 @end deffn
11117 The most concise way to spell them is with overloaded operators:
11119 @geindex operator- (C++ function)
11120 @anchor{cp/topics/expressions sub-operator__gccjit rvalue}@anchor{135}
11121 @deffn {C++ Function} gccjit::rvalue operator- (gccjit::rvalue a)
11123 @example
11124 gccjit::rvalue negpi = -pi;
11125 @end example
11127 @noindent
11128 @end deffn
11130 @geindex operator~ (C++ function)
11131 @anchor{cp/topics/expressions inv-operator__gccjit rvalue}@anchor{136}
11132 @deffn {C++ Function} gccjit::rvalue operator~ (gccjit::rvalue a)
11134 @example
11135 gccjit::rvalue mask = ~a;
11136 @end example
11138 @noindent
11139 @end deffn
11141 @geindex operator! (C++ function)
11142 @anchor{cp/topics/expressions not-operator__gccjit rvalue}@anchor{137}
11143 @deffn {C++ Function} gccjit::rvalue operator! (gccjit::rvalue a)
11145 @example
11146 gccjit::rvalue guard = !cond;
11147 @end example
11149 @noindent
11150 @end deffn
11152 @node Binary Operations<2>,Comparisons<2>,Unary Operations<2>,Rvalues<2>
11153 @anchor{cp/topics/expressions binary-operations}@anchor{138}
11154 @subsubsection Binary Operations
11157 @geindex gccjit;;context;;new_binary_op (C++ function)
11158 @anchor{cp/topics/expressions gccjit context new_binary_op__enum gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{d9}
11159 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_binary_op (enum gcc_jit_binary_op, gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11161 Build a binary operation out of two constituent rvalues.
11163 Parameter @code{loc} is optional.
11165 This is a thin wrapper around the C API's
11166 @pxref{12,,gcc_jit_context_new_binary_op()} and the available binary
11167 operations are documented there.
11168 @end deffn
11170 There are shorter ways to spell the various specific kinds of binary
11171 operation:
11173 @geindex gccjit;;context;;new_plus (C++ function)
11174 @anchor{cp/topics/expressions gccjit context new_plus__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{139}
11175 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_plus (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11176 @end deffn
11178 @geindex gccjit;;context;;new_minus (C++ function)
11179 @anchor{cp/topics/expressions gccjit context new_minus__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{13a}
11180 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_minus (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11181 @end deffn
11183 @geindex gccjit;;context;;new_mult (C++ function)
11184 @anchor{cp/topics/expressions gccjit context new_mult__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{13b}
11185 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_mult (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11186 @end deffn
11188 @geindex gccjit;;context;;new_divide (C++ function)
11189 @anchor{cp/topics/expressions gccjit context new_divide__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{13c}
11190 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_divide (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11191 @end deffn
11193 @geindex gccjit;;context;;new_modulo (C++ function)
11194 @anchor{cp/topics/expressions gccjit context new_modulo__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{13d}
11195 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_modulo (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11196 @end deffn
11198 @geindex gccjit;;context;;new_bitwise_and (C++ function)
11199 @anchor{cp/topics/expressions gccjit context new_bitwise_and__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{13e}
11200 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_bitwise_and (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11201 @end deffn
11203 @geindex gccjit;;context;;new_bitwise_xor (C++ function)
11204 @anchor{cp/topics/expressions gccjit context new_bitwise_xor__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{13f}
11205 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_bitwise_xor (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11206 @end deffn
11208 @geindex gccjit;;context;;new_bitwise_or (C++ function)
11209 @anchor{cp/topics/expressions gccjit context new_bitwise_or__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{140}
11210 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_bitwise_or (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11211 @end deffn
11213 @geindex gccjit;;context;;new_logical_and (C++ function)
11214 @anchor{cp/topics/expressions gccjit context new_logical_and__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{141}
11215 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_logical_and (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11216 @end deffn
11218 @geindex gccjit;;context;;new_logical_or (C++ function)
11219 @anchor{cp/topics/expressions gccjit context new_logical_or__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{142}
11220 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_logical_or (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11221 @end deffn
11223 The most concise way to spell them is with overloaded operators:
11225 @geindex operator+ (C++ function)
11226 @anchor{cp/topics/expressions add-operator__gccjit rvalue gccjit rvalue}@anchor{143}
11227 @deffn {C++ Function} gccjit::rvalue operator+ (gccjit::rvalue a, gccjit::rvalue b)
11229 @example
11230 gccjit::rvalue sum = a + b;
11231 @end example
11233 @noindent
11234 @end deffn
11236 @geindex operator- (C++ function)
11237 @anchor{cp/topics/expressions sub-operator__gccjit rvalue gccjit rvalue}@anchor{144}
11238 @deffn {C++ Function} gccjit::rvalue operator- (gccjit::rvalue a, gccjit::rvalue b)
11240 @example
11241 gccjit::rvalue diff = a - b;
11242 @end example
11244 @noindent
11245 @end deffn
11247 @geindex operator* (C++ function)
11248 @anchor{cp/topics/expressions mul-operator__gccjit rvalue gccjit rvalue}@anchor{145}
11249 @deffn {C++ Function} gccjit::rvalue operator* (gccjit::rvalue a, gccjit::rvalue b)
11251 @example
11252 gccjit::rvalue prod = a * b;
11253 @end example
11255 @noindent
11256 @end deffn
11258 @geindex operator/ (C++ function)
11259 @anchor{cp/topics/expressions div-operator__gccjit rvalue gccjit rvalue}@anchor{146}
11260 @deffn {C++ Function} gccjit::rvalue operator/ (gccjit::rvalue a, gccjit::rvalue b)
11262 @example
11263 gccjit::rvalue result = a / b;
11264 @end example
11266 @noindent
11267 @end deffn
11269 @geindex operator% (C++ function)
11270 @anchor{cp/topics/expressions mod-operator__gccjit rvalue gccjit rvalue}@anchor{147}
11271 @deffn {C++ Function} gccjit::rvalue operator% (gccjit::rvalue a, gccjit::rvalue b)
11273 @example
11274 gccjit::rvalue mod = a % b;
11275 @end example
11277 @noindent
11278 @end deffn
11280 @geindex operator& (C++ function)
11281 @anchor{cp/topics/expressions and-operator__gccjit rvalue gccjit rvalue}@anchor{148}
11282 @deffn {C++ Function} gccjit::rvalue operator& (gccjit::rvalue a, gccjit::rvalue b)
11284 @example
11285 gccjit::rvalue x = a & b;
11286 @end example
11288 @noindent
11289 @end deffn
11291 @geindex operator^ (C++ function)
11292 @anchor{cp/topics/expressions xor-operator__gccjit rvalue gccjit rvalue}@anchor{149}
11293 @deffn {C++ Function} gccjit::rvalue operator^ (gccjit::rvalue a, gccjit::rvalue b)
11295 @example
11296 gccjit::rvalue x = a ^ b;
11297 @end example
11299 @noindent
11300 @end deffn
11302 @geindex operator| (C++ function)
11303 @anchor{cp/topics/expressions or-operator__gccjit rvalue gccjit rvalue}@anchor{14a}
11304 @deffn {C++ Function} gccjit::rvalue operator| (gccjit::rvalue a, gccjit::rvalue b)
11306 @example
11307 gccjit::rvalue x = a | b;
11308 @end example
11310 @noindent
11311 @end deffn
11313 @geindex operator&& (C++ function)
11314 @anchor{cp/topics/expressions sand-operator__gccjit rvalue gccjit rvalue}@anchor{14b}
11315 @deffn {C++ Function} gccjit::rvalue operator&& (gccjit::rvalue a, gccjit::rvalue b)
11317 @example
11318 gccjit::rvalue cond = a && b;
11319 @end example
11321 @noindent
11322 @end deffn
11324 @geindex operator|| (C++ function)
11325 @anchor{cp/topics/expressions sor-operator__gccjit rvalue gccjit rvalue}@anchor{14c}
11326 @deffn {C++ Function} gccjit::rvalue operator|| (gccjit::rvalue a, gccjit::rvalue b)
11328 @example
11329 gccjit::rvalue cond = a || b;
11330 @end example
11332 @noindent
11333 @end deffn
11335 These can of course be combined, giving a terse way to build compound
11336 expressions:
11338 @quotation
11340 @example
11341 gccjit::rvalue discriminant = (b * b) - (four * a * c);
11342 @end example
11344 @noindent
11345 @end quotation
11347 @node Comparisons<2>,Function calls<2>,Binary Operations<2>,Rvalues<2>
11348 @anchor{cp/topics/expressions comparisons}@anchor{14d}
11349 @subsubsection Comparisons
11352 @geindex gccjit;;context;;new_comparison (C++ function)
11353 @anchor{cp/topics/expressions gccjit context new_comparison__enum gccjit rvalue gccjit rvalue gccjit location}@anchor{e6}
11354 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_comparison (enum gcc_jit_comparison, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11356 Build a boolean rvalue out of the comparison of two other rvalues.
11358 Parameter @code{loc} is optional.
11360 This is a thin wrapper around the C API's
11361 @pxref{2c,,gcc_jit_context_new_comparison()} and the available kinds
11362 of comparison are documented there.
11363 @end deffn
11365 There are shorter ways to spell the various specific kinds of binary
11366 operation:
11368 @geindex gccjit;;context;;new_eq (C++ function)
11369 @anchor{cp/topics/expressions gccjit context new_eq__gccjit rvalue gccjit rvalue gccjit location}@anchor{14e}
11370 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_eq (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11371 @end deffn
11373 @geindex gccjit;;context;;new_ne (C++ function)
11374 @anchor{cp/topics/expressions gccjit context new_ne__gccjit rvalue gccjit rvalue gccjit location}@anchor{14f}
11375 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_ne (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11376 @end deffn
11378 @geindex gccjit;;context;;new_lt (C++ function)
11379 @anchor{cp/topics/expressions gccjit context new_lt__gccjit rvalue gccjit rvalue gccjit location}@anchor{150}
11380 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_lt (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11381 @end deffn
11383 @geindex gccjit;;context;;new_le (C++ function)
11384 @anchor{cp/topics/expressions gccjit context new_le__gccjit rvalue gccjit rvalue gccjit location}@anchor{151}
11385 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_le (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11386 @end deffn
11388 @geindex gccjit;;context;;new_gt (C++ function)
11389 @anchor{cp/topics/expressions gccjit context new_gt__gccjit rvalue gccjit rvalue gccjit location}@anchor{152}
11390 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_gt (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11391 @end deffn
11393 @geindex gccjit;;context;;new_ge (C++ function)
11394 @anchor{cp/topics/expressions gccjit context new_ge__gccjit rvalue gccjit rvalue gccjit location}@anchor{153}
11395 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_ge (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11396 @end deffn
11398 The most concise way to spell them is with overloaded operators:
11400 @geindex operator== (C++ function)
11401 @anchor{cp/topics/expressions eq-operator__gccjit rvalue gccjit rvalue}@anchor{154}
11402 @deffn {C++ Function} gccjit::rvalue operator== (gccjit::rvalue a, gccjit::rvalue b)
11404 @example
11405 gccjit::rvalue cond = (a == ctxt.zero (t_int));
11406 @end example
11408 @noindent
11409 @end deffn
11411 @geindex operator!= (C++ function)
11412 @anchor{cp/topics/expressions neq-operator__gccjit rvalue gccjit rvalue}@anchor{155}
11413 @deffn {C++ Function} gccjit::rvalue operator!= (gccjit::rvalue a, gccjit::rvalue b)
11415 @example
11416 gccjit::rvalue cond = (i != j);
11417 @end example
11419 @noindent
11420 @end deffn
11422 @geindex operator< (C++ function)
11423 @anchor{cp/topics/expressions lt-operator__gccjit rvalue gccjit rvalue}@anchor{156}
11424 @deffn {C++ Function} gccjit::rvalue operator< (gccjit::rvalue a, gccjit::rvalue b)
11426 @example
11427 gccjit::rvalue cond = i < n;
11428 @end example
11430 @noindent
11431 @end deffn
11433 @geindex operator<= (C++ function)
11434 @anchor{cp/topics/expressions lte-operator__gccjit rvalue gccjit rvalue}@anchor{157}
11435 @deffn {C++ Function} gccjit::rvalue operator<= (gccjit::rvalue a, gccjit::rvalue b)
11437 @example
11438 gccjit::rvalue cond = i <= n;
11439 @end example
11441 @noindent
11442 @end deffn
11444 @geindex operator> (C++ function)
11445 @anchor{cp/topics/expressions gt-operator__gccjit rvalue gccjit rvalue}@anchor{158}
11446 @deffn {C++ Function} gccjit::rvalue operator> (gccjit::rvalue a, gccjit::rvalue b)
11448 @example
11449 gccjit::rvalue cond = (ch > limit);
11450 @end example
11452 @noindent
11453 @end deffn
11455 @geindex operator>= (C++ function)
11456 @anchor{cp/topics/expressions gte-operator__gccjit rvalue gccjit rvalue}@anchor{159}
11457 @deffn {C++ Function} gccjit::rvalue operator>= (gccjit::rvalue a, gccjit::rvalue b)
11459 @example
11460 gccjit::rvalue cond = (score >= ctxt.new_rvalue (t_int, 100));
11461 @end example
11463 @noindent
11464 @end deffn
11466 @c TODO: beyond this point
11468 @node Function calls<2>,Type-coercion<2>,Comparisons<2>,Rvalues<2>
11469 @anchor{cp/topics/expressions function-calls}@anchor{15a}
11470 @subsubsection Function calls
11473 @geindex gcc_jit_context_new_call (C++ function)
11474 @anchor{cp/topics/expressions gcc_jit_context_new_call__gcc_jit_contextP gcc_jit_locationP gcc_jit_functionP i gcc_jit_rvaluePP}@anchor{15b}
11475 @deffn {C++ Function} gcc_jit_rvalue* gcc_jit_context_new_call (gcc_jit_context* ctxt, gcc_jit_location* loc, gcc_jit_function* func, int numargs, gcc_jit_rvalue** args)
11477 Given a function and the given table of argument rvalues, construct a
11478 call to the function, with the result as an rvalue.
11480 @cartouche
11481 @quotation Note 
11482 @code{gccjit::context::new_call()} merely builds a
11483 @pxref{128,,gccjit;;rvalue} i.e. an expression that can be evaluated,
11484 perhaps as part of a more complicated expression.
11485 The call @emph{won't} happen unless you add a statement to a function
11486 that evaluates the expression.
11488 For example, if you want to call a function and discard the result
11489 (or to call a function with @code{void} return type), use
11490 @pxref{15c,,gccjit;;block;;add_eval()}:
11492 @example
11493 /* Add "(void)printf (arg0, arg1);".  */
11494 block.add_eval (ctxt.new_call (printf_func, arg0, arg1));
11495 @end example
11497 @noindent
11498 @end quotation
11499 @end cartouche
11500 @end deffn
11502 @node Type-coercion<2>,,Function calls<2>,Rvalues<2>
11503 @anchor{cp/topics/expressions type-coercion}@anchor{15d}
11504 @subsubsection Type-coercion
11507 @geindex gccjit;;context;;new_cast (C++ function)
11508 @anchor{cp/topics/expressions gccjit context new_cast__gccjit rvalue gccjit type gccjit location}@anchor{15e}
11509 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_cast (gccjit::rvalue rvalue, gccjit::type type, gccjit::location loc)
11511 Given an rvalue of T, construct another rvalue of another type.
11513 Currently only a limited set of conversions are possible:
11515 @quotation
11518 @itemize *
11520 @item 
11521 int <-> float
11523 @item 
11524 int <-> bool
11526 @item 
11527 P*  <-> Q*, for pointer types P and Q
11528 @end itemize
11529 @end quotation
11530 @end deffn
11532 @node Lvalues<2>,Working with pointers structs and unions<2>,Rvalues<2>,Expressions<2>
11533 @anchor{cp/topics/expressions lvalues}@anchor{15f}
11534 @subsubsection Lvalues
11537 @geindex gccjit;;lvalue (C++ class)
11538 @anchor{cp/topics/expressions gccjit lvalue}@anchor{160}
11539 @deffn {C++ Class} gccjit::lvalue
11540 @end deffn
11542 An lvalue is something that can of the @emph{left}-hand side of an assignment:
11543 a storage area (such as a variable).  It is a subclass of
11544 @pxref{128,,gccjit;;rvalue}, where the rvalue is computed by reading from the
11545 storage area.
11547 It iss a thin wrapper around @pxref{24,,gcc_jit_lvalue *} from the C API.
11549 @geindex gccjit;;lvalue;;get_address (C++ function)
11550 @anchor{cp/topics/expressions gccjit lvalue get_address__gccjit location}@anchor{161}
11551 @deffn {C++ Function} gccjit::rvalue gccjit::lvalue::get_address (gccjit::location loc)
11553 Take the address of an lvalue; analogous to:
11555 @example
11556 &(EXPR)
11557 @end example
11559 @noindent
11561 in C.
11563 Parameter "loc" is optional.
11564 @end deffn
11566 @menu
11567 * Global variables: Global variables<2>. 
11569 @end menu
11571 @node Global variables<2>,,,Lvalues<2>
11572 @anchor{cp/topics/expressions global-variables}@anchor{162}
11573 @subsubsection Global variables
11576 @geindex gccjit;;context;;new_global (C++ function)
11577 @anchor{cp/topics/expressions gccjit context new_global__enum gccjit type cCP gccjit location}@anchor{163}
11578 @deffn {C++ Function} gccjit::lvalue gccjit::context::new_global (enum gcc_jit_global_kind, gccjit::type type, const char* name, gccjit::location loc)
11580 Add a new global variable of the given type and name to the context.
11582 This is a thin wrapper around @pxref{a5,,gcc_jit_context_new_global()} from
11583 the C API; the "kind" parameter has the same meaning as there.
11584 @end deffn
11586 @node Working with pointers structs and unions<2>,,Lvalues<2>,Expressions<2>
11587 @anchor{cp/topics/expressions working-with-pointers-structs-and-unions}@anchor{164}
11588 @subsubsection Working with pointers, structs and unions
11591 @geindex gccjit;;rvalue;;dereference (C++ function)
11592 @anchor{cp/topics/expressions gccjit rvalue dereference__gccjit location}@anchor{165}
11593 @deffn {C++ Function} gccjit::lvalue gccjit::rvalue::dereference (gccjit::location loc)
11595 Given an rvalue of pointer type @code{T *}, dereferencing the pointer,
11596 getting an lvalue of type @code{T}.  Analogous to:
11598 @example
11599 *(EXPR)
11600 @end example
11602 @noindent
11604 in C.
11606 Parameter "loc" is optional.
11607 @end deffn
11609 If you don't need to specify the location, this can also be expressed using
11610 an overloaded operator:
11613 @deffn {C++ Function} gccjit::lvalue            gccjit::rvalue::operator* ();
11615 @example
11616 gccjit::lvalue content = *ptr;
11617 @end example
11619 @noindent
11620 @end deffn
11622 Field access is provided separately for both lvalues and rvalues:
11624 @geindex gccjit;;lvalue;;access_field (C++ function)
11625 @anchor{cp/topics/expressions gccjit lvalue access_field__gccjit field gccjit location}@anchor{166}
11626 @deffn {C++ Function} gccjit::lvalue gccjit::lvalue::access_field (gccjit::field field, gccjit::location loc)
11628 Given an lvalue of struct or union type, access the given field,
11629 getting an lvalue of the field's type.  Analogous to:
11631 @example
11632 (EXPR).field = ...;
11633 @end example
11635 @noindent
11637 in C.
11638 @end deffn
11640 @geindex gccjit;;rvalue;;access_field (C++ function)
11641 @anchor{cp/topics/expressions gccjit rvalue access_field__gccjit field gccjit location}@anchor{167}
11642 @deffn {C++ Function} gccjit::rvalue gccjit::rvalue::access_field (gccjit::field field, gccjit::location loc)
11644 Given an rvalue of struct or union type, access the given field
11645 as an rvalue.  Analogous to:
11647 @example
11648 (EXPR).field
11649 @end example
11651 @noindent
11653 in C.
11654 @end deffn
11656 @geindex gccjit;;rvalue;;dereference_field (C++ function)
11657 @anchor{cp/topics/expressions gccjit rvalue dereference_field__gccjit field gccjit location}@anchor{168}
11658 @deffn {C++ Function} gccjit::lvalue gccjit::rvalue::dereference_field (gccjit::field field, gccjit::location loc)
11660 Given an rvalue of pointer type @code{T *} where T is of struct or union
11661 type, access the given field as an lvalue.  Analogous to:
11663 @example
11664 (EXPR)->field
11665 @end example
11667 @noindent
11669 in C, itself equivalent to @code{(*EXPR).FIELD}.
11670 @end deffn
11672 @geindex gccjit;;context;;new_array_access (C++ function)
11673 @anchor{cp/topics/expressions gccjit context new_array_access__gccjit rvalue gccjit rvalue gccjit location}@anchor{169}
11674 @deffn {C++ Function} gccjit::lvalue gccjit::context::new_array_access (gccjit::rvalue ptr, gccjit::rvalue index, gccjit::location loc)
11676 Given an rvalue of pointer type @code{T *}, get at the element @cite{T} at
11677 the given index, using standard C array indexing rules i.e. each
11678 increment of @code{index} corresponds to @code{sizeof(T)} bytes.
11679 Analogous to:
11681 @example
11682 PTR[INDEX]
11683 @end example
11685 @noindent
11687 in C (or, indeed, to @code{PTR + INDEX}).
11689 Parameter "loc" is optional.
11690 @end deffn
11692 For array accesses where you don't need to specify a @pxref{109,,gccjit;;location},
11693 two overloaded operators are available:
11695 @quotation
11697 gccjit::lvalue gccjit::rvalue::operator[] (gccjit::rvalue index)
11699 @example
11700 gccjit::lvalue element = array[idx];
11701 @end example
11703 @noindent
11705 gccjit::lvalue gccjit::rvalue::operator[] (int index)
11707 @example
11708 gccjit::lvalue element = array[0];
11709 @end example
11711 @noindent
11712 @end quotation
11714 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
11715 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
11716 @c 
11717 @c This is free software: you can redistribute it and/or modify it
11718 @c under the terms of the GNU General Public License as published by
11719 @c the Free Software Foundation, either version 3 of the License, or
11720 @c (at your option) any later version.
11721 @c 
11722 @c This program is distributed in the hope that it will be useful, but
11723 @c WITHOUT ANY WARRANTY; without even the implied warranty of
11724 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11725 @c General Public License for more details.
11726 @c 
11727 @c You should have received a copy of the GNU General Public License
11728 @c along with this program.  If not, see
11729 @c <http://www.gnu.org/licenses/>.
11731 @node Creating and using functions<2>,Source Locations<2>,Expressions<2>,Topic Reference<2>
11732 @anchor{cp/topics/functions doc}@anchor{16a}@anchor{cp/topics/functions creating-and-using-functions}@anchor{16b}
11733 @subsection Creating and using functions
11736 @menu
11737 * Params: Params<2>. 
11738 * Functions: Functions<2>. 
11739 * Blocks: Blocks<2>. 
11740 * Statements: Statements<2>. 
11742 @end menu
11744 @node Params<2>,Functions<2>,,Creating and using functions<2>
11745 @anchor{cp/topics/functions params}@anchor{16c}
11746 @subsubsection Params
11749 @geindex gccjit;;param (C++ class)
11750 @anchor{cp/topics/functions gccjit param}@anchor{16d}
11751 @deffn {C++ Class} gccjit::param
11753 A @cite{gccjit::param} represents a parameter to a function.
11754 @end deffn
11756 @geindex gccjit;;context;;new_param (C++ function)
11757 @anchor{cp/topics/functions gccjit context new_param__gccjit type cCP gccjit location}@anchor{d8}
11758 @deffn {C++ Function} gccjit::param gccjit::context::new_param (gccjit::type type, const char* name, gccjit::location loc)
11760 In preparation for creating a function, create a new parameter of the
11761 given type and name.
11762 @end deffn
11764 @pxref{16d,,gccjit;;param} is a subclass of @pxref{160,,gccjit;;lvalue} (and thus
11765 of @pxref{128,,gccjit;;rvalue} and @pxref{112,,gccjit;;object}).  It is a thin
11766 wrapper around the C API's @pxref{25,,gcc_jit_param *}.
11768 @node Functions<2>,Blocks<2>,Params<2>,Creating and using functions<2>
11769 @anchor{cp/topics/functions functions}@anchor{16e}
11770 @subsubsection Functions
11773 @geindex gccjit;;function (C++ class)
11774 @anchor{cp/topics/functions gccjit function}@anchor{16f}
11775 @deffn {C++ Class} gccjit::function
11777 A @cite{gccjit::function} represents a function - either one that we're
11778 creating ourselves, or one that we're referencing.
11779 @end deffn
11782 @deffn {C++ Function} gccjit::function             gccjit::context::new_function (enum gcc_jit_function_kind,                                           gccjit::type return_type,                                            const char *name,                                            std::vector<param> &params,                                            int is_variadic,                                            gccjit::location loc) \
11784 Create a gcc_jit_function with the given name and parameters.
11786 Parameters "is_variadic" and "loc" are optional.
11788 This is a wrapper around the C API's @pxref{11,,gcc_jit_context_new_function()}.
11789 @end deffn
11791 @geindex gccjit;;context;;get_builtin_function (C++ function)
11792 @anchor{cp/topics/functions gccjit context get_builtin_function__cCP}@anchor{170}
11793 @deffn {C++ Function} gccjit::function gccjit::context::get_builtin_function (const char* name)
11795 This is a wrapper around the C API's
11796 @pxref{bc,,gcc_jit_context_get_builtin_function()}.
11797 @end deffn
11799 @geindex gccjit;;function;;get_param (C++ function)
11800 @anchor{cp/topics/functions gccjit function get_param__iC}@anchor{171}
11801 @deffn {C++ Function} gccjit::param gccjit::function::get_param (int index) const
11803 Get the param of the given index (0-based).
11804 @end deffn
11806 @geindex gccjit;;function;;dump_to_dot (C++ function)
11807 @anchor{cp/topics/functions gccjit function dump_to_dot__cCP}@anchor{eb}
11808 @deffn {C++ Function} void gccjit::function::dump_to_dot (const char* path)
11810 Emit the function in graphviz format to the given path.
11811 @end deffn
11813 @geindex gccjit;;function;;new_local (C++ function)
11814 @anchor{cp/topics/functions gccjit function new_local__gccjit type cCP gccjit location}@anchor{e2}
11815 @deffn {C++ Function} gccjit::lvalue gccjit::function::new_local (gccjit::type type, const char* name, gccjit::location loc)
11817 Create a new local variable within the function, of the given type and
11818 name.
11819 @end deffn
11821 @node Blocks<2>,Statements<2>,Functions<2>,Creating and using functions<2>
11822 @anchor{cp/topics/functions blocks}@anchor{172}
11823 @subsubsection Blocks
11826 @geindex gccjit;;block (C++ class)
11827 @anchor{cp/topics/functions gccjit block}@anchor{173}
11828 @deffn {C++ Class} gccjit::block
11830 A @cite{gccjit::block} represents a basic block within a function  i.e. a
11831 sequence of statements with a single entry point and a single exit
11832 point.
11834 @pxref{173,,gccjit;;block} is a subclass of @pxref{112,,gccjit;;object}.
11836 The first basic block that you create within a function will
11837 be the entrypoint.
11839 Each basic block that you create within a function must be
11840 terminated, either with a conditional, a jump, or a return.
11842 It's legal to have multiple basic blocks that return within
11843 one function.
11844 @end deffn
11846 @geindex gccjit;;function;;new_block (C++ function)
11847 @anchor{cp/topics/functions gccjit function new_block__cCP}@anchor{174}
11848 @deffn {C++ Function} gccjit::block gccjit::function::new_block (const char* name)
11850 Create a basic block of the given name.  The name may be NULL, but
11851 providing meaningful names is often helpful when debugging: it may
11852 show up in dumps of the internal representation, and in error
11853 messages.
11854 @end deffn
11856 @node Statements<2>,,Blocks<2>,Creating and using functions<2>
11857 @anchor{cp/topics/functions statements}@anchor{175}
11858 @subsubsection Statements
11861 @geindex gccjit;;block;;add_eval (C++ function)
11862 @anchor{cp/topics/functions gccjit block add_eval__gccjit rvalue gccjit location}@anchor{15c}
11863 @deffn {C++ Function} void gccjit::block::add_eval (gccjit::rvalue rvalue, gccjit::location loc)
11865 Add evaluation of an rvalue, discarding the result
11866 (e.g. a function call that "returns" void).
11868 This is equivalent to this C code:
11870 @example
11871 (void)expression;
11872 @end example
11874 @noindent
11875 @end deffn
11877 @geindex gccjit;;block;;add_assignment (C++ function)
11878 @anchor{cp/topics/functions gccjit block add_assignment__gccjit lvalue gccjit rvalue gccjit location}@anchor{e4}
11879 @deffn {C++ Function} void gccjit::block::add_assignment (gccjit::lvalue lvalue, gccjit::rvalue rvalue, gccjit::location loc)
11881 Add evaluation of an rvalue, assigning the result to the given
11882 lvalue.
11884 This is roughly equivalent to this C code:
11886 @example
11887 lvalue = rvalue;
11888 @end example
11890 @noindent
11891 @end deffn
11893 @geindex gccjit;;block;;add_assignment_op (C++ function)
11894 @anchor{cp/topics/functions gccjit block add_assignment_op__gccjit lvalue enum gccjit rvalue gccjit location}@anchor{e8}
11895 @deffn {C++ Function} void gccjit::block::add_assignment_op (gccjit::lvalue lvalue, enum gcc_jit_binary_op, gccjit::rvalue rvalue, gccjit::location loc)
11897 Add evaluation of an rvalue, using the result to modify an
11898 lvalue.
11900 This is analogous to "+=" and friends:
11902 @example
11903 lvalue += rvalue;
11904 lvalue *= rvalue;
11905 lvalue /= rvalue;
11906 @end example
11908 @noindent
11910 etc.  For example:
11912 @example
11913 /* "i++" */
11914 loop_body.add_assignment_op (
11915   i,
11916   GCC_JIT_BINARY_OP_PLUS,
11917   ctxt.one (int_type));
11918 @end example
11920 @noindent
11921 @end deffn
11923 @geindex gccjit;;block;;add_comment (C++ function)
11924 @anchor{cp/topics/functions gccjit block add_comment__cCP gccjit location}@anchor{f3}
11925 @deffn {C++ Function} void gccjit::block::add_comment (const char* text, gccjit::location loc)
11927 Add a no-op textual comment to the internal representation of the
11928 code.  It will be optimized away, but will be visible in the dumps
11929 seen via @pxref{5f,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE}
11930 and @pxref{1c,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE},
11931 and thus may be of use when debugging how your project's internal
11932 representation gets converted to the libgccjit IR.
11934 Parameter "loc" is optional.
11935 @end deffn
11937 @geindex gccjit;;block;;end_with_conditional (C++ function)
11938 @anchor{cp/topics/functions gccjit block end_with_conditional__gccjit rvalue gccjit block gccjit block gccjit location}@anchor{e7}
11939 @deffn {C++ Function} void gccjit::block::end_with_conditional (gccjit::rvalue boolval, gccjit::block on_true, gccjit::block on_false, gccjit::location loc)
11941 Terminate a block by adding evaluation of an rvalue, branching on the
11942 result to the appropriate successor block.
11944 This is roughly equivalent to this C code:
11946 @example
11947 if (boolval)
11948   goto on_true;
11949 else
11950   goto on_false;
11951 @end example
11953 @noindent
11955 block, boolval, on_true, and on_false must be non-NULL.
11956 @end deffn
11958 @geindex gccjit;;block;;end_with_jump (C++ function)
11959 @anchor{cp/topics/functions gccjit block end_with_jump__gccjit block gccjit location}@anchor{176}
11960 @deffn {C++ Function} void gccjit::block::end_with_jump (gccjit::block target, gccjit::location loc)
11962 Terminate a block by adding a jump to the given target block.
11964 This is roughly equivalent to this C code:
11966 @example
11967 goto target;
11968 @end example
11970 @noindent
11971 @end deffn
11973 @geindex gccjit;;block;;end_with_return (C++ function)
11974 @anchor{cp/topics/functions gccjit block end_with_return__gccjit rvalue gccjit location}@anchor{177}
11975 @deffn {C++ Function} void gccjit::block::end_with_return (gccjit::rvalue rvalue, gccjit::location loc)
11977 Terminate a block.
11979 Both params are optional.
11981 An rvalue must be provided for a function returning non-void, and
11982 must not be provided by a function "returning" @cite{void}.
11984 If an rvalue is provided, the block is terminated by evaluating the
11985 rvalue and returning the value.
11987 This is roughly equivalent to this C code:
11989 @example
11990 return expression;
11991 @end example
11993 @noindent
11995 If an rvalue is not provided, the block is terminated by adding a
11996 valueless return, for use within a function with "void" return type.
11998 This is equivalent to this C code:
12000 @example
12001 return;
12002 @end example
12004 @noindent
12005 @end deffn
12007 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
12008 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
12009 @c 
12010 @c This is free software: you can redistribute it and/or modify it
12011 @c under the terms of the GNU General Public License as published by
12012 @c the Free Software Foundation, either version 3 of the License, or
12013 @c (at your option) any later version.
12014 @c 
12015 @c This program is distributed in the hope that it will be useful, but
12016 @c WITHOUT ANY WARRANTY; without even the implied warranty of
12017 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12018 @c General Public License for more details.
12019 @c 
12020 @c You should have received a copy of the GNU General Public License
12021 @c along with this program.  If not, see
12022 @c <http://www.gnu.org/licenses/>.
12024 @node Source Locations<2>,Compilation results<2>,Creating and using functions<2>,Topic Reference<2>
12025 @anchor{cp/topics/locations source-locations}@anchor{178}@anchor{cp/topics/locations doc}@anchor{179}
12026 @subsection Source Locations
12029 @geindex gccjit;;location (C++ class)
12030 @anchor{cp/topics/locations gccjit location}@anchor{109}
12031 @deffn {C++ Class} gccjit::location
12033 A @cite{gccjit::location} encapsulates a source code location, so that
12034 you can (optionally) associate locations in your language with
12035 statements in the JIT-compiled code, allowing the debugger to
12036 single-step through your language.
12038 @cite{gccjit::location} instances are optional: you can always omit them
12039 from any C++ API entrypoint accepting one.
12041 You can construct them using @pxref{f7,,gccjit;;context;;new_location()}.
12043 You need to enable @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} on the
12044 @pxref{101,,gccjit;;context} for these locations to actually be usable by
12045 the debugger:
12047 @example
12048 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DEBUGINFO, 1);
12049 @end example
12051 @noindent
12052 @end deffn
12054 @geindex gccjit;;context;;new_location (C++ function)
12055 @anchor{cp/topics/locations gccjit context new_location__cCP i i}@anchor{f7}
12056 @deffn {C++ Function} gccjit::location gccjit::context::new_location (const char* filename, int line, int column)
12058 Create a @cite{gccjit::location} instance representing the given source
12059 location.
12060 @end deffn
12062 @menu
12063 * Faking it: Faking it<2>. 
12065 @end menu
12067 @node Faking it<2>,,,Source Locations<2>
12068 @anchor{cp/topics/locations faking-it}@anchor{17a}
12069 @subsubsection Faking it
12072 If you don't have source code for your internal representation, but need
12073 to debug, you can generate a C-like representation of the functions in
12074 your context using @pxref{108,,gccjit;;context;;dump_to_file()}:
12076 @example
12077 ctxt.dump_to_file ("/tmp/something.c",
12078                    1 /* update_locations */);
12079 @end example
12081 @noindent
12083 This will dump C-like code to the given path.  If the @cite{update_locations}
12084 argument is true, this will also set up @cite{gccjit::location} information
12085 throughout the context, pointing at the dump file as if it were a source
12086 file, giving you @emph{something} you can step through in the debugger.
12088 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
12089 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
12090 @c 
12091 @c This is free software: you can redistribute it and/or modify it
12092 @c under the terms of the GNU General Public License as published by
12093 @c the Free Software Foundation, either version 3 of the License, or
12094 @c (at your option) any later version.
12095 @c 
12096 @c This program is distributed in the hope that it will be useful, but
12097 @c WITHOUT ANY WARRANTY; without even the implied warranty of
12098 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12099 @c General Public License for more details.
12100 @c 
12101 @c You should have received a copy of the GNU General Public License
12102 @c along with this program.  If not, see
12103 @c <http://www.gnu.org/licenses/>.
12105 @node Compilation results<2>,,Source Locations<2>,Topic Reference<2>
12106 @anchor{cp/topics/results compilation-results}@anchor{17b}@anchor{cp/topics/results doc}@anchor{17c}
12107 @subsection Compilation results
12110 @geindex gcc_jit_result (C++ type)
12111 @anchor{cp/topics/results gcc_jit_result}@anchor{17d}
12112 @deffn {C++ Type} gcc_jit_result
12114 A @cite{gcc_jit_result} encapsulates the result of compiling a context.
12115 @end deffn
12117 @geindex gccjit;;context;;compile (C++ function)
12118 @anchor{cp/topics/results gccjit context compile}@anchor{da}
12119 @deffn {C++ Function} @pxref{17d,,gcc_jit_result*} gccjit::context::compile ()
12121 This calls into GCC and builds the code, returning a
12122 @cite{gcc_jit_result *}.
12123 @end deffn
12125 @geindex gcc_jit_result_get_code (C++ function)
12126 @anchor{cp/topics/results gcc_jit_result_get_code__gcc_jit_resultP cCP}@anchor{17e}
12127 @deffn {C++ Function} void* gcc_jit_result_get_code (gcc_jit_result* result, const char* funcname)
12129 Locate a given function within the built machine code.
12130 This will need to be cast to a function pointer of the
12131 correct type before it can be called.
12132 @end deffn
12134 @geindex gcc_jit_result_release (C++ function)
12135 @anchor{cp/topics/results gcc_jit_result_release__gcc_jit_resultP}@anchor{17f}
12136 @deffn {C++ Function} void gcc_jit_result_release (gcc_jit_result* result)
12138 Once we're done with the code, this unloads the built .so file.
12139 This cleans up the result; after calling this, it's no longer
12140 valid to use the result.
12141 @end deffn
12143 @c Copyright (C) 2014-2015 Free Software Foundation, Inc.
12144 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
12145 @c 
12146 @c This is free software: you can redistribute it and/or modify it
12147 @c under the terms of the GNU General Public License as published by
12148 @c the Free Software Foundation, either version 3 of the License, or
12149 @c (at your option) any later version.
12150 @c 
12151 @c This program is distributed in the hope that it will be useful, but
12152 @c WITHOUT ANY WARRANTY; without even the implied warranty of
12153 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12154 @c General Public License for more details.
12155 @c 
12156 @c You should have received a copy of the GNU General Public License
12157 @c along with this program.  If not, see
12158 @c <http://www.gnu.org/licenses/>.
12160 @node Internals,Indices and tables,C++ bindings for libgccjit,Top
12161 @anchor{internals/index internals}@anchor{180}@anchor{internals/index doc}@anchor{181}
12162 @chapter Internals
12165 @menu
12166 * Working on the JIT library:: 
12167 * Running the test suite:: 
12168 * Environment variables:: 
12169 * Overview of code structure:: 
12170 * Design notes:: 
12172 @end menu
12174 @node Working on the JIT library,Running the test suite,,Internals
12175 @anchor{internals/index working-on-the-jit-library}@anchor{182}
12176 @section Working on the JIT library
12179 Having checked out the source code (to "src"), you can configure and build
12180 the JIT library like this:
12182 @example
12183 mkdir build
12184 mkdir install
12185 PREFIX=$(pwd)/install
12186 cd build
12187 ../src/configure \
12188    --enable-host-shared \
12189    --enable-languages=jit,c++ \
12190    --disable-bootstrap \
12191    --enable-checking=release \
12192    --prefix=$PREFIX
12193 nice make -j4 # altering the "4" to however many cores you have
12194 @end example
12196 @noindent
12198 This should build a libgccjit.so within jit/build/gcc:
12200 @example
12201 [build] $ file gcc/libgccjit.so*
12202 gcc/libgccjit.so:       symbolic link to `libgccjit.so.0'
12203 gcc/libgccjit.so.0:     symbolic link to `libgccjit.so.0.0.1'
12204 gcc/libgccjit.so.0.0.1: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, not stripped
12205 @end example
12207 @noindent
12209 Here's what those configuration options mean:
12211 @geindex command line option; --enable-host-shared
12212 @anchor{internals/index cmdoption--enable-host-shared}@anchor{183}
12213 @deffn {Option} --enable-host-shared
12215 Configuring with this option means that the compiler is built as
12216 position-independent code, which incurs a slight performance hit,
12217 but it necessary for a shared library.
12218 @end deffn
12220 @geindex command line option; --enable-languages=jit@comma{}c++
12221 @anchor{internals/index cmdoption--enable-languages}@anchor{184}
12222 @deffn {Option} --enable-languages=jit,c++
12224 This specifies which frontends to build.  The JIT library looks like
12225 a frontend to the rest of the code.
12227 The C++ portion of the JIT test suite requires the C++ frontend to be
12228 enabled at configure-time, or you may see errors like this when
12229 running the test suite:
12231 @example
12232 xgcc: error: /home/david/jit/src/gcc/testsuite/jit.dg/test-quadratic.cc: C++ compiler not installed on this system
12233 c++: error trying to exec 'cc1plus': execvp: No such file or directory
12234 @end example
12236 @noindent
12237 @end deffn
12239 @geindex command line option; --disable-bootstrap
12240 @anchor{internals/index cmdoption--disable-bootstrap}@anchor{185}
12241 @deffn {Option} --disable-bootstrap
12243 For hacking on the "jit" subdirectory, performing a full
12244 bootstrap can be overkill, since it's unused by a bootstrap.  However,
12245 when submitting patches, you should remove this option, to ensure that
12246 the compiler can still bootstrap itself.
12247 @end deffn
12249 @geindex command line option; --enable-checking=release
12250 @anchor{internals/index cmdoption--enable-checking}@anchor{186}
12251 @deffn {Option} --enable-checking=release
12253 The compile can perform extensive self-checking as it runs, useful when
12254 debugging, but slowing things down.
12256 For maximum speed, configure with @code{--enable-checking=release} to
12257 disable this self-checking.
12258 @end deffn
12260 @node Running the test suite,Environment variables,Working on the JIT library,Internals
12261 @anchor{internals/index running-the-test-suite}@anchor{187}
12262 @section Running the test suite
12265 @example
12266 [build] $ cd gcc
12267 [gcc] $ make check-jit RUNTESTFLAGS="-v -v -v"
12268 @end example
12270 @noindent
12272 A summary of the tests can then be seen in:
12274 @example
12275 jit/build/gcc/testsuite/jit/jit.sum
12276 @end example
12278 @noindent
12280 and detailed logs in:
12282 @example
12283 jit/build/gcc/testsuite/jit/jit.log
12284 @end example
12286 @noindent
12288 The test executables can be seen as:
12290 @example
12291 jit/build/gcc/testsuite/jit/*.exe
12292 @end example
12294 @noindent
12296 which can be run independently.
12298 You can compile and run individual tests by passing "jit.exp=TESTNAME" to RUNTESTFLAGS e.g.:
12300 @example
12301 [gcc] $ make check-jit RUNTESTFLAGS="-v -v -v jit.exp=test-factorial.c"
12302 @end example
12304 @noindent
12306 and once a test has been compiled, you can debug it directly:
12308 @example
12309 [gcc] $ PATH=.:$PATH \
12310         LD_LIBRARY_PATH=. \
12311         LIBRARY_PATH=. \
12312           gdb --args \
12313             testsuite/jit/test-factorial.c.exe
12314 @end example
12316 @noindent
12318 @menu
12319 * Running under valgrind:: 
12321 @end menu
12323 @node Running under valgrind,,,Running the test suite
12324 @anchor{internals/index running-under-valgrind}@anchor{188}
12325 @subsection Running under valgrind
12328 The jit testsuite detects if RUN_UNDER_VALGRIND is present in the
12329 environment (with any value).  If it is present, it runs the test client
12330 code under valgrind@footnote{http://valgrind.org},
12331 specifcally, the default
12332 memcheck@footnote{http://valgrind.org/docs/manual/mc-manual.html}
12333 tool with
12334 --leak-check=full@footnote{http://valgrind.org/docs/manual/mc-manual.html#opt.leak-check}.
12336 It automatically parses the output from valgrind, injecting XFAIL results if
12337 any issues are found, or PASS results if the output is clean.  The output
12338 is saved to @code{TESTNAME.exe.valgrind.txt}.
12340 For example, the following invocation verbosely runs the testcase
12341 @code{test-sum-of-squares.c} under valgrind, showing an issue:
12343 @example
12344 $ RUN_UNDER_VALGRIND= \
12345     make check-jit \
12346       RUNTESTFLAGS="-v -v -v jit.exp=test-sum-of-squares.c"
12348 (...verbose log contains detailed valgrind errors, if any...)
12350                 === jit Summary ===
12352 # of expected passes            28
12353 # of expected failures          2
12355 $ less testsuite/jit/jit.sum
12356 (...other results...)
12357 XFAIL: jit.dg/test-sum-of-squares.c: test-sum-of-squares.c.exe.valgrind.txt: definitely lost: 8 bytes in 1 blocks
12358 XFAIL: jit.dg/test-sum-of-squares.c: test-sum-of-squares.c.exe.valgrind.txt: unsuppressed errors: 1
12359 (...other results...)
12361 $ less testsuite/jit/test-sum-of-squares.c.exe.valgrind.txt
12362 (...shows full valgrind report for this test case...)
12363 @end example
12365 @noindent
12367 When running under valgrind, it's best to have configured gcc with
12368 @code{--enable-valgrind-annotations}, which automatically suppresses
12369 various known false positives.
12371 @node Environment variables,Overview of code structure,Running the test suite,Internals
12372 @anchor{internals/index environment-variables}@anchor{189}
12373 @section Environment variables
12376 When running client code against a locally-built libgccjit, three
12377 environment variables need to be set up:
12379 @geindex environment variable; LD_LIBRARY_PATH
12380 @anchor{internals/index envvar-LD_LIBRARY_PATH}@anchor{18a}
12381 @deffn {Environment Variable} LD_LIBRARY_PATH
12383 @quotation
12385 @cite{libgccjit.so} is dynamically linked into client code, so if running
12386 against a locally-built library, @code{LD_LIBRARY_PATH} needs to be set
12387 up appropriately.  The library can be found within the "gcc"
12388 subdirectory of the build tree:
12389 @end quotation
12391 @example
12392 $ file libgccjit.so*
12393 libgccjit.so:       symbolic link to `libgccjit.so.0'
12394 libgccjit.so.0:     symbolic link to `libgccjit.so.0.0.1'
12395 libgccjit.so.0.0.1: ELF 64-bit LSB shared object, x86-64, version 1 (GNU/Linux), dynamically linked, not stripped
12396 @end example
12398 @noindent
12399 @end deffn
12401 @geindex environment variable; PATH
12402 @anchor{internals/index envvar-PATH}@anchor{18b}
12403 @deffn {Environment Variable} PATH
12405 The library uses a driver executable for converting from .s assembler
12406 files to .so shared libraries.  Specifically, it looks for a name
12407 expanded from
12408 @code{$@{target_noncanonical@}-gcc-$@{gcc_BASEVER@}$@{exeext@}}
12409 such as @code{x86_64-unknown-linux-gnu-gcc-5.0.0}.
12411 Hence @code{PATH} needs to include a directory where the library can
12412 locate this executable.
12414 The executable is normally installed to the installation bindir
12415 (e.g. /usr/bin), but a copy is also created within the "gcc"
12416 subdirectory of the build tree for running the testsuite, and for ease
12417 of development.
12418 @end deffn
12420 @geindex environment variable; LIBRARY_PATH
12421 @anchor{internals/index envvar-LIBRARY_PATH}@anchor{18c}
12422 @deffn {Environment Variable} LIBRARY_PATH
12424 The driver executable invokes the linker, and the latter needs to locate
12425 support libraries needed by the generated code, or you will see errors
12426 like:
12428 @example
12429 ld: cannot find crtbeginS.o: No such file or directory
12430 ld: cannot find -lgcc
12431 ld: cannot find -lgcc_s
12432 @end example
12434 @noindent
12436 Hence if running directly from a locally-built copy (without installing),
12437 @code{LIBRARY_PATH} needs to contain the "gcc" subdirectory of the build
12438 tree.
12439 @end deffn
12441 For example, to run a binary that uses the library against a non-installed
12442 build of the library in LIBGCCJIT_BUILD_DIR you need an invocation of the
12443 client code like this, to preprend the dir to each of the environment
12444 variables:
12446 @example
12447 $ LD_LIBRARY_PATH=$(LIBGCCJIT_BUILD_DIR):$(LD_LIBRARY_PATH) \
12448   PATH=$(LIBGCCJIT_BUILD_DIR):$(PATH) \
12449   LIBRARY_PATH=$(LIBGCCJIT_BUILD_DIR):$(LIBRARY_PATH) \
12450     ./jit-hello-world
12451 hello world
12452 @end example
12454 @noindent
12456 @node Overview of code structure,Design notes,Environment variables,Internals
12457 @anchor{internals/index overview-of-code-structure}@anchor{18d}
12458 @section Overview of code structure
12462 @itemize *
12464 @item 
12465 @code{libgccjit.c} implements the API entrypoints.  It performs error
12466 checking, then calls into classes of the gcc::jit::recording namespace
12467 within @code{jit-recording.c} and @code{jit-recording.h}.
12469 @item 
12470 The gcc::jit::recording classes (within @code{jit-recording.c} and
12471 @code{jit-recording.h}) record the API calls that are made:
12473 @quotation
12475 @example
12477   /* Indentation indicates inheritance: */
12478   class context;
12479   class memento;
12480     class string;
12481     class location;
12482     class type;
12483       class function_type;
12484       class compound_type;
12485         class struct_;
12486         class union_;
12487     class field;
12488     class fields;
12489     class function;
12490     class block;
12491     class rvalue;
12492       class lvalue;
12493         class local;
12494         class global;
12495         class param;
12496     class statement;
12499 @end example
12501 @noindent
12502 @end quotation
12504 @item 
12505 When the context is compiled, the gcc::jit::playback classes (within
12506 @code{jit-playback.c} and @code{jit-playback.h}) replay the API calls
12507 within langhook:parse_file:
12509 @quotation
12511 @example
12513   /* Indentation indicates inheritance: */
12514   class context;
12515   class wrapper;
12516     class type;
12517       class compound_type;
12518     class field;
12519     class function;
12520     class block;
12521     class rvalue;
12522       class lvalue;
12523         class param;
12524     class source_file;
12525     class source_line;
12526     class location;
12529 @end example
12531 @noindent
12533 @example
12534 Client Code   . Generated .            libgccjit.so
12535               . code      .
12536               .           . JIT API  . JIT "Frontend". (libbackend.a)
12537 ....................................................................................
12538    â”‚          .           .          .               .
12539     â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€>      .               .
12540               .           .    â”‚     .               .
12541               .           .    V     .               .
12542               .           .    â”€â”€> libgccjit.c       .
12543               .           .        â”‚ (error-checking).
12544               .           .        â”‚                 .
12545               .           .        â”€â”€> jit-recording.c
12546               .           .              (record API calls)
12547               .           .    <───────              .
12548               .           .    â”‚     .               .
12549    <───────────────────────────      .               .
12550    â”‚          .           .          .               .
12551    â”‚          .           .          .               .
12552    V          .           .  gcc_jit_context_compile .
12553     â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€>      .               .
12554               .           .    â”‚ start of recording::context::compile ()
12555               .           .    â”‚     .               .
12556               .           .    â”‚ start of playback::context::compile ()
12557               .           .    â”‚   (create tempdir)  .
12558               .           .    â”‚     .               .
12559               .           .    â”‚ ACQUIRE MUTEX       .
12560               .           .    â”‚     .               .
12561               .           .    V───────────────────────> toplev::main (for now)
12562               .           .          .               .       â”‚
12563               .           .          .               .   (various code)
12564               .           .          .               .       â”‚
12565               .           .          .               .       V
12566               .           .          .    <───────────────── langhook:parse_file
12567               .           .          .    â”‚          .
12568               .           .          .    â”‚ (jit_langhook_parse_file)
12569               .           .          .    â”‚          .
12570 ..........................................│..................VVVVVVVVVVVVV...
12571               .           .          .    â”‚          .       No GC in here
12572               .           .          .    â”‚ jit-playback.c
12573               .           .          .    â”‚   (playback of API calls)
12574               .           .          .    â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€> creation of functions,
12575               .           .          .               .     types, expression trees
12576               .           .          .    <──────────────── etc
12577               .           .          .    â”‚(handle_locations: add locations to
12578               .           .          .    â”‚ linemap and associate them with trees)
12579               .           .          .    â”‚          .
12580               .           .          .    â”‚          .       No GC in here
12581 ..........................................│..................AAAAAAAAAAAAA...
12582               .           .          .    â”‚ for each function
12583               .           .          .    â”€â”€> postprocess
12584               .           .          .        â”‚      .
12585               .           .          .        â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€> cgraph_finalize_function
12586               .           .          .        <────────────
12587               .           .          .     <──       .
12588               .           .          .    â”‚          .
12589               .           .          .    â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€> (end of
12590               .           .          .               .       â”‚ langhook_parse_file)
12591               .           .          .               .       â”‚
12592               .           .          .               .   (various code)
12593               .           .          .               .       â”‚
12594               .           .          .               .       â†“
12595               .           .          .    <───────────────── langhook:write_globals
12596               .           .          .    â”‚          .
12597               .           .          .    â”‚ (jit_langhook_write_globals)
12598               .           .          .    â”‚          .
12599               .           .          .    â”‚          .
12600               .           .          .    â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€> finalize_compilation_unit
12601               .           .          .               .       â”‚
12602               .           .          .               .   (the middle─end and backend)
12603               .           .          .               .       â†“
12604               .           .    <───────────────────────────── end of toplev::main
12605               .           .    â”‚     .               .
12606               .           .    V───────────────────────> toplev::finalize
12607               .           .          .               . â”‚   (purge internal state)
12608               .           .    <──────────────────────── end of toplev::finalize
12609               .           .    â”‚     .               .
12610               .           .    â”‚ Convert assembler to DSO ("fake.so")
12611               .           .    â”‚     .               .
12612               .           .    â”‚ Load DSO (dlopen "fake.so")
12613               .           .    â”‚     .               .
12614               .           .    â”‚ RELEASE MUTEX       .
12615               .           .    â”‚     .               .
12616               .           .    â”‚ end of playback::context::compile ()
12617               .           .    â”‚     .               .
12618               .           .    â”‚ playback::context dtor
12619               .           .     â”€â”€>  .               .
12620               .           .       â”‚ Normally we cleanup the tempdir here:
12621               .           .       â”‚   ("fake.so" is unlinked from the
12622               .           .       â”‚    filesystem at this point)
12623               .           .       â”‚ If the client code requested debuginfo, the
12624               .           .       â”‚ cleanup happens later (in gcc_jit_result_release)
12625               .           .       â”‚ to make it easier on the debugger (see PR jit/64206)
12626               .           .    <──   .               .
12627               .           .    â”‚     .               .
12628               .           .    â”‚ end of recording::context::compile ()
12629    <───────────────────────────      .               .
12630    â”‚          .           .          .               .
12631    V          .           .  gcc_jit_result_get_code .
12632     â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€>      .               .
12633               .           .    â”‚ dlsym () within loaded DSO
12634    <───────────────────────────      .               .
12635    Get (void*).           .          .               .
12636    â”‚          .           .          .               .
12637    â”‚ Call it  .           .          .               .
12638    â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€>       .          .               .
12639               .    â”‚      .          .               .
12640               .    â”‚      .          .               .
12641    <───────────────       .          .               .
12642    â”‚          .           .          .               .
12643 etc│          .           .          .               .
12644    â”‚          .           .          .               .
12645    V          .           .  gcc_jit_result_release  .
12646     â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€>      .               .
12647               .           .    â”‚ dlclose () the loaded DSO
12648               .           .    â”‚    (code becomes uncallable)
12649               .           .    â”‚     .               .
12650               .           .    â”‚ If the client code requested debuginfo, then
12651               .           .    â”‚ cleanup of the tempdir was delayed.
12652               .           .    â”‚ If that was the case, clean it up now.
12653    <───────────────────────────      .               .
12654    â”‚          .           .          .               .
12656 @end example
12658 @noindent
12659 @end quotation
12660 @end itemize
12662 Here is a high-level summary from @code{jit-common.h}:
12664 @quotation
12666 In order to allow jit objects to be usable outside of a compile
12667 whilst working with the existing structure of GCC's code the
12668 C API is implemented in terms of a gcc::jit::recording::context,
12669 which records the calls made to it.
12671 When a gcc_jit_context is compiled, the recording context creates a
12672 playback context.  The playback context invokes the bulk of the GCC
12673 code, and within the "frontend" parsing hook, plays back the recorded
12674 API calls, creating GCC tree objects.
12676 So there are two parallel families of classes: those relating to
12677 recording, and those relating to playback:
12680 @itemize *
12682 @item 
12683 Visibility: recording objects are exposed back to client code,
12684 whereas playback objects are internal to the library.
12686 @item 
12687 Lifetime: recording objects have a lifetime equal to that of the
12688 recording context that created them, whereas playback objects only
12689 exist within the frontend hook.
12691 @item 
12692 Memory allocation: recording objects are allocated by the recording
12693 context, and automatically freed by it when the context is released,
12694 whereas playback objects are allocated within the GC heap, and
12695 garbage-collected; they can own GC-references.
12697 @item 
12698 Integration with rest of GCC: recording objects are unrelated to the
12699 rest of GCC, whereas playback objects are wrappers around "tree"
12700 instances.  Hence you can't ask a recording rvalue or lvalue what its
12701 type is, whereas you can for a playback rvalue of lvalue (since it
12702 can work with the underlying GCC tree nodes).
12704 @item 
12705 Instancing: There can be multiple recording contexts "alive" at once
12706 (albeit it only one compiling at once), whereas there can only be one
12707 playback context alive at one time (since it interacts with the GC).
12708 @end itemize
12710 Ultimately if GCC could support multiple GC heaps and contexts, and
12711 finer-grained initialization, then this recording vs playback
12712 distinction could be eliminated.
12714 During a playback, we associate objects from the recording with
12715 their counterparts during this playback.  For simplicity, we store this
12716 within the recording objects, as @code{void *m_playback_obj}, casting it to
12717 the appropriate playback object subclass.  For these casts to make
12718 sense, the two class hierarchies need to have the same structure.
12720 Note that the playback objects that @code{m_playback_obj} points to are
12721 GC-allocated, but the recording objects don't own references:
12722 these associations only exist within a part of the code where
12723 the GC doesn't collect, and are set back to NULL before the GC can
12724 run.
12725 @end quotation
12726 @anchor{internals/index example-of-log-file}@anchor{55}
12727 Another way to understand the structure of the code is to enable logging,
12728 via @pxref{54,,gcc_jit_context_set_logfile()}.  Here is an example of a log
12729 generated via this call:
12731 @example
12732 JIT: entering: gcc_jit_context_set_str_option
12733 JIT: exiting: gcc_jit_context_set_str_option
12734 JIT: entering: gcc_jit_context_set_int_option
12735 JIT: exiting: gcc_jit_context_set_int_option
12736 JIT: entering: gcc_jit_context_set_bool_option
12737 JIT: exiting: gcc_jit_context_set_bool_option
12738 JIT: entering: gcc_jit_context_set_bool_option
12739 JIT: exiting: gcc_jit_context_set_bool_option
12740 JIT: entering: gcc_jit_context_set_bool_option
12741 JIT: exiting: gcc_jit_context_set_bool_option
12742 JIT: entering: gcc_jit_context_set_bool_option
12743 JIT: exiting: gcc_jit_context_set_bool_option
12744 JIT: entering: gcc_jit_context_set_bool_option
12745 JIT: exiting: gcc_jit_context_set_bool_option
12746 JIT: entering: gcc_jit_context_get_type
12747 JIT: exiting: gcc_jit_context_get_type
12748 JIT: entering: gcc_jit_context_get_type
12749 JIT: exiting: gcc_jit_context_get_type
12750 JIT: entering: gcc_jit_context_new_param
12751 JIT: exiting: gcc_jit_context_new_param
12752 JIT: entering: gcc_jit_context_new_function
12753 JIT: exiting: gcc_jit_context_new_function
12754 JIT: entering: gcc_jit_context_new_param
12755 JIT: exiting: gcc_jit_context_new_param
12756 JIT: entering: gcc_jit_context_get_type
12757 JIT: exiting: gcc_jit_context_get_type
12758 JIT: entering: gcc_jit_context_new_function
12759 JIT: exiting: gcc_jit_context_new_function
12760 JIT: entering: gcc_jit_context_new_string_literal
12761 JIT: exiting: gcc_jit_context_new_string_literal
12762 JIT: entering: gcc_jit_function_new_block
12763 JIT: exiting: gcc_jit_function_new_block
12764 JIT: entering: gcc_jit_block_add_comment
12765 JIT: exiting: gcc_jit_block_add_comment
12766 JIT: entering: gcc_jit_context_new_call
12767 JIT: exiting: gcc_jit_context_new_call
12768 JIT: entering: gcc_jit_block_add_eval
12769 JIT: exiting: gcc_jit_block_add_eval
12770 JIT: entering: gcc_jit_block_end_with_void_return
12771 JIT: exiting: gcc_jit_block_end_with_void_return
12772 JIT: entering: gcc_jit_context_compile
12773 JIT:  compiling ctxt: 0x1283e20
12774 JIT:  entering: gcc::jit::result* gcc::jit::recording::context::compile()
12775 JIT:   entering: void gcc::jit::recording::context::validate()
12776 JIT:   exiting: void gcc::jit::recording::context::validate()
12777 JIT:   entering: gcc::jit::playback::context::context(gcc::jit::recording::context*)
12778 JIT:   exiting: gcc::jit::playback::context::context(gcc::jit::recording::context*)
12779 JIT:   entering: gcc::jit::result* gcc::jit::playback::context::compile()
12780 JIT:    entering: gcc::jit::tempdir::tempdir(gcc::jit::logger*, int)
12781 JIT:    exiting: gcc::jit::tempdir::tempdir(gcc::jit::logger*, int)
12782 JIT:    entering: bool gcc::jit::tempdir::create()
12783 JIT:     m_path_template: /tmp/libgccjit-XXXXXX
12784 JIT:     m_path_tempdir: /tmp/libgccjit-CKq1M9
12785 JIT:    exiting: bool gcc::jit::tempdir::create()
12786 JIT:    entering: void gcc::jit::playback::context::make_fake_args(vec<char*>*, const char*, vec<gcc::jit::recording::requested_dump>*)
12787 JIT:    exiting: void gcc::jit::playback::context::make_fake_args(vec<char*>*, const char*, vec<gcc::jit::recording::requested_dump>*)
12788 JIT:    entering: void gcc::jit::playback::context::acquire_mutex()
12789 JIT:    exiting: void gcc::jit::playback::context::acquire_mutex()
12790 JIT:    entering: toplev::main
12791 JIT:     argv[0]: ./test-hello-world.c.exe
12792 JIT:     argv[1]: /tmp/libgccjit-CKq1M9/fake.c
12793 JIT:     argv[2]: -fPIC
12794 JIT:     argv[3]: -O3
12795 JIT:     argv[4]: -g
12796 JIT:     argv[5]: -quiet
12797 JIT:     argv[6]: --param
12798 JIT:     argv[7]: ggc-min-expand=0
12799 JIT:     argv[8]: --param
12800 JIT:     argv[9]: ggc-min-heapsize=0
12801 JIT:     entering: bool jit_langhook_init()
12802 JIT:     exiting: bool jit_langhook_init()
12803 JIT:     entering: void gcc::jit::playback::context::replay()
12804 JIT:      entering: void gcc::jit::recording::context::replay_into(gcc::jit::replayer*)
12805 JIT:      exiting: void gcc::jit::recording::context::replay_into(gcc::jit::replayer*)
12806 JIT:      entering: void gcc::jit::recording::context::disassociate_from_playback()
12807 JIT:      exiting: void gcc::jit::recording::context::disassociate_from_playback()
12808 JIT:      entering: void gcc::jit::playback::context::handle_locations()
12809 JIT:      exiting: void gcc::jit::playback::context::handle_locations()
12810 JIT:      entering: void gcc::jit::playback::function::build_stmt_list()
12811 JIT:      exiting: void gcc::jit::playback::function::build_stmt_list()
12812 JIT:      entering: void gcc::jit::playback::function::build_stmt_list()
12813 JIT:      exiting: void gcc::jit::playback::function::build_stmt_list()
12814 JIT:      entering: void gcc::jit::playback::function::postprocess()
12815 JIT:      exiting: void gcc::jit::playback::function::postprocess()
12816 JIT:      entering: void gcc::jit::playback::function::postprocess()
12817 JIT:      exiting: void gcc::jit::playback::function::postprocess()
12818 JIT:     exiting: void gcc::jit::playback::context::replay()
12819 JIT:     entering: void jit_langhook_write_globals()
12820 JIT:     exiting: void jit_langhook_write_globals()
12821 JIT:    exiting: toplev::main
12822 JIT:    entering: void gcc::jit::playback::context::extract_any_requested_dumps(vec<gcc::jit::recording::requested_dump>*)
12823 JIT:    exiting: void gcc::jit::playback::context::extract_any_requested_dumps(vec<gcc::jit::recording::requested_dump>*)
12824 JIT:    entering: toplev::finalize
12825 JIT:    exiting: toplev::finalize
12826 JIT:    entering: void gcc::jit::playback::context::convert_to_dso(const char*)
12827 JIT:     argv[0]: x86_64-unknown-linux-gnu-gcc-5.0.0
12828 JIT:     argv[1]: -shared
12829 JIT:     argv[2]: /tmp/libgccjit-CKq1M9/fake.s
12830 JIT:     argv[3]: -o
12831 JIT:     argv[4]: /tmp/libgccjit-CKq1M9/fake.so
12832 JIT:     argv[5]: -fno-use-linker-plugin
12833 JIT:     argv[6]: (null)
12834 JIT:    exiting: void gcc::jit::playback::context::convert_to_dso(const char*)
12835 JIT:    entering: gcc::jit::result* gcc::jit::playback::context::dlopen_built_dso()
12836 JIT:     GCC_JIT_BOOL_OPTION_DEBUGINFO was set: handing over tempdir to jit::result
12837 JIT:     entering: gcc::jit::result::result(gcc::jit::logger*, void*, gcc::jit::tempdir*)
12838 JIT:     exiting: gcc::jit::result::result(gcc::jit::logger*, void*, gcc::jit::tempdir*)
12839 JIT:    exiting: gcc::jit::result* gcc::jit::playback::context::dlopen_built_dso()
12840 JIT:    entering: void gcc::jit::playback::context::release_mutex()
12841 JIT:    exiting: void gcc::jit::playback::context::release_mutex()
12842 JIT:   exiting: gcc::jit::result* gcc::jit::playback::context::compile()
12843 JIT:   entering: gcc::jit::playback::context::~context()
12844 JIT:   exiting: gcc::jit::playback::context::~context()
12845 JIT:  exiting: gcc::jit::result* gcc::jit::recording::context::compile()
12846 JIT:  gcc_jit_context_compile: returning (gcc_jit_result *)0x12f75d0
12847 JIT: exiting: gcc_jit_context_compile
12848 JIT: entering: gcc_jit_result_get_code
12849 JIT:  locating fnname: hello_world
12850 JIT:  entering: void* gcc::jit::result::get_code(const char*)
12851 JIT:  exiting: void* gcc::jit::result::get_code(const char*)
12852 JIT:  gcc_jit_result_get_code: returning (void *)0x7ff6b8cd87f0
12853 JIT: exiting: gcc_jit_result_get_code
12854 JIT: entering: gcc_jit_context_release
12855 JIT:  deleting ctxt: 0x1283e20
12856 JIT:  entering: gcc::jit::recording::context::~context()
12857 JIT:  exiting: gcc::jit::recording::context::~context()
12858 JIT: exiting: gcc_jit_context_release
12859 JIT: entering: gcc_jit_result_release
12860 JIT:  deleting result: 0x12f75d0
12861 JIT:  entering: virtual gcc::jit::result::~result()
12862 JIT:   entering: gcc::jit::tempdir::~tempdir()
12863 JIT:    unlinking .s file: /tmp/libgccjit-CKq1M9/fake.s
12864 JIT:    unlinking .so file: /tmp/libgccjit-CKq1M9/fake.so
12865 JIT:    removing tempdir: /tmp/libgccjit-CKq1M9
12866 JIT:   exiting: gcc::jit::tempdir::~tempdir()
12867 JIT:  exiting: virtual gcc::jit::result::~result()
12868 JIT: exiting: gcc_jit_result_release
12869 JIT: gcc::jit::logger::~logger()
12871 @end example
12873 @noindent
12875 @node Design notes,,Overview of code structure,Internals
12876 @anchor{internals/index design-notes}@anchor{18e}
12877 @section Design notes
12880 It should not be possible for client code to cause an internal compiler
12881 error.  If this @emph{does} happen, the root cause should be isolated (perhaps
12882 using @pxref{56,,gcc_jit_context_dump_reproducer_to_file()}) and the cause
12883 should be rejected via additional checking.  The checking ideally should
12884 be within the libgccjit API entrypoints in libgccjit.c, since this is as
12885 close as possible to the error; failing that, a good place is within
12886 @code{recording::context::validate ()} in jit-recording.c.
12888 @node Indices and tables,Index,Internals,Top
12889 @anchor{index indices-and-tables}@anchor{18f}
12890 @unnumbered Indices and tables
12894 @itemize *
12896 @item 
12897 @emph{genindex}
12899 @item 
12900 @emph{modindex}
12902 @item 
12903 @emph{search}
12904 @end itemize
12906 @c Some notes:
12907 @c 
12908 @c The Sphinx C domain appears to lack explicit support for enum values,
12909 @c so I've been using :c:macro: for them.
12910 @c 
12911 @c See http://sphinx-doc.org/domains.html#the-c-domain
12913 @node Index,,Indices and tables,Top
12914 @unnumbered Index
12917 @printindex ge
12919 @c %**end of body
12920 @bye