jit: New API entrypoint: gcc_jit_context_get_last_error
[official-gcc.git] / gcc / jit / docs / _build / texinfo / libgccjit.texi
blobd489d46527a3ef728e44fa11a7718552b78a8202
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 20150108), January 08, 2015
24 David Malcolm
26 Copyright @copyright{} 2014, Free Software Foundation
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 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 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:: 
323 Running the test suite
325 * Running under valgrind:: 
327 @end detailmenu
328 @end menu
331 @node Tutorial,Topic Reference,Top,Top
332 @anchor{intro/index libgccjit}@anchor{1}@anchor{intro/index doc}@anchor{2}@anchor{intro/index tutorial}@anchor{3}
333 @chapter Tutorial
336 @c Copyright (C) 2014 Free Software Foundation, Inc.
337 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
338 @c 
339 @c This is free software: you can redistribute it and/or modify it
340 @c under the terms of the GNU General Public License as published by
341 @c the Free Software Foundation, either version 3 of the License, or
342 @c (at your option) any later version.
343 @c 
344 @c This program is distributed in the hope that it will be useful, but
345 @c WITHOUT ANY WARRANTY; without even the implied warranty of
346 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
347 @c General Public License for more details.
348 @c 
349 @c You should have received a copy of the GNU General Public License
350 @c along with this program.  If not, see
351 @c <http://www.gnu.org/licenses/>.
353 @menu
354 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world". 
355 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function. 
356 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables. 
357 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter. 
359 @end menu
361 @node Tutorial part 1 "Hello world",Tutorial part 2 Creating a trivial machine code function,,Tutorial
362 @anchor{intro/tutorial01 doc}@anchor{4}@anchor{intro/tutorial01 tutorial-part-1-hello-world}@anchor{5}
363 @section Tutorial part 1: "Hello world"
366 Before we look at the details of the API, let's look at building and
367 running programs that use the library.
369 Here's a toy "hello world" program that uses the library to synthesize
370 a call to @cite{printf} and uses it to write a message to stdout.
372 Don't worry about the content of the program for now; we'll cover
373 the details in later parts of this tutorial.
375 @quotation
377 @example
378 /* Smoketest example for libgccjit.so
379    Copyright (C) 2014 Free Software Foundation, Inc.
381 This file is part of GCC.
383 GCC is free software; you can redistribute it and/or modify it
384 under the terms of the GNU General Public License as published by
385 the Free Software Foundation; either version 3, or (at your option)
386 any later version.
388 GCC is distributed in the hope that it will be useful, but
389 WITHOUT ANY WARRANTY; without even the implied warranty of
390 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
391 General Public License for more details.
393 You should have received a copy of the GNU General Public License
394 along with GCC; see the file COPYING3.  If not see
395 <http://www.gnu.org/licenses/>.  */
397 #include <libgccjit.h>
399 #include <stdlib.h>
400 #include <stdio.h>
402 static void
403 create_code (gcc_jit_context *ctxt)
405   /* Let's try to inject the equivalent of:
406      void
407      greet (const char *name)
408      @{
409         printf ("hello %s\n", name);
410      @}
411   */
412   gcc_jit_type *void_type =
413     gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_VOID);
414   gcc_jit_type *const_char_ptr_type =
415     gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_CONST_CHAR_PTR);
416   gcc_jit_param *param_name =
417     gcc_jit_context_new_param (ctxt, NULL, const_char_ptr_type, "name");
418   gcc_jit_function *func =
419     gcc_jit_context_new_function (ctxt, NULL,
420                                   GCC_JIT_FUNCTION_EXPORTED,
421                                   void_type,
422                                   "greet",
423                                   1, &param_name,
424                                   0);
426   gcc_jit_param *param_format =
427     gcc_jit_context_new_param (ctxt, NULL, const_char_ptr_type, "format");
428   gcc_jit_function *printf_func =
429     gcc_jit_context_new_function (ctxt, NULL,
430                                   GCC_JIT_FUNCTION_IMPORTED,
431                                   gcc_jit_context_get_type (
432                                      ctxt, GCC_JIT_TYPE_INT),
433                                   "printf",
434                                   1, &param_format,
435                                   1);
436   gcc_jit_rvalue *args[2];
437   args[0] = gcc_jit_context_new_string_literal (ctxt, "hello %s\n");
438   args[1] = gcc_jit_param_as_rvalue (param_name);
440   gcc_jit_block *block = gcc_jit_function_new_block (func, NULL);
442   gcc_jit_block_add_eval (
443     block, NULL,
444     gcc_jit_context_new_call (ctxt,
445                               NULL,
446                               printf_func,
447                               2, args));
448   gcc_jit_block_end_with_void_return (block, NULL);
452 main (int argc, char **argv)
454   gcc_jit_context *ctxt;
455   gcc_jit_result *result;
457   /* Get a "context" object for working with the library.  */
458   ctxt = gcc_jit_context_acquire ();
459   if (!ctxt)
460     @{
461       fprintf (stderr, "NULL ctxt");
462       exit (1);
463     @}
465   /* Set some options on the context.
466      Let's see the code being generated, in assembler form.  */
467   gcc_jit_context_set_bool_option (
468     ctxt,
469     GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
470     0);
472   /* Populate the context.  */
473   create_code (ctxt);
475   /* Compile the code.  */
476   result = gcc_jit_context_compile (ctxt);
477   if (!result)
478     @{
479       fprintf (stderr, "NULL result");
480       exit (1);
481     @}
483   /* Extract the generated code from "result".  */
484   typedef void (*fn_type) (const char *);
485   fn_type greet =
486     (fn_type)gcc_jit_result_get_code (result, "greet");
487   if (!greet)
488     @{
489       fprintf (stderr, "NULL greet");
490       exit (1);
491     @}
493   /* Now call the generated function: */
494   greet ("world");
495   fflush (stdout);
497   gcc_jit_context_release (ctxt);
498   gcc_jit_result_release (result);
499   return 0;
502 @end example
504 @noindent
505 @end quotation
507 Copy the above to @cite{tut01-hello-world.c}.
509 Assuming you have the jit library installed, build the test program
510 using:
512 @example
513 $ gcc \
514     tut01-hello-world.c \
515     -o tut01-hello-world \
516     -lgccjit
517 @end example
519 @noindent
521 You should then be able to run the built program:
523 @example
524 $ ./tut01-hello-world
525 hello world
526 @end example
528 @noindent
530 @c Copyright (C) 2014 Free Software Foundation, Inc.
531 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
532 @c 
533 @c This is free software: you can redistribute it and/or modify it
534 @c under the terms of the GNU General Public License as published by
535 @c the Free Software Foundation, either version 3 of the License, or
536 @c (at your option) any later version.
537 @c 
538 @c This program is distributed in the hope that it will be useful, but
539 @c WITHOUT ANY WARRANTY; without even the implied warranty of
540 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
541 @c General Public License for more details.
542 @c 
543 @c You should have received a copy of the GNU General Public License
544 @c along with this program.  If not, see
545 @c <http://www.gnu.org/licenses/>.
547 @node Tutorial part 2 Creating a trivial machine code function,Tutorial part 3 Loops and variables,Tutorial part 1 "Hello world",Tutorial
548 @anchor{intro/tutorial02 doc}@anchor{6}@anchor{intro/tutorial02 tutorial-part-2-creating-a-trivial-machine-code-function}@anchor{7}
549 @section Tutorial part 2: Creating a trivial machine code function
552 Consider this C function:
554 @example
555 int square (int i)
557   return i * i;
559 @end example
561 @noindent
563 How can we construct this at run-time using libgccjit?
565 First we need to include the relevant header:
567 @example
568 #include <libgccjit.h>
569 @end example
571 @noindent
573 All state associated with compilation is associated with a
574 @pxref{8,,gcc_jit_context *}.
576 Create one using @pxref{9,,gcc_jit_context_acquire()}:
578 @example
579 gcc_jit_context *ctxt;
580 ctxt = gcc_jit_context_acquire ();
581 @end example
583 @noindent
585 The JIT library has a system of types.  It is statically-typed: every
586 expression is of a specific type, fixed at compile-time.  In our example,
587 all of the expressions are of the C @cite{int} type, so let's obtain this from
588 the context, as a @pxref{a,,gcc_jit_type *}, using
589 @pxref{b,,gcc_jit_context_get_type()}:
591 @example
592 gcc_jit_type *int_type =
593   gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
594 @end example
596 @noindent
598 @pxref{a,,gcc_jit_type *} is an example of a "contextual" object: every
599 entity in the API is associated with a @pxref{8,,gcc_jit_context *}.
601 Memory management is easy: all such "contextual" objects are automatically
602 cleaned up for you when the context is released, using
603 @pxref{c,,gcc_jit_context_release()}:
605 @example
606 gcc_jit_context_release (ctxt);
607 @end example
609 @noindent
611 so you don't need to manually track and cleanup all objects, just the
612 contexts.
614 Although the API is C-based, there is a form of class hierarchy, which
615 looks like this:
617 @example
618 +- gcc_jit_object
619     +- gcc_jit_location
620     +- gcc_jit_type
621        +- gcc_jit_struct
622     +- gcc_jit_field
623     +- gcc_jit_function
624     +- gcc_jit_block
625     +- gcc_jit_rvalue
626         +- gcc_jit_lvalue
627            +- gcc_jit_param
628 @end example
630 @noindent
632 There are casting methods for upcasting from subclasses to parent classes.
633 For example, @pxref{d,,gcc_jit_type_as_object()}:
635 @example
636 gcc_jit_object *obj = gcc_jit_type_as_object (int_type);
637 @end example
639 @noindent
641 One thing you can do with a @pxref{e,,gcc_jit_object *} is
642 to ask it for a human-readable description, using
643 @pxref{f,,gcc_jit_object_get_debug_string()}:
645 @example
646 printf ("obj: %s\n", gcc_jit_object_get_debug_string (obj));
647 @end example
649 @noindent
651 giving this text on stdout:
653 @example
654 obj: int
655 @end example
657 @noindent
659 This is invaluable when debugging.
661 Let's create the function.  To do so, we first need to construct
662 its single parameter, specifying its type and giving it a name,
663 using @pxref{10,,gcc_jit_context_new_param()}:
665 @example
666 gcc_jit_param *param_i =
667   gcc_jit_context_new_param (ctxt, NULL, int_type, "i");
668 @end example
670 @noindent
672 Now we can create the function, using
673 @pxref{11,,gcc_jit_context_new_function()}:
675 @example
676 gcc_jit_function *func =
677   gcc_jit_context_new_function (ctxt, NULL,
678                                 GCC_JIT_FUNCTION_EXPORTED,
679                                 int_type,
680                                 "square",
681                                 1, &param_i,
682                                 0);
683 @end example
685 @noindent
687 To define the code within the function, we must create basic blocks
688 containing statements.
690 Every basic block contains a list of statements, eventually terminated
691 by a statement that either returns, or jumps to another basic block.
693 Our function has no control-flow, so we just need one basic block:
695 @example
696 gcc_jit_block *block = gcc_jit_function_new_block (func, NULL);
697 @end example
699 @noindent
701 Our basic block is relatively simple: it immediately terminates by
702 returning the value of an expression.
704 We can build the expression using @pxref{12,,gcc_jit_context_new_binary_op()}:
706 @example
707 gcc_jit_rvalue *expr =
708   gcc_jit_context_new_binary_op (
709     ctxt, NULL,
710     GCC_JIT_BINARY_OP_MULT, int_type,
711     gcc_jit_param_as_rvalue (param_i),
712     gcc_jit_param_as_rvalue (param_i));
713 @end example
715 @noindent
717 A @pxref{13,,gcc_jit_rvalue *} is another example of a
718 @pxref{e,,gcc_jit_object *} subclass.  We can upcast it using
719 @pxref{14,,gcc_jit_rvalue_as_object()} and as before print it with
720 @pxref{f,,gcc_jit_object_get_debug_string()}.
722 @example
723 printf ("expr: %s\n",
724         gcc_jit_object_get_debug_string (
725           gcc_jit_rvalue_as_object (expr)));
726 @end example
728 @noindent
730 giving this output:
732 @example
733 expr: i * i
734 @end example
736 @noindent
738 Creating the expression in itself doesn't do anything; we have to add
739 this expression to a statement within the block.  In this case, we use it
740 to build a return statement, which terminates the basic block:
742 @example
743 gcc_jit_block_end_with_return (block, NULL, expr);
744 @end example
746 @noindent
748 OK, we've populated the context.  We can now compile it using
749 @pxref{15,,gcc_jit_context_compile()}:
751 @example
752 gcc_jit_result *result;
753 result = gcc_jit_context_compile (ctxt);
754 @end example
756 @noindent
758 and get a @pxref{16,,gcc_jit_result *}.
760 At this point we're done with the context; we can release it:
762 @example
763 gcc_jit_context_release (ctxt);
764 @end example
766 @noindent
768 We can now use @pxref{17,,gcc_jit_result_get_code()} to look up a specific
769 machine code routine within the result, in this case, the function we
770 created above.
772 @example
773 void *fn_ptr = gcc_jit_result_get_code (result, "square");
774 if (!fn_ptr)
775   @{
776     fprintf (stderr, "NULL fn_ptr");
777     goto error;
778   @}
779 @end example
781 @noindent
783 We can now cast the pointer to an appropriate function pointer type, and
784 then call it:
786 @example
787 typedef int (*fn_type) (int);
788 fn_type square = (fn_type)fn_ptr;
789 printf ("result: %d", square (5));
790 @end example
792 @noindent
794 @example
795 result: 25
796 @end example
798 @noindent
800 Once we're done with the code, we can release the result:
802 @example
803 gcc_jit_result_release (result);
804 @end example
806 @noindent
808 We can't call @code{square} anymore once we've released @code{result}.
810 @menu
811 * Error-handling:: 
812 * Options:: 
813 * Full example:: 
815 @end menu
817 @node Error-handling,Options,,Tutorial part 2 Creating a trivial machine code function
818 @anchor{intro/tutorial02 error-handling}@anchor{18}
819 @subsection Error-handling
822 Various kinds of errors are possible when using the API, such as
823 mismatched types in an assignment.  You can only compile and get code
824 from a context if no errors occur.
826 Errors are printed on stderr; they typically contain the name of the API
827 entrypoint where the error occurred, and pertinent information on the
828 problem:
830 @example
831 ./buggy-program: error: gcc_jit_block_add_assignment: mismatching types: assignment to i (type: int) from "hello world" (type: const char *)
832 @end example
834 @noindent
836 The API is designed to cope with errors without crashing, so you can get
837 away with having a single error-handling check in your code:
839 @example
840 void *fn_ptr = gcc_jit_result_get_code (result, "square");
841 if (!fn_ptr)
842   @{
843     fprintf (stderr, "NULL fn_ptr");
844     goto error;
845   @}
846 @end example
848 @noindent
850 For more information, see the @pxref{19,,error-handling guide}
851 within the Topic eference.
853 @node Options,Full example,Error-handling,Tutorial part 2 Creating a trivial machine code function
854 @anchor{intro/tutorial02 options}@anchor{1a}
855 @subsection Options
858 To get more information on what's going on, you can set debugging flags
859 on the context using @pxref{1b,,gcc_jit_context_set_bool_option()}.
861 @c (I'm deliberately not mentioning
862 @c :c:macro:`GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE` here since I think
863 @c it's probably more of use to implementors than to users)
865 Setting @pxref{1c,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE} will dump a
866 C-like representation to stderr when you compile (GCC's "GIMPLE"
867 representation):
869 @example
870 gcc_jit_context_set_bool_option (
871   ctxt,
872   GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE,
873   1);
874 result = gcc_jit_context_compile (ctxt);
875 @end example
877 @noindent
879 @example
880 square (signed int i)
882   signed int D.260;
884   entry:
885   D.260 = i * i;
886   return D.260;
888 @end example
890 @noindent
892 We can see the generated machine code in assembler form (on stderr) by
893 setting @pxref{1d,,GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE} on the context
894 before compiling:
896 @example
897 gcc_jit_context_set_bool_option (
898   ctxt,
899   GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
900   1);
901 result = gcc_jit_context_compile (ctxt);
902 @end example
904 @noindent
906 @example
907       .file   "fake.c"
908       .text
909       .globl  square
910       .type   square, @@function
911 square:
912 .LFB6:
913       .cfi_startproc
914       pushq   %rbp
915       .cfi_def_cfa_offset 16
916       .cfi_offset 6, -16
917       movq    %rsp, %rbp
918       .cfi_def_cfa_register 6
919       movl    %edi, -4(%rbp)
920 .L14:
921       movl    -4(%rbp), %eax
922       imull   -4(%rbp), %eax
923       popq    %rbp
924       .cfi_def_cfa 7, 8
925       ret
926       .cfi_endproc
927 .LFE6:
928       .size   square, .-square
929       .ident  "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)"
930       .section       .note.GNU-stack,"",@@progbits
931 @end example
933 @noindent
935 By default, no optimizations are performed, the equivalent of GCC's
936 @cite{-O0} option.  We can turn things up to e.g. @cite{-O3} by calling
937 @pxref{1e,,gcc_jit_context_set_int_option()} with
938 @pxref{1f,,GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}:
940 @example
941 gcc_jit_context_set_int_option (
942   ctxt,
943   GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL,
944   3);
945 @end example
947 @noindent
949 @example
950       .file   "fake.c"
951       .text
952       .p2align 4,,15
953       .globl  square
954       .type   square, @@function
955 square:
956 .LFB7:
957       .cfi_startproc
958 .L16:
959       movl    %edi, %eax
960       imull   %edi, %eax
961       ret
962       .cfi_endproc
963 .LFE7:
964       .size   square, .-square
965       .ident  "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)"
966       .section        .note.GNU-stack,"",@@progbits
967 @end example
969 @noindent
971 Naturally this has only a small effect on such a trivial function.
973 @node Full example,,Options,Tutorial part 2 Creating a trivial machine code function
974 @anchor{intro/tutorial02 full-example}@anchor{20}
975 @subsection Full example
978 Here's what the above looks like as a complete program:
980 @quotation
982 @example
983 /* Usage example for libgccjit.so
984    Copyright (C) 2014 Free Software Foundation, Inc.
986 This file is part of GCC.
988 GCC is free software; you can redistribute it and/or modify it
989 under the terms of the GNU General Public License as published by
990 the Free Software Foundation; either version 3, or (at your option)
991 any later version.
993 GCC is distributed in the hope that it will be useful, but
994 WITHOUT ANY WARRANTY; without even the implied warranty of
995 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
996 General Public License for more details.
998 You should have received a copy of the GNU General Public License
999 along with GCC; see the file COPYING3.  If not see
1000 <http://www.gnu.org/licenses/>.  */
1002 #include <libgccjit.h>
1004 #include <stdlib.h>
1005 #include <stdio.h>
1007 void
1008 create_code (gcc_jit_context *ctxt)
1010   /* Let's try to inject the equivalent of:
1012       int square (int i)
1013       @{
1014         return i * i;
1015       @}
1016   */
1017   gcc_jit_type *int_type =
1018     gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
1019   gcc_jit_param *param_i =
1020     gcc_jit_context_new_param (ctxt, NULL, int_type, "i");
1021   gcc_jit_function *func =
1022     gcc_jit_context_new_function (ctxt, NULL,
1023                                   GCC_JIT_FUNCTION_EXPORTED,
1024                                   int_type,
1025                                   "square",
1026                                   1, &param_i,
1027                                   0);
1029   gcc_jit_block *block = gcc_jit_function_new_block (func, NULL);
1031   gcc_jit_rvalue *expr =
1032     gcc_jit_context_new_binary_op (
1033       ctxt, NULL,
1034       GCC_JIT_BINARY_OP_MULT, int_type,
1035       gcc_jit_param_as_rvalue (param_i),
1036       gcc_jit_param_as_rvalue (param_i));
1038    gcc_jit_block_end_with_return (block, NULL, expr);
1042 main (int argc, char **argv)
1044   gcc_jit_context *ctxt = NULL;
1045   gcc_jit_result *result = NULL;
1047   /* Get a "context" object for working with the library.  */
1048   ctxt = gcc_jit_context_acquire ();
1049   if (!ctxt)
1050     @{
1051       fprintf (stderr, "NULL ctxt");
1052       goto error;
1053     @}
1055   /* Set some options on the context.
1056      Let's see the code being generated, in assembler form.  */
1057   gcc_jit_context_set_bool_option (
1058     ctxt,
1059     GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
1060     0);
1062   /* Populate the context.  */
1063   create_code (ctxt);
1065   /* Compile the code.  */
1066   result = gcc_jit_context_compile (ctxt);
1067   if (!result)
1068     @{
1069       fprintf (stderr, "NULL result");
1070       goto error;
1071     @}
1073   /* We're done with the context; we can release it: */
1074   gcc_jit_context_release (ctxt);
1075   ctxt = NULL;
1077   /* Extract the generated code from "result".  */
1078   void *fn_ptr = gcc_jit_result_get_code (result, "square");
1079   if (!fn_ptr)
1080      @{
1081        fprintf (stderr, "NULL fn_ptr");
1082        goto error;
1083      @}
1085   typedef int (*fn_type) (int);
1086   fn_type square = (fn_type)fn_ptr;
1087   printf ("result: %d\n", square (5));
1089  error:
1090   if (ctxt)
1091     gcc_jit_context_release (ctxt);
1092   if (result)
1093     gcc_jit_result_release (result);
1094   return 0;
1097 @end example
1099 @noindent
1100 @end quotation
1102 Building and running it:
1104 @example
1105 $ gcc \
1106     tut02-square.c \
1107     -o tut02-square \
1108     -lgccjit
1110 # Run the built program:
1111 $ ./tut02-square
1112 result: 25
1113 @end example
1115 @noindent
1117 @c Copyright (C) 2014 Free Software Foundation, Inc.
1118 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
1119 @c 
1120 @c This is free software: you can redistribute it and/or modify it
1121 @c under the terms of the GNU General Public License as published by
1122 @c the Free Software Foundation, either version 3 of the License, or
1123 @c (at your option) any later version.
1124 @c 
1125 @c This program is distributed in the hope that it will be useful, but
1126 @c WITHOUT ANY WARRANTY; without even the implied warranty of
1127 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
1128 @c General Public License for more details.
1129 @c 
1130 @c You should have received a copy of the GNU General Public License
1131 @c along with this program.  If not, see
1132 @c <http://www.gnu.org/licenses/>.
1134 @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
1135 @anchor{intro/tutorial03 tutorial-part-3-loops-and-variables}@anchor{21}@anchor{intro/tutorial03 doc}@anchor{22}
1136 @section Tutorial part 3: Loops and variables
1139 Consider this C function:
1141 @quotation
1143 @example
1144 int loop_test (int n)
1146   int sum = 0;
1147   for (int i = 0; i < n; i++)
1148     sum += i * i;
1149   return sum;
1151 @end example
1153 @noindent
1154 @end quotation
1156 This example demonstrates some more features of libgccjit, with local
1157 variables and a loop.
1159 To break this down into libgccjit terms, it's usually easier to reword
1160 the @cite{for} loop as a @cite{while} loop, giving:
1162 @quotation
1164 @example
1165 int loop_test (int n)
1167   int sum = 0;
1168   int i = 0;
1169   while (i < n)
1170   @{
1171     sum += i * i;
1172     i++;
1173   @}
1174   return sum;
1176 @end example
1178 @noindent
1179 @end quotation
1181 Here's what the final control flow graph will look like:
1183 @quotation
1186 @float Figure
1188 @image{sum-of-squares1,,,image of a control flow graph,png}
1190 @end float
1192 @end quotation
1194 As before, we include the libgccjit header and make a
1195 @pxref{8,,gcc_jit_context *}.
1197 @example
1198 #include <libgccjit.h>
1200 void test (void)
1202   gcc_jit_context *ctxt;
1203   ctxt = gcc_jit_context_acquire ();
1204 @end example
1206 @noindent
1208 The function works with the C @cite{int} type:
1210 @example
1211 gcc_jit_type *the_type =
1212   gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
1213 gcc_jit_type *return_type = the_type;
1214 @end example
1216 @noindent
1218 though we could equally well make it work on, say, @cite{double}:
1220 @example
1221 gcc_jit_type *the_type =
1222   gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_DOUBLE);
1223 @end example
1225 @noindent
1227 Let's build the function:
1229 @example
1230 gcc_jit_param *n =
1231   gcc_jit_context_new_param (ctxt, NULL, the_type, "n");
1232 gcc_jit_param *params[1] = @{n@};
1233 gcc_jit_function *func =
1234   gcc_jit_context_new_function (ctxt, NULL,
1235                                 GCC_JIT_FUNCTION_EXPORTED,
1236                                 return_type,
1237                                 "loop_test",
1238                                 1, params, 0);
1239 @end example
1241 @noindent
1243 @menu
1244 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues. 
1245 * Control flow:: 
1246 * Visualizing the control flow graph:: 
1247 * Full example: Full example<2>. 
1249 @end menu
1251 @node Expressions lvalues and rvalues,Control flow,,Tutorial part 3 Loops and variables
1252 @anchor{intro/tutorial03 expressions-lvalues-and-rvalues}@anchor{23}
1253 @subsection Expressions: lvalues and rvalues
1256 The base class of expression is the @pxref{13,,gcc_jit_rvalue *},
1257 representing an expression that can be on the @emph{right}-hand side of
1258 an assignment: a value that can be computed somehow, and assigned
1259 @emph{to} a storage area (such as a variable).  It has a specific
1260 @pxref{a,,gcc_jit_type *}.
1262 Anothe important class is @pxref{24,,gcc_jit_lvalue *}.
1263 A @pxref{24,,gcc_jit_lvalue *}. is something that can of the @emph{left}-hand
1264 side of an assignment: a storage area (such as a variable).
1266 In other words, every assignment can be thought of as:
1268 @example
1269 LVALUE = RVALUE;
1270 @end example
1272 @noindent
1274 Note that @pxref{24,,gcc_jit_lvalue *} is a subclass of
1275 @pxref{13,,gcc_jit_rvalue *}, where in an assignment of the form:
1277 @example
1278 LVALUE_A = LVALUE_B;
1279 @end example
1281 @noindent
1283 the @cite{LVALUE_B} implies reading the current value of that storage
1284 area, assigning it into the @cite{LVALUE_A}.
1286 So far the only expressions we've seen are @cite{i * i}:
1288 @example
1289 gcc_jit_rvalue *expr =
1290   gcc_jit_context_new_binary_op (
1291     ctxt, NULL,
1292     GCC_JIT_BINARY_OP_MULT, int_type,
1293     gcc_jit_param_as_rvalue (param_i),
1294     gcc_jit_param_as_rvalue (param_i));
1295 @end example
1297 @noindent
1299 which is a @pxref{13,,gcc_jit_rvalue *}, and the various function
1300 parameters: @cite{param_i} and @cite{param_n}, instances of
1301 @pxref{25,,gcc_jit_param *}, which is a subclass of
1302 @pxref{24,,gcc_jit_lvalue *} (and, in turn, of @pxref{13,,gcc_jit_rvalue *}):
1303 we can both read from and write to function parameters within the
1304 body of a function.
1306 Our new example has a couple of local variables.  We create them by
1307 calling @pxref{26,,gcc_jit_function_new_local()}, supplying a type and a
1308 name:
1310 @example
1311 /* Build locals:  */
1312 gcc_jit_lvalue *i =
1313   gcc_jit_function_new_local (func, NULL, the_type, "i");
1314 gcc_jit_lvalue *sum =
1315   gcc_jit_function_new_local (func, NULL, the_type, "sum");
1316 @end example
1318 @noindent
1320 These are instances of @pxref{24,,gcc_jit_lvalue *} - they can be read from
1321 and written to.
1323 Note that there is no precanned way to create @emph{and} initialize a variable
1324 like in C:
1326 @example
1327 int i = 0;
1328 @end example
1330 @noindent
1332 Instead, having added the local to the function, we have to separately add
1333 an assignment of @cite{0} to @cite{local_i} at the beginning of the function.
1335 @node Control flow,Visualizing the control flow graph,Expressions lvalues and rvalues,Tutorial part 3 Loops and variables
1336 @anchor{intro/tutorial03 control-flow}@anchor{27}
1337 @subsection Control flow
1340 This function has a loop, so we need to build some basic blocks to
1341 handle the control flow.  In this case, we need 4 blocks:
1344 @enumerate 
1346 @item 
1347 before the loop (initializing the locals)
1349 @item 
1350 the conditional at the top of the loop (comparing @cite{i < n})
1352 @item 
1353 the body of the loop
1355 @item 
1356 after the loop terminates (@cite{return sum})
1357 @end enumerate
1359 so we create these as @pxref{28,,gcc_jit_block *} instances within the
1360 @pxref{29,,gcc_jit_function *}:
1362 @example
1363 gcc_jit_block *b_initial =
1364   gcc_jit_function_new_block (func, "initial");
1365 gcc_jit_block *b_loop_cond =
1366   gcc_jit_function_new_block (func, "loop_cond");
1367 gcc_jit_block *b_loop_body =
1368   gcc_jit_function_new_block (func, "loop_body");
1369 gcc_jit_block *b_after_loop =
1370   gcc_jit_function_new_block (func, "after_loop");
1371 @end example
1373 @noindent
1375 We now populate each block with statements.
1377 The entry block @cite{b_initial} consists of initializations followed by a jump
1378 to the conditional.  We assign @cite{0} to @cite{i} and to @cite{sum}, using
1379 @pxref{2a,,gcc_jit_block_add_assignment()} to add
1380 an assignment statement, and using @pxref{2b,,gcc_jit_context_zero()} to get
1381 the constant value @cite{0} for the relevant type for the right-hand side of
1382 the assignment:
1384 @example
1385 /* sum = 0; */
1386 gcc_jit_block_add_assignment (
1387   b_initial, NULL,
1388   sum,
1389   gcc_jit_context_zero (ctxt, the_type));
1391 /* i = 0; */
1392 gcc_jit_block_add_assignment (
1393   b_initial, NULL,
1394   i,
1395   gcc_jit_context_zero (ctxt, the_type));
1396 @end example
1398 @noindent
1400 We can then terminate the entry block by jumping to the conditional:
1402 @example
1403 gcc_jit_block_end_with_jump (b_initial, NULL, b_loop_cond);
1404 @end example
1406 @noindent
1408 The conditional block is equivalent to the line @cite{while (i < n)} from our
1409 C example. It contains a single statement: a conditional, which jumps to
1410 one of two destination blocks depending on a boolean
1411 @pxref{13,,gcc_jit_rvalue *}, in this case the comparison of @cite{i} and @cite{n}.
1412 We build the comparison using @pxref{2c,,gcc_jit_context_new_comparison()}:
1414 @example
1415 gcc_jit_rvalue *guard =
1416   gcc_jit_context_new_comparison (
1417     ctxt, NULL,
1418     GCC_JIT_COMPARISON_GE,
1419     gcc_jit_lvalue_as_rvalue (i),
1420     gcc_jit_param_as_rvalue (n));
1421 @end example
1423 @noindent
1425 and can then use this to add @cite{b_loop_cond}'s sole statement, via
1426 @pxref{2d,,gcc_jit_block_end_with_conditional()}:
1428 @example
1429 gcc_jit_block_end_with_conditional (b_loop_cond, NULL, guard);
1430 @end example
1432 @noindent
1434 Next, we populate the body of the loop.
1436 The C statement @cite{sum += i * i;} is an assignment operation, where an
1437 lvalue is modified "in-place".  We use
1438 @pxref{2e,,gcc_jit_block_add_assignment_op()} to handle these operations:
1440 @example
1441 /* sum += i * i */
1442 gcc_jit_block_add_assignment_op (
1443   b_loop_body, NULL,
1444   sum,
1445   GCC_JIT_BINARY_OP_PLUS,
1446   gcc_jit_context_new_binary_op (
1447     ctxt, NULL,
1448     GCC_JIT_BINARY_OP_MULT, the_type,
1449     gcc_jit_lvalue_as_rvalue (i),
1450     gcc_jit_lvalue_as_rvalue (i)));
1451 @end example
1453 @noindent
1455 The @cite{i++} can be thought of as @cite{i += 1}, and can thus be handled in
1456 a similar way.  We use @pxref{2f,,gcc_jit_context_one()} to get the constant
1457 value @cite{1} (for the relevant type) for the right-hand side
1458 of the assignment.
1460 @example
1461 /* i++ */
1462 gcc_jit_block_add_assignment_op (
1463   b_loop_body, NULL,
1464   i,
1465   GCC_JIT_BINARY_OP_PLUS,
1466   gcc_jit_context_one (ctxt, the_type));
1467 @end example
1469 @noindent
1471 @cartouche
1472 @quotation Note 
1473 For numeric constants other than 0 or 1, we could use
1474 @pxref{30,,gcc_jit_context_new_rvalue_from_int()} and
1475 @pxref{31,,gcc_jit_context_new_rvalue_from_double()}.
1476 @end quotation
1477 @end cartouche
1479 The loop body completes by jumping back to the conditional:
1481 @example
1482 gcc_jit_block_end_with_jump (b_loop_body, NULL, b_loop_cond);
1483 @end example
1485 @noindent
1487 Finally, we populate the @cite{b_after_loop} block, reached when the loop
1488 conditional is false.  We want to generate the equivalent of:
1490 @example
1491 return sum;
1492 @end example
1494 @noindent
1496 so the block is just one statement:
1498 @example
1499 /* return sum */
1500 gcc_jit_block_end_with_return (
1501   b_after_loop,
1502   NULL,
1503   gcc_jit_lvalue_as_rvalue (sum));
1504 @end example
1506 @noindent
1508 @cartouche
1509 @quotation Note 
1510 You can intermingle block creation with statement creation,
1511 but given that the terminator statements generally include references
1512 to other blocks, I find it's clearer to create all the blocks,
1513 @emph{then} all the statements.
1514 @end quotation
1515 @end cartouche
1517 We've finished populating the function.  As before, we can now compile it
1518 to machine code:
1520 @example
1521 gcc_jit_result *result;
1522 result = gcc_jit_context_compile (ctxt);
1524 typedef int (*loop_test_fn_type) (int);
1525 loop_test_fn_type loop_test =
1526  (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
1527 if (!loop_test)
1528   goto error;
1529 printf ("result: %d", loop_test (10));
1530 @end example
1532 @noindent
1534 @example
1535 result: 285
1536 @end example
1538 @noindent
1540 @node Visualizing the control flow graph,Full example<2>,Control flow,Tutorial part 3 Loops and variables
1541 @anchor{intro/tutorial03 visualizing-the-control-flow-graph}@anchor{32}
1542 @subsection Visualizing the control flow graph
1545 You can see the control flow graph of a function using
1546 @pxref{33,,gcc_jit_function_dump_to_dot()}:
1548 @example
1549 gcc_jit_function_dump_to_dot (func, "/tmp/sum-of-squares.dot");
1550 @end example
1552 @noindent
1554 giving a .dot file in GraphViz format.
1556 You can convert this to an image using @cite{dot}:
1558 @example
1559 $ dot -Tpng /tmp/sum-of-squares.dot -o /tmp/sum-of-squares.png
1560 @end example
1562 @noindent
1564 or use a viewer (my preferred one is xdot.py; see
1565 @indicateurl{https://github.com/jrfonseca/xdot.py}; on Fedora you can
1566 install it with @cite{yum install python-xdot}):
1568 @quotation
1571 @float Figure
1573 @image{sum-of-squares1,,,image of a control flow graph,png}
1575 @end float
1577 @end quotation
1579 @node Full example<2>,,Visualizing the control flow graph,Tutorial part 3 Loops and variables
1580 @anchor{intro/tutorial03 full-example}@anchor{34}
1581 @subsection Full example
1584 @quotation
1586 @example
1587 /* Usage example for libgccjit.so
1588    Copyright (C) 2014 Free Software Foundation, Inc.
1590 This file is part of GCC.
1592 GCC is free software; you can redistribute it and/or modify it
1593 under the terms of the GNU General Public License as published by
1594 the Free Software Foundation; either version 3, or (at your option)
1595 any later version.
1597 GCC is distributed in the hope that it will be useful, but
1598 WITHOUT ANY WARRANTY; without even the implied warranty of
1599 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
1600 General Public License for more details.
1602 You should have received a copy of the GNU General Public License
1603 along with GCC; see the file COPYING3.  If not see
1604 <http://www.gnu.org/licenses/>.  */
1606 #include <libgccjit.h>
1608 #include <stdlib.h>
1609 #include <stdio.h>
1611 void
1612 create_code (gcc_jit_context *ctxt)
1614   /*
1615     Simple sum-of-squares, to test conditionals and looping
1617     int loop_test (int n)
1618     @{
1619       int i;
1620       int sum = 0;
1621       for (i = 0; i < n ; i ++)
1622       @{
1623         sum += i * i;
1624       @}
1625       return sum;
1626    */
1627   gcc_jit_type *the_type =
1628     gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
1629   gcc_jit_type *return_type = the_type;
1631   gcc_jit_param *n =
1632     gcc_jit_context_new_param (ctxt, NULL, the_type, "n");
1633   gcc_jit_param *params[1] = @{n@};
1634   gcc_jit_function *func =
1635     gcc_jit_context_new_function (ctxt, NULL,
1636                                   GCC_JIT_FUNCTION_EXPORTED,
1637                                   return_type,
1638                                   "loop_test",
1639                                   1, params, 0);
1641   /* Build locals:  */
1642   gcc_jit_lvalue *i =
1643     gcc_jit_function_new_local (func, NULL, the_type, "i");
1644   gcc_jit_lvalue *sum =
1645     gcc_jit_function_new_local (func, NULL, the_type, "sum");
1647   gcc_jit_block *b_initial =
1648     gcc_jit_function_new_block (func, "initial");
1649   gcc_jit_block *b_loop_cond =
1650     gcc_jit_function_new_block (func, "loop_cond");
1651   gcc_jit_block *b_loop_body =
1652     gcc_jit_function_new_block (func, "loop_body");
1653   gcc_jit_block *b_after_loop =
1654     gcc_jit_function_new_block (func, "after_loop");
1656   /* sum = 0; */
1657   gcc_jit_block_add_assignment (
1658     b_initial, NULL,
1659     sum,
1660     gcc_jit_context_zero (ctxt, the_type));
1662   /* i = 0; */
1663   gcc_jit_block_add_assignment (
1664     b_initial, NULL,
1665     i,
1666     gcc_jit_context_zero (ctxt, the_type));
1668   gcc_jit_block_end_with_jump (b_initial, NULL, b_loop_cond);
1670   /* if (i >= n) */
1671   gcc_jit_block_end_with_conditional (
1672     b_loop_cond, NULL,
1673     gcc_jit_context_new_comparison (
1674        ctxt, NULL,
1675        GCC_JIT_COMPARISON_GE,
1676        gcc_jit_lvalue_as_rvalue (i),
1677        gcc_jit_param_as_rvalue (n)),
1678     b_after_loop,
1679     b_loop_body);
1681   /* sum += i * i */
1682   gcc_jit_block_add_assignment_op (
1683     b_loop_body, NULL,
1684     sum,
1685     GCC_JIT_BINARY_OP_PLUS,
1686     gcc_jit_context_new_binary_op (
1687       ctxt, NULL,
1688       GCC_JIT_BINARY_OP_MULT, the_type,
1689       gcc_jit_lvalue_as_rvalue (i),
1690       gcc_jit_lvalue_as_rvalue (i)));
1692   /* i++ */
1693   gcc_jit_block_add_assignment_op (
1694     b_loop_body, NULL,
1695     i,
1696     GCC_JIT_BINARY_OP_PLUS,
1697     gcc_jit_context_one (ctxt, the_type));
1699   gcc_jit_block_end_with_jump (b_loop_body, NULL, b_loop_cond);
1701   /* return sum */
1702   gcc_jit_block_end_with_return (
1703     b_after_loop,
1704     NULL,
1705     gcc_jit_lvalue_as_rvalue (sum));
1709 main (int argc, char **argv)
1711   gcc_jit_context *ctxt = NULL;
1712   gcc_jit_result *result = NULL;
1714   /* Get a "context" object for working with the library.  */
1715   ctxt = gcc_jit_context_acquire ();
1716   if (!ctxt)
1717     @{
1718       fprintf (stderr, "NULL ctxt");
1719       goto error;
1720     @}
1722   /* Set some options on the context.
1723      Let's see the code being generated, in assembler form.  */
1724   gcc_jit_context_set_bool_option (
1725     ctxt,
1726     GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
1727     0);
1729   /* Populate the context.  */
1730   create_code (ctxt);
1732   /* Compile the code.  */
1733   result = gcc_jit_context_compile (ctxt);
1734   if (!result)
1735     @{
1736       fprintf (stderr, "NULL result");
1737       goto error;
1738     @}
1740   /* Extract the generated code from "result".  */
1741   typedef int (*loop_test_fn_type) (int);
1742   loop_test_fn_type loop_test =
1743     (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
1744   if (!loop_test)
1745     @{
1746       fprintf (stderr, "NULL loop_test");
1747       goto error;
1748     @}
1750   /* Run the generated code.  */
1751   int val = loop_test (10);
1752   printf("loop_test returned: %d\n", val);
1754  error:
1755   gcc_jit_context_release (ctxt);
1756   gcc_jit_result_release (result);
1757   return 0;
1760 @end example
1762 @noindent
1763 @end quotation
1765 Building and running it:
1767 @example
1768 $ gcc \
1769     tut03-sum-of-squares.c \
1770     -o tut03-sum-of-squares \
1771     -lgccjit
1773 # Run the built program:
1774 $ ./tut03-sum-of-squares
1775 loop_test returned: 285
1776 @end example
1778 @noindent
1780 @c Copyright (C) 2014 Free Software Foundation, Inc.
1781 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
1782 @c 
1783 @c This is free software: you can redistribute it and/or modify it
1784 @c under the terms of the GNU General Public License as published by
1785 @c the Free Software Foundation, either version 3 of the License, or
1786 @c (at your option) any later version.
1787 @c 
1788 @c This program is distributed in the hope that it will be useful, but
1789 @c WITHOUT ANY WARRANTY; without even the implied warranty of
1790 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
1791 @c General Public License for more details.
1792 @c 
1793 @c You should have received a copy of the GNU General Public License
1794 @c along with this program.  If not, see
1795 @c <http://www.gnu.org/licenses/>.
1797 @node Tutorial part 4 Adding JIT-compilation to a toy interpreter,,Tutorial part 3 Loops and variables,Tutorial
1798 @anchor{intro/tutorial04 tutorial-part-4-adding-jit-compilation-to-a-toy-interpreter}@anchor{35}@anchor{intro/tutorial04 doc}@anchor{36}
1799 @section Tutorial part 4: Adding JIT-compilation to a toy interpreter
1802 In this example we construct a "toy" interpreter, and add JIT-compilation
1803 to it.
1805 @menu
1806 * Our toy interpreter:: 
1807 * Compiling to machine code:: 
1808 * Setting things up:: 
1809 * Populating the function:: 
1810 * Verifying the control flow graph:: 
1811 * Compiling the context:: 
1812 * Single-stepping through the generated code:: 
1813 * Examining the generated code:: 
1814 * Putting it all together:: 
1815 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?. 
1817 @end menu
1819 @node Our toy interpreter,Compiling to machine code,,Tutorial part 4 Adding JIT-compilation to a toy interpreter
1820 @anchor{intro/tutorial04 our-toy-interpreter}@anchor{37}
1821 @subsection Our toy interpreter
1824 It's a stack-based interpreter, and is intended as a (very simple) example
1825 of the kind of bytecode interpreter seen in dynamic languages such as
1826 Python, Ruby etc.
1828 For the sake of simplicity, our toy virtual machine is very limited:
1830 @quotation
1833 @itemize *
1835 @item 
1836 The only data type is @cite{int}
1838 @item 
1839 It can only work on one function at a time (so that the only
1840 function call that can be made is to recurse).
1842 @item 
1843 Functions can only take one parameter.
1845 @item 
1846 Functions have a stack of @cite{int} values.
1848 @item 
1849 We'll implement function call within the interpreter by calling a
1850 function in our implementation, rather than implementing our own
1851 frame stack.
1853 @item 
1854 The parser is only good enough to get the examples to work.
1855 @end itemize
1856 @end quotation
1858 Naturally, a real interpreter would be much more complicated that this.
1860 The following operations are supported:
1863 @multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxx} 
1864 @headitem
1866 Operation
1868 @tab
1870 Meaning
1872 @tab
1874 Old Stack
1876 @tab
1878 New Stack
1880 @item
1884 @tab
1886 Duplicate top of stack.
1888 @tab
1890 @code{[..., x]}
1892 @tab
1894 @code{[..., x, x]}
1896 @item
1900 @tab
1902 Swap top two elements
1903 of stack.
1905 @tab
1907 @code{[..., x, y]}
1909 @tab
1911 @code{[..., y, x]}
1913 @item
1915 BINARY_ADD
1917 @tab
1919 Add the top two elements
1920 on the stack.
1922 @tab
1924 @code{[..., x, y]}
1926 @tab
1928 @code{[..., (x+y)]}
1930 @item
1932 BINARY_SUBTRACT
1934 @tab
1936 Likewise, but subtract.
1938 @tab
1940 @code{[..., x, y]}
1942 @tab
1944 @code{[..., (x-y)]}
1946 @item
1948 BINARY_MULT
1950 @tab
1952 Likewise, but multiply.
1954 @tab
1956 @code{[..., x, y]}
1958 @tab
1960 @code{[..., (x*y)]}
1962 @item
1964 BINARY_COMPARE_LT
1966 @tab
1968 Compare the top two
1969 elements on the stack
1970 and push a nonzero/zero
1971 if (x<y).
1973 @tab
1975 @code{[..., x, y]}
1977 @tab
1979 @code{[..., (x<y)]}
1981 @item
1983 RECURSE
1985 @tab
1987 Recurse, passing the top
1988 of the stack, and
1989 popping the result.
1991 @tab
1993 @code{[..., x]}
1995 @tab
1997 @code{[..., fn(x)]}
1999 @item
2001 RETURN
2003 @tab
2005 Return the top of the
2006 stack.
2008 @tab
2010 @code{[x]}
2012 @tab
2014 @code{[]}
2016 @item
2018 PUSH_CONST @cite{arg}
2020 @tab
2022 Push an int const.
2024 @tab
2026 @code{[...]}
2028 @tab
2030 @code{[..., arg]}
2032 @item
2034 JUMP_ABS_IF_TRUE @cite{arg}
2036 @tab
2038 Pop; if top of stack was
2039 nonzero, jump to
2040 @code{arg}.
2042 @tab
2044 @code{[..., x]}
2046 @tab
2048 @code{[...]}
2050 @end multitable
2053 Programs can be interpreted, disassembled, and compiled to machine code.
2055 The interpreter reads @code{.toy} scripts.  Here's what a simple recursive
2056 factorial program looks like, the script @code{factorial.toy}.
2057 The parser ignores lines beginning with a @cite{#}.
2059 @quotation
2061 @example
2062 # Simple recursive factorial implementation, roughly equivalent to:
2064 #  int factorial (int arg)
2065 #  @{
2066 #     if (arg < 2)
2067 #       return arg
2068 #     return arg * factorial (arg - 1)
2069 #  @}
2071 # Initial state:
2072 # stack: [arg]
2074 # 0:
2076 # stack: [arg, arg]
2078 # 1:
2079 PUSH_CONST 2
2080 # stack: [arg, arg, 2]
2082 # 2:
2083 BINARY_COMPARE_LT
2084 # stack: [arg, (arg < 2)]
2086 # 3:
2087 JUMP_ABS_IF_TRUE 9
2088 # stack: [arg]
2090 # 4:
2092 # stack: [arg, arg]
2094 # 5:
2095 PUSH_CONST 1
2096 # stack: [arg, arg, 1]
2098 # 6:
2099 BINARY_SUBTRACT
2100 # stack: [arg,  (arg - 1)
2102 # 7:
2103 RECURSE
2104 # stack: [arg, factorial(arg - 1)]
2106 # 8:
2107 BINARY_MULT
2108 # stack: [arg * factorial(arg - 1)]
2110 # 9:
2111 RETURN
2113 @end example
2115 @noindent
2116 @end quotation
2118 The interpreter is a simple infinite loop with a big @code{switch} statement
2119 based on what the next opcode is:
2121 @quotation
2123 @example
2125 static int
2126 toyvm_function_interpret (toyvm_function *fn, int arg, FILE *trace)
2128   toyvm_frame frame;
2129 #define PUSH(ARG) (toyvm_frame_push (&frame, (ARG)))
2130 #define POP(ARG) (toyvm_frame_pop (&frame))
2132   frame.frm_function = fn;
2133   frame.frm_pc = 0;
2134   frame.frm_cur_depth = 0;
2136   PUSH (arg);
2138   while (1)
2139     @{
2140       toyvm_op *op;
2141       int x, y;
2142       assert (frame.frm_pc < fn->fn_num_ops);
2143       op = &fn->fn_ops[frame.frm_pc++];
2145       if (trace)
2146         @{
2147           toyvm_frame_dump_stack (&frame, trace);
2148           toyvm_function_disassemble_op (fn, op, frame.frm_pc, trace);
2149         @}
2151       switch (op->op_opcode)
2152         @{
2153           /* Ops taking no operand.  */
2154         case DUP:
2155           x = POP ();
2156           PUSH (x);
2157           PUSH (x);
2158           break;
2160         case ROT:
2161           y = POP ();
2162           x = POP ();
2163           PUSH (y);
2164           PUSH (x);
2165           break;
2167         case BINARY_ADD:
2168           y = POP ();
2169           x = POP ();
2170           PUSH (x + y);
2171           break;
2173         case BINARY_SUBTRACT:
2174           y = POP ();
2175           x = POP ();
2176           PUSH (x - y);
2177           break;
2179         case BINARY_MULT:
2180           y = POP ();
2181           x = POP ();
2182           PUSH (x * y);
2183           break;
2185         case BINARY_COMPARE_LT:
2186           y = POP ();
2187           x = POP ();
2188           PUSH (x < y);
2189           break;
2191         case RECURSE:
2192           x = POP ();
2193           x = toyvm_function_interpret (fn, x, trace);
2194           PUSH (x);
2195           break;
2197         case RETURN:
2198           return POP ();
2200           /* Ops taking an operand.  */
2201         case PUSH_CONST:
2202           PUSH (op->op_operand);
2203           break;
2205         case JUMP_ABS_IF_TRUE:
2206           x = POP ();
2207           if (x)
2208             frame.frm_pc = op->op_operand;
2209           break;
2211         default:
2212           assert (0); /* unknown opcode */
2214         @} /* end of switch on opcode */
2215     @} /* end of while loop */
2217 #undef PUSH
2218 #undef POP
2222 @end example
2224 @noindent
2225 @end quotation
2227 @node Compiling to machine code,Setting things up,Our toy interpreter,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2228 @anchor{intro/tutorial04 compiling-to-machine-code}@anchor{38}
2229 @subsection Compiling to machine code
2232 We want to generate machine code that can be cast to this type and
2233 then directly executed in-process:
2235 @quotation
2237 @example
2238 typedef int (*toyvm_compiled_code) (int);
2241 @end example
2243 @noindent
2244 @end quotation
2246 The lifetime of the code is tied to that of a @pxref{16,,gcc_jit_result *}.
2247 We'll handle this by bundling them up in a structure, so that we can
2248 clean them up together by calling @pxref{39,,gcc_jit_result_release()}:
2250 @quotation
2252 @example
2254 struct toyvm_compiled_function
2256   gcc_jit_result *cf_jit_result;
2257   toyvm_compiled_code cf_code;
2261 @end example
2263 @noindent
2264 @end quotation
2266 Our compiler isn't very sophisticated; it takes the implementation of
2267 each opcode above, and maps it directly to the operations supported by
2268 the libgccjit API.
2270 How should we handle the stack?  In theory we could calculate what the
2271 stack depth will be at each opcode, and optimize away the stack
2272 manipulation "by hand".  We'll see below that libgccjit is able to do
2273 this for us, so we'll implement stack manipulation
2274 in a direct way, by creating a @code{stack} array and @code{stack_depth}
2275 variables, local within the generated function, equivalent to this C code:
2277 @example
2278 int stack_depth;
2279 int stack[MAX_STACK_DEPTH];
2280 @end example
2282 @noindent
2284 We'll also have local variables @code{x} and @code{y} for use when implementing
2285 the opcodes, equivalent to this:
2287 @example
2288 int x;
2289 int y;
2290 @end example
2292 @noindent
2294 This means our compiler has the following state:
2296 @quotation
2298 @example
2300 struct compilation_state
2302   gcc_jit_context *ctxt;
2304   gcc_jit_type *int_type;
2305   gcc_jit_type *bool_type;
2306   gcc_jit_type *stack_type; /* int[MAX_STACK_DEPTH] */
2308   gcc_jit_rvalue *const_one;
2310   gcc_jit_function *fn;
2311   gcc_jit_param *param_arg;
2312   gcc_jit_lvalue *stack;
2313   gcc_jit_lvalue *stack_depth;
2314   gcc_jit_lvalue *x;
2315   gcc_jit_lvalue *y;
2317   gcc_jit_location *op_locs[MAX_OPS];
2318   gcc_jit_block *initial_block;
2319   gcc_jit_block *op_blocks[MAX_OPS];
2324 @end example
2326 @noindent
2327 @end quotation
2329 @node Setting things up,Populating the function,Compiling to machine code,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2330 @anchor{intro/tutorial04 setting-things-up}@anchor{3a}
2331 @subsection Setting things up
2334 First we create our types:
2336 @quotation
2338 @example
2339   state.int_type =
2340     gcc_jit_context_get_type (state.ctxt, GCC_JIT_TYPE_INT);
2341   state.bool_type =
2342     gcc_jit_context_get_type (state.ctxt, GCC_JIT_TYPE_BOOL);
2343   state.stack_type =
2344     gcc_jit_context_new_array_type (state.ctxt, NULL,
2345                                     state.int_type, MAX_STACK_DEPTH);
2348 @end example
2350 @noindent
2351 @end quotation
2353 along with extracting a useful @cite{int} constant:
2355 @quotation
2357 @example
2358   state.const_one = gcc_jit_context_one (state.ctxt, state.int_type);
2361 @end example
2363 @noindent
2364 @end quotation
2366 We'll implement push and pop in terms of the @code{stack} array and
2367 @code{stack_depth}.  Here are helper functions for adding statements to
2368 a block, implementing pushing and popping values:
2370 @quotation
2372 @example
2374 static void
2375 add_push (compilation_state *state,
2376           gcc_jit_block *block,
2377           gcc_jit_rvalue *rvalue,
2378           gcc_jit_location *loc)
2380   /* stack[stack_depth] = RVALUE */
2381   gcc_jit_block_add_assignment (
2382     block,
2383     loc,
2384     /* stack[stack_depth] */
2385     gcc_jit_context_new_array_access (
2386       state->ctxt,
2387       loc,
2388       gcc_jit_lvalue_as_rvalue (state->stack),
2389       gcc_jit_lvalue_as_rvalue (state->stack_depth)),
2390     rvalue);
2392   /* "stack_depth++;".  */
2393   gcc_jit_block_add_assignment_op (
2394     block,
2395     loc,
2396     state->stack_depth,
2397     GCC_JIT_BINARY_OP_PLUS,
2398     state->const_one);
2401 static void
2402 add_pop (compilation_state *state,
2403          gcc_jit_block *block,
2404          gcc_jit_lvalue *lvalue,
2405          gcc_jit_location *loc)
2407   /* "--stack_depth;".  */
2408   gcc_jit_block_add_assignment_op (
2409     block,
2410     loc,
2411     state->stack_depth,
2412     GCC_JIT_BINARY_OP_MINUS,
2413     state->const_one);
2415   /* "LVALUE = stack[stack_depth];".  */
2416   gcc_jit_block_add_assignment (
2417     block,
2418     loc,
2419     lvalue,
2420     /* stack[stack_depth] */
2421     gcc_jit_lvalue_as_rvalue (
2422       gcc_jit_context_new_array_access (
2423         state->ctxt,
2424         loc,
2425         gcc_jit_lvalue_as_rvalue (state->stack),
2426         gcc_jit_lvalue_as_rvalue (state->stack_depth))));
2430 @end example
2432 @noindent
2433 @end quotation
2435 We will support single-stepping through the generated code in the
2436 debugger, so we need to create @pxref{3b,,gcc_jit_location} instances, one
2437 per operation in the source code.  These will reference the lines of
2438 e.g. @code{factorial.toy}.
2440 @quotation
2442 @example
2443   for (pc = 0; pc < fn->fn_num_ops; pc++)
2444     @{
2445       toyvm_op *op = &fn->fn_ops[pc];
2447       state.op_locs[pc] = gcc_jit_context_new_location (state.ctxt,
2448                                                         fn->fn_filename,
2449                                                         op->op_linenum,
2450                                                         0); /* column */
2451     @}
2454 @end example
2456 @noindent
2457 @end quotation
2459 Let's create the function itself.  As usual, we create its parameter
2460 first, then use the parameter to create the function:
2462 @quotation
2464 @example
2465   state.param_arg =
2466     gcc_jit_context_new_param (state.ctxt, state.op_locs[0],
2467                                state.int_type, "arg");
2468   state.fn =
2469     gcc_jit_context_new_function (state.ctxt,
2470                                   state.op_locs[0],
2471                                   GCC_JIT_FUNCTION_EXPORTED,
2472                                   state.int_type,
2473                                   funcname,
2474                                   1, &state.param_arg, 0);
2477 @end example
2479 @noindent
2480 @end quotation
2482 We create the locals within the function.
2484 @quotation
2486 @example
2487   state.stack =
2488     gcc_jit_function_new_local (state.fn, NULL,
2489                                 state.stack_type, "stack");
2490   state.stack_depth =
2491     gcc_jit_function_new_local (state.fn, NULL,
2492                                 state.int_type, "stack_depth");
2493   state.x =
2494     gcc_jit_function_new_local (state.fn, NULL,
2495                                 state.int_type, "x");
2496   state.y =
2497     gcc_jit_function_new_local (state.fn, NULL,
2498                                 state.int_type, "y");
2501 @end example
2503 @noindent
2504 @end quotation
2506 @node Populating the function,Verifying the control flow graph,Setting things up,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2507 @anchor{intro/tutorial04 populating-the-function}@anchor{3c}
2508 @subsection Populating the function
2511 There's some one-time initialization, and the API treats the first block
2512 you create as the entrypoint of the function, so we need to create that
2513 block first:
2515 @quotation
2517 @example
2518   state.initial_block = gcc_jit_function_new_block (state.fn, "initial");
2521 @end example
2523 @noindent
2524 @end quotation
2526 We can now create blocks for each of the operations.  Most of these will
2527 be consolidated into larger blocks when the optimizer runs.
2529 @quotation
2531 @example
2532   for (pc = 0; pc < fn->fn_num_ops; pc++)
2533     @{
2534       char buf[16];
2535       sprintf (buf, "instr%i", pc);
2536       state.op_blocks[pc] = gcc_jit_function_new_block (state.fn, buf);
2537     @}
2540 @end example
2542 @noindent
2543 @end quotation
2545 Now that we have a block it can jump to when it's done, we can populate
2546 the initial block:
2548 @quotation
2550 @example
2552   /* "stack_depth = 0;".  */
2553   gcc_jit_block_add_assignment (
2554     state.initial_block,
2555     state.op_locs[0],
2556     state.stack_depth,
2557     gcc_jit_context_zero (state.ctxt, state.int_type));
2559   /* "PUSH (arg);".  */
2560   add_push (&state,
2561             state.initial_block,
2562             gcc_jit_param_as_rvalue (state.param_arg),
2563             state.op_locs[0]);
2565   /* ...and jump to insn 0.  */
2566   gcc_jit_block_end_with_jump (state.initial_block,
2567                                state.op_locs[0],
2568                                state.op_blocks[0]);
2571 @end example
2573 @noindent
2574 @end quotation
2576 We can now populate the blocks for the individual operations.  We loop
2577 through them, adding instructions to their blocks:
2579 @quotation
2581 @example
2582   for (pc = 0; pc < fn->fn_num_ops; pc++)
2583     @{
2584       gcc_jit_location *loc = state.op_locs[pc];
2586       gcc_jit_block *block = state.op_blocks[pc];
2587       gcc_jit_block *next_block = (pc < fn->fn_num_ops
2588                                    ? state.op_blocks[pc + 1]
2589                                    : NULL);
2591       toyvm_op *op;
2592       op = &fn->fn_ops[pc];
2595 @end example
2597 @noindent
2598 @end quotation
2600 We're going to have another big @code{switch} statement for implementing
2601 the opcodes, this time for compiling them, rather than interpreting
2602 them.  It's helpful to have macros for implementing push and pop, so that
2603 we can make the @code{switch} statement that's coming up look as much as
2604 possible like the one above within the interpreter:
2606 @example
2608 #define X_EQUALS_POP()\
2609       add_pop (&state, block, state.x, loc)
2610 #define Y_EQUALS_POP()\
2611       add_pop (&state, block, state.y, loc)
2612 #define PUSH_RVALUE(RVALUE)\
2613       add_push (&state, block, (RVALUE), loc)
2614 #define PUSH_X()\
2615       PUSH_RVALUE (gcc_jit_lvalue_as_rvalue (state.x))
2616 #define PUSH_Y() \
2617       PUSH_RVALUE (gcc_jit_lvalue_as_rvalue (state.y))
2620 @end example
2622 @noindent
2624 @cartouche
2625 @quotation Note 
2626 A particularly clever implementation would have an @emph{identical}
2627 @code{switch} statement shared by the interpreter and the compiler, with
2628 some preprocessor "magic".  We're not doing that here, for the sake
2629 of simplicity.
2630 @end quotation
2631 @end cartouche
2633 When I first implemented this compiler, I accidentally missed an edit
2634 when copying and pasting the @code{Y_EQUALS_POP} macro, so that popping the
2635 stack into @code{y} instead erroneously assigned it to @code{x}, leaving @code{y}
2636 uninitialized.
2638 To track this kind of thing down, we can use
2639 @pxref{3d,,gcc_jit_block_add_comment()} to add descriptive comments
2640 to the internal representation.  This is invaluable when looking through
2641 the generated IR for, say @code{factorial}:
2643 @quotation
2645 @example
2647       gcc_jit_block_add_comment (block, loc, opcode_names[op->op_opcode]);
2650 @end example
2652 @noindent
2653 @end quotation
2655 We can now write the big @code{switch} statement that implements the
2656 individual opcodes, populating the relevant block with statements:
2658 @quotation
2660 @example
2662       switch (op->op_opcode)
2663         @{
2664         case DUP:
2665           X_EQUALS_POP ();
2666           PUSH_X ();
2667           PUSH_X ();
2668           break;
2670         case ROT:
2671           Y_EQUALS_POP ();
2672           X_EQUALS_POP ();
2673           PUSH_Y ();
2674           PUSH_X ();
2675           break;
2677         case BINARY_ADD:
2678           Y_EQUALS_POP ();
2679           X_EQUALS_POP ();
2680           PUSH_RVALUE (
2681            gcc_jit_context_new_binary_op (
2682              state.ctxt,
2683              loc,
2684              GCC_JIT_BINARY_OP_PLUS,
2685              state.int_type,
2686              gcc_jit_lvalue_as_rvalue (state.x),
2687              gcc_jit_lvalue_as_rvalue (state.y)));
2688           break;
2690         case BINARY_SUBTRACT:
2691           Y_EQUALS_POP ();
2692           X_EQUALS_POP ();
2693           PUSH_RVALUE (
2694            gcc_jit_context_new_binary_op (
2695              state.ctxt,
2696              loc,
2697              GCC_JIT_BINARY_OP_MINUS,
2698              state.int_type,
2699              gcc_jit_lvalue_as_rvalue (state.x),
2700              gcc_jit_lvalue_as_rvalue (state.y)));
2701           break;
2703         case BINARY_MULT:
2704           Y_EQUALS_POP ();
2705           X_EQUALS_POP ();
2706           PUSH_RVALUE (
2707            gcc_jit_context_new_binary_op (
2708              state.ctxt,
2709              loc,
2710              GCC_JIT_BINARY_OP_MULT,
2711              state.int_type,
2712              gcc_jit_lvalue_as_rvalue (state.x),
2713              gcc_jit_lvalue_as_rvalue (state.y)));
2714           break;
2716         case BINARY_COMPARE_LT:
2717           Y_EQUALS_POP ();
2718           X_EQUALS_POP ();
2719           PUSH_RVALUE (
2720              /* cast of bool to int */
2721              gcc_jit_context_new_cast (
2722                state.ctxt,
2723                loc,
2724                /* (x < y) as a bool */
2725                gcc_jit_context_new_comparison (
2726                  state.ctxt,
2727                  loc,
2728                  GCC_JIT_COMPARISON_LT,
2729                  gcc_jit_lvalue_as_rvalue (state.x),
2730                  gcc_jit_lvalue_as_rvalue (state.y)),
2731                state.int_type));
2732           break;
2734         case RECURSE:
2735           @{
2736             X_EQUALS_POP ();
2737             gcc_jit_rvalue *arg = gcc_jit_lvalue_as_rvalue (state.x);
2738             PUSH_RVALUE (
2739               gcc_jit_context_new_call (
2740                 state.ctxt,
2741                 loc,
2742                 state.fn,
2743                 1, &arg));
2744             break;
2745           @}
2747         case RETURN:
2748           X_EQUALS_POP ();
2749           gcc_jit_block_end_with_return (
2750             block,
2751             loc,
2752             gcc_jit_lvalue_as_rvalue (state.x));
2753           break;
2755           /* Ops taking an operand.  */
2756         case PUSH_CONST:
2757           PUSH_RVALUE (
2758             gcc_jit_context_new_rvalue_from_int (
2759               state.ctxt,
2760               state.int_type,
2761               op->op_operand));
2762           break;
2764         case JUMP_ABS_IF_TRUE:
2765           X_EQUALS_POP ();
2766           gcc_jit_block_end_with_conditional (
2767             block,
2768             loc,
2769             /* "(bool)x".  */
2770             gcc_jit_context_new_cast (
2771               state.ctxt,
2772               loc,
2773               gcc_jit_lvalue_as_rvalue (state.x),
2774               state.bool_type),
2775             state.op_blocks[op->op_operand], /* on_true */
2776             next_block); /* on_false */
2777           break;
2779         default:
2780           assert(0);
2781         @} /* end of switch on opcode */
2784 @end example
2786 @noindent
2787 @end quotation
2789 Every block must be terminated, via a call to one of the
2790 @code{gcc_jit_block_end_with_} entrypoints.  This has been done for two
2791 of the opcodes, but we need to do it for the other ones, by jumping
2792 to the next block.
2794 @quotation
2796 @example
2797       if (op->op_opcode != JUMP_ABS_IF_TRUE
2798           && op->op_opcode != RETURN)
2799         gcc_jit_block_end_with_jump (
2800           block,
2801           loc,
2802           next_block);
2805 @end example
2807 @noindent
2808 @end quotation
2810 This is analogous to simply incrementing the program counter.
2812 @node Verifying the control flow graph,Compiling the context,Populating the function,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2813 @anchor{intro/tutorial04 verifying-the-control-flow-graph}@anchor{3e}
2814 @subsection Verifying the control flow graph
2817 Having finished looping over the blocks, the context is complete.
2819 As before, we can verify that the control flow and statements are sane by
2820 using @pxref{33,,gcc_jit_function_dump_to_dot()}:
2822 @example
2823 gcc_jit_function_dump_to_dot (state.fn, "/tmp/factorial.dot");
2824 @end example
2826 @noindent
2828 and viewing the result.  Note how the label names, comments, and
2829 variable names show up in the dump, to make it easier to spot
2830 errors in our compiler.
2832 @quotation
2835 @float Figure
2837 @image{factorial1,,,image of a control flow graph,png}
2839 @end float
2841 @end quotation
2843 @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
2844 @anchor{intro/tutorial04 compiling-the-context}@anchor{3f}
2845 @subsection Compiling the context
2848 Having finished looping over the blocks and populating them with
2849 statements, the context is complete.
2851 We can now compile it, and extract machine code from the result:
2853 @quotation
2855 @example
2856   gcc_jit_result *jit_result = gcc_jit_context_compile (state.ctxt);
2857   gcc_jit_context_release (state.ctxt);
2859   toyvm_compiled_function *toyvm_result =
2860     (toyvm_compiled_function *)calloc (1, sizeof (toyvm_compiled_function));
2861   if (!toyvm_result)
2862     @{
2863       fprintf (stderr, "out of memory allocating toyvm_compiled_function\n");
2864       gcc_jit_result_release (jit_result);
2865       return NULL;
2866     @}
2868   toyvm_result->cf_jit_result = jit_result;
2869   toyvm_result->cf_code =
2870     (toyvm_compiled_code)gcc_jit_result_get_code (jit_result,
2871                                                   funcname);
2873   free (funcname);
2875   return toyvm_result;
2878 char test[1024];
2880 #define CHECK_NON_NULL(PTR) \
2881   do @{                                       \
2882     if ((PTR) != NULL)                       \
2883       @{                                      \
2884         pass ("%s: %s is non-null", test, #PTR); \
2885       @}                                      \
2886     else                                     \
2887       @{                                      \
2888         fail ("%s: %s is NULL", test, #PTR); \
2889         abort ();                            \
2890     @}                                        \
2891   @} while (0)
2893 #define CHECK_VALUE(ACTUAL, EXPECTED) \
2894   do @{                                       \
2895     if ((ACTUAL) == (EXPECTED))              \
2896       @{                                      \
2897         pass ("%s: actual: %s == expected: %s", test, #ACTUAL, #EXPECTED); \
2898       @}                                      \
2899     else                                     \
2900       @{                                        \
2901         fail ("%s: actual: %s != expected: %s", test, #ACTUAL, #EXPECTED); \
2902         fprintf (stderr, "incorrect value\n"); \
2903         abort ();                              \
2904     @}                                        \
2905   @} while (0)
2907 static void
2908 test_script (const char *scripts_dir, const char *script_name, int input,
2909              int expected_result)
2911   char *script_path;
2912   toyvm_function *fn;
2913   int interpreted_result;
2914   toyvm_compiled_function *compiled_fn;
2915   toyvm_compiled_code code;
2916   int compiled_result;
2918   snprintf (test, sizeof (test), "toyvm.c: %s", script_name);
2920   script_path = (char *)malloc (strlen (scripts_dir)
2921                                 + strlen (script_name) + 1);
2922   CHECK_NON_NULL (script_path);
2923   sprintf (script_path, "%s%s", scripts_dir, script_name);
2925   fn = toyvm_function_parse (script_path, script_name);
2926   CHECK_NON_NULL (fn);
2928   interpreted_result = toyvm_function_interpret (fn, input, NULL);
2929   CHECK_VALUE (interpreted_result, expected_result);
2931   compiled_fn = toyvm_function_compile (fn);
2932   CHECK_NON_NULL (compiled_fn);
2934   code = (toyvm_compiled_code)compiled_fn->cf_code;
2935   CHECK_NON_NULL (code);
2937   compiled_result = code (input);
2938   CHECK_VALUE (compiled_result, expected_result);
2940   gcc_jit_result_release (compiled_fn->cf_jit_result);
2941   free (compiled_fn);
2942   free (fn);
2943   free (script_path);
2946 #define PATH_TO_SCRIPTS  ("/jit/docs/examples/tut04-toyvm/")
2948 static void
2949 test_suite (void)
2951   const char *srcdir;
2952   char *scripts_dir;
2954   snprintf (test, sizeof (test), "toyvm.c");
2956   /* We need to locate the test scripts.
2957      Rely on "srcdir" being set in the environment.  */
2959   srcdir = getenv ("srcdir");
2960   CHECK_NON_NULL (srcdir);
2962   scripts_dir = (char *)malloc (strlen (srcdir) + strlen(PATH_TO_SCRIPTS)
2963                                 + 1);
2964   CHECK_NON_NULL (scripts_dir);
2965   sprintf (scripts_dir, "%s%s", srcdir, PATH_TO_SCRIPTS);
2967   test_script (scripts_dir, "factorial.toy", 10, 3628800);
2968   test_script (scripts_dir, "fibonacci.toy", 10, 55);
2970   free (scripts_dir);
2974 main (int argc, char **argv)
2976   const char *filename = NULL;
2977   toyvm_function *fn = NULL;
2979   /* If called with no args, assume we're being run by the test suite.  */
2980   if (argc < 3)
2981     @{
2982       test_suite ();
2983       return 0;
2984     @}
2986   if (argc != 3)
2987     @{
2988       fprintf (stdout,
2989         "%s FILENAME INPUT: Parse and run a .toy file\n",
2990         argv[0]);
2991       exit (1);
2992     @}
2994   filename = argv[1];
2995   fn = toyvm_function_parse (filename, filename);
2996   if (!fn)
2997     exit (1);
2999   if (0)
3000     toyvm_function_disassemble (fn, stdout);
3002   printf ("interpreter result: %d\n",
3003           toyvm_function_interpret (fn, atoi (argv[2]), NULL));
3005   /* JIT-compilation.  */
3006   toyvm_compiled_function *compiled_fn
3007     = toyvm_function_compile (fn);
3009   toyvm_compiled_code code = compiled_fn->cf_code;
3010   printf ("compiler result: %d\n",
3011           code (atoi (argv[2])));
3013   gcc_jit_result_release (compiled_fn->cf_jit_result);
3014   free (compiled_fn);
3016  return 0;
3019 @end example
3021 @noindent
3022 @end quotation
3024 We can now run the result:
3026 @quotation
3028 @example
3029   toyvm_compiled_function *compiled_fn
3030     = toyvm_function_compile (fn);
3032   toyvm_compiled_code code = compiled_fn->cf_code;
3033   printf ("compiler result: %d\n",
3034           code (atoi (argv[2])));
3036   gcc_jit_result_release (compiled_fn->cf_jit_result);
3037   free (compiled_fn);
3040 @end example
3042 @noindent
3043 @end quotation
3045 @node Single-stepping through the generated code,Examining the generated code,Compiling the context,Tutorial part 4 Adding JIT-compilation to a toy interpreter
3046 @anchor{intro/tutorial04 single-stepping-through-the-generated-code}@anchor{40}
3047 @subsection Single-stepping through the generated code
3050 It's possible to debug the generated code.  To do this we need to both:
3052 @quotation
3055 @itemize *
3057 @item 
3058 Set up source code locations for our statements, so that we can
3059 meaningfully step through the code.  We did this above by
3060 calling @pxref{41,,gcc_jit_context_new_location()} and using the
3061 results.
3063 @item 
3064 Enable the generation of debugging information, by setting
3065 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} on the
3066 @pxref{8,,gcc_jit_context} via
3067 @pxref{1b,,gcc_jit_context_set_bool_option()}:
3069 @example
3070 gcc_jit_context_set_bool_option (
3071   ctxt,
3072   GCC_JIT_BOOL_OPTION_DEBUGINFO,
3073   1);
3074 @end example
3076 @noindent
3077 @end itemize
3078 @end quotation
3080 Having done this, we can put a breakpoint on the generated function:
3082 @example
3083 $ gdb --args ./toyvm factorial.toy 10
3084 (gdb) break factorial
3085 Function "factorial" not defined.
3086 Make breakpoint pending on future shared library load? (y or [n]) y
3087 Breakpoint 1 (factorial) pending.
3088 (gdb) run
3089 Breakpoint 1, factorial (arg=10) at factorial.toy:14
3090 14    DUP
3091 @end example
3093 @noindent
3095 We've set up location information, which references @code{factorial.toy}.
3096 This allows us to use e.g. @code{list} to see where we are in the script:
3098 @example
3099 (gdb) list
3101 10    # Initial state:
3102 11    # stack: [arg]
3104 13    # 0:
3105 14    DUP
3106 15    # stack: [arg, arg]
3108 17    # 1:
3109 18    PUSH_CONST 2
3110 @end example
3112 @noindent
3114 and to step through the function, examining the data:
3116 @example
3117 (gdb) n
3118 18    PUSH_CONST 2
3119 (gdb) n
3120 22    BINARY_COMPARE_LT
3121 (gdb) print stack
3122 $5 = @{10, 10, 2, 0, -7152, 32767, 0, 0@}
3123 (gdb) print stack_depth
3124 $6 = 3
3125 @end example
3127 @noindent
3129 You'll see that the parts of the @code{stack} array that haven't been
3130 touched yet are uninitialized.
3132 @cartouche
3133 @quotation Note 
3134 Turning on optimizations may lead to unpredictable results when
3135 stepping through the generated code: the execution may appear to
3136 "jump around" the source code.  This is analogous to turning up the
3137 optimization level in a regular compiler.
3138 @end quotation
3139 @end cartouche
3141 @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
3142 @anchor{intro/tutorial04 examining-the-generated-code}@anchor{43}
3143 @subsection Examining the generated code
3146 How good is the optimized code?
3148 We can turn up optimizations, by calling
3149 @pxref{1e,,gcc_jit_context_set_int_option()} with
3150 @pxref{1f,,GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}:
3152 @example
3153 gcc_jit_context_set_int_option (
3154   ctxt,
3155   GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL,
3156   3);
3157 @end example
3159 @noindent
3161 One of GCC's internal representations is called "gimple".  A dump of the
3162 initial gimple representation of the code can be seen by setting:
3164 @example
3165 gcc_jit_context_set_bool_option (ctxt,
3166                                  GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE,
3167                                  1);
3168 @end example
3170 @noindent
3172 With optimization on and source locations displayed, this gives:
3174 @c We'll use "c" for gimple dumps
3176 @example
3177 factorial (signed int arg)
3179   <unnamed type> D.80;
3180   signed int D.81;
3181   signed int D.82;
3182   signed int D.83;
3183   signed int D.84;
3184   signed int D.85;
3185   signed int y;
3186   signed int x;
3187   signed int stack_depth;
3188   signed int stack[8];
3190   try
3191     @{
3192       initial:
3193       stack_depth = 0;
3194       stack[stack_depth] = arg;
3195       stack_depth = stack_depth + 1;
3196       goto instr0;
3197       instr0:
3198       /* DUP */:
3199       stack_depth = stack_depth + -1;
3200       x = stack[stack_depth];
3201       stack[stack_depth] = x;
3202       stack_depth = stack_depth + 1;
3203       stack[stack_depth] = x;
3204       stack_depth = stack_depth + 1;
3205       goto instr1;
3206       instr1:
3207       /* PUSH_CONST */:
3208       stack[stack_depth] = 2;
3209       stack_depth = stack_depth + 1;
3210       goto instr2;
3212       /* etc */
3213 @end example
3215 @noindent
3217 You can see the generated machine code in assembly form via:
3219 @example
3220 gcc_jit_context_set_bool_option (
3221   ctxt,
3222   GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
3223   1);
3224 result = gcc_jit_context_compile (ctxt);
3225 @end example
3227 @noindent
3229 which shows that (on this x86_64 box) the compiler has unrolled the loop
3230 and is using MMX instructions to perform several multiplications
3231 simultaneously:
3233 @example
3234         .file   "fake.c"
3235         .text
3236 .Ltext0:
3237         .p2align 4,,15
3238         .globl  factorial
3239         .type   factorial, @@function
3240 factorial:
3241 .LFB0:
3242         .file 1 "factorial.toy"
3243         .loc 1 14 0
3244         .cfi_startproc
3245 .LVL0:
3246 .L2:
3247         .loc 1 26 0
3248         cmpl    $1, %edi
3249         jle     .L13
3250         leal    -1(%rdi), %edx
3251         movl    %edx, %ecx
3252         shrl    $2, %ecx
3253         leal    0(,%rcx,4), %esi
3254         testl   %esi, %esi
3255         je      .L14
3256         cmpl    $9, %edx
3257         jbe     .L14
3258         leal    -2(%rdi), %eax
3259         movl    %eax, -16(%rsp)
3260         leal    -3(%rdi), %eax
3261         movd    -16(%rsp), %xmm0
3262         movl    %edi, -16(%rsp)
3263         movl    %eax, -12(%rsp)
3264         movd    -16(%rsp), %xmm1
3265         xorl    %eax, %eax
3266         movl    %edx, -16(%rsp)
3267         movd    -12(%rsp), %xmm4
3268         movd    -16(%rsp), %xmm6
3269         punpckldq       %xmm4, %xmm0
3270         movdqa  .LC1(%rip), %xmm4
3271         punpckldq       %xmm6, %xmm1
3272         punpcklqdq      %xmm0, %xmm1
3273         movdqa  .LC0(%rip), %xmm0
3274         jmp     .L5
3275         # etc - edited for brevity
3276 @end example
3278 @noindent
3280 This is clearly overkill for a function that will likely overflow the
3281 @code{int} type before the vectorization is worthwhile - but then again, this
3282 is a toy example.
3284 Turning down the optimization level to 2:
3286 @example
3287 gcc_jit_context_set_int_option (
3288   ctxt,
3289   GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL,
3290   3);
3291 @end example
3293 @noindent
3295 yields this code, which is simple enough to quote in its entirety:
3297 @example
3298         .file   "fake.c"
3299         .text
3300         .p2align 4,,15
3301         .globl  factorial
3302         .type   factorial, @@function
3303 factorial:
3304 .LFB0:
3305         .cfi_startproc
3306 .L2:
3307         cmpl    $1, %edi
3308         jle     .L8
3309         movl    $1, %edx
3310         jmp     .L4
3311         .p2align 4,,10
3312         .p2align 3
3313 .L6:
3314         movl    %eax, %edi
3315 .L4:
3316 .L5:
3317         leal    -1(%rdi), %eax
3318         imull   %edi, %edx
3319         cmpl    $1, %eax
3320         jne     .L6
3321 .L3:
3322 .L7:
3323         imull   %edx, %eax
3324         ret
3325 .L8:
3326         movl    %edi, %eax
3327         movl    $1, %edx
3328         jmp     .L7
3329         .cfi_endproc
3330 .LFE0:
3331         .size   factorial, .-factorial
3332         .ident  "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-%@{gcc_release@})"
3333         .section        .note.GNU-stack,"",@@progbits
3334 @end example
3336 @noindent
3338 Note that the stack pushing and popping have been eliminated, as has the
3339 recursive call (in favor of an iteration).
3341 @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
3342 @anchor{intro/tutorial04 putting-it-all-together}@anchor{44}
3343 @subsection Putting it all together
3346 The complete example can be seen in the source tree at
3347 @code{gcc/jit/docs/examples/tut04-toyvm/toyvm.c}
3349 along with a Makefile and a couple of sample .toy scripts:
3351 @example
3352 $ ls -al
3353 drwxrwxr-x. 2 david david   4096 Sep 19 17:46 .
3354 drwxrwxr-x. 3 david david   4096 Sep 19 15:26 ..
3355 -rw-rw-r--. 1 david david    615 Sep 19 12:43 factorial.toy
3356 -rw-rw-r--. 1 david david    834 Sep 19 13:08 fibonacci.toy
3357 -rw-rw-r--. 1 david david    238 Sep 19 14:22 Makefile
3358 -rw-rw-r--. 1 david david  16457 Sep 19 17:07 toyvm.c
3360 $ make toyvm
3361 g++ -Wall -g -o toyvm toyvm.c -lgccjit
3363 $ ./toyvm factorial.toy 10
3364 interpreter result: 3628800
3365 compiler result: 3628800
3367 $ ./toyvm fibonacci.toy 10
3368 interpreter result: 55
3369 compiler result: 55
3370 @end example
3372 @noindent
3374 @node Behind the curtain How does our code get optimized?,,Putting it all together,Tutorial part 4 Adding JIT-compilation to a toy interpreter
3375 @anchor{intro/tutorial04 behind-the-curtain-how-does-our-code-get-optimized}@anchor{45}
3376 @subsection Behind the curtain: How does our code get optimized?
3379 Our example is done, but you may be wondering about exactly how the
3380 compiler turned what we gave it into the machine code seen above.
3382 We can examine what the compiler is doing in detail by setting:
3384 @example
3385 gcc_jit_context_set_bool_option (state.ctxt,
3386                                  GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING,
3387                                  1);
3388 gcc_jit_context_set_bool_option (state.ctxt,
3389                                  GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES,
3390                                  1);
3391 @end example
3393 @noindent
3395 This will dump detailed information about the compiler's state to a
3396 directory under @code{/tmp}, and keep it from being cleaned up.
3398 The precise names and their formats of these files is subject to change.
3399 Higher optimization levels lead to more files.
3400 Here's what I saw (edited for brevity; there were almost 200 files):
3402 @example
3403 intermediate files written to /tmp/libgccjit-KPQbGw
3404 $ ls /tmp/libgccjit-KPQbGw/
3405 fake.c.000i.cgraph
3406 fake.c.000i.type-inheritance
3407 fake.c.004t.gimple
3408 fake.c.007t.omplower
3409 fake.c.008t.lower
3410 fake.c.011t.eh
3411 fake.c.012t.cfg
3412 fake.c.014i.visibility
3413 fake.c.015i.early_local_cleanups
3414 fake.c.016t.ssa
3415 # etc
3416 @end example
3418 @noindent
3420 The gimple code is converted into Static Single Assignment form,
3421 with annotations for use when generating the debuginfo:
3423 @example
3424 $ less /tmp/libgccjit-KPQbGw/fake.c.016t.ssa
3425 @end example
3427 @noindent
3429 @example
3430 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3432 factorial (signed int arg)
3434   signed int stack[8];
3435   signed int stack_depth;
3436   signed int x;
3437   signed int y;
3438   <unnamed type> _20;
3439   signed int _21;
3440   signed int _38;
3441   signed int _44;
3442   signed int _51;
3443   signed int _56;
3445 initial:
3446   stack_depth_3 = 0;
3447   # DEBUG stack_depth => stack_depth_3
3448   stack[stack_depth_3] = arg_5(D);
3449   stack_depth_7 = stack_depth_3 + 1;
3450   # DEBUG stack_depth => stack_depth_7
3451   # DEBUG instr0 => NULL
3452   # DEBUG /* DUP */ => NULL
3453   stack_depth_8 = stack_depth_7 + -1;
3454   # DEBUG stack_depth => stack_depth_8
3455   x_9 = stack[stack_depth_8];
3456   # DEBUG x => x_9
3457   stack[stack_depth_8] = x_9;
3458   stack_depth_11 = stack_depth_8 + 1;
3459   # DEBUG stack_depth => stack_depth_11
3460   stack[stack_depth_11] = x_9;
3461   stack_depth_13 = stack_depth_11 + 1;
3462   # DEBUG stack_depth => stack_depth_13
3463   # DEBUG instr1 => NULL
3464   # DEBUG /* PUSH_CONST */ => NULL
3465   stack[stack_depth_13] = 2;
3467   /* etc; edited for brevity */
3468 @end example
3470 @noindent
3472 We can perhaps better see the code by turning off
3473 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} to suppress all those @code{DEBUG}
3474 statements, giving:
3476 @example
3477 $ less /tmp/libgccjit-1Hywc0/fake.c.016t.ssa
3478 @end example
3480 @noindent
3482 @example
3483 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3485 factorial (signed int arg)
3487   signed int stack[8];
3488   signed int stack_depth;
3489   signed int x;
3490   signed int y;
3491   <unnamed type> _20;
3492   signed int _21;
3493   signed int _38;
3494   signed int _44;
3495   signed int _51;
3496   signed int _56;
3498 initial:
3499   stack_depth_3 = 0;
3500   stack[stack_depth_3] = arg_5(D);
3501   stack_depth_7 = stack_depth_3 + 1;
3502   stack_depth_8 = stack_depth_7 + -1;
3503   x_9 = stack[stack_depth_8];
3504   stack[stack_depth_8] = x_9;
3505   stack_depth_11 = stack_depth_8 + 1;
3506   stack[stack_depth_11] = x_9;
3507   stack_depth_13 = stack_depth_11 + 1;
3508   stack[stack_depth_13] = 2;
3509   stack_depth_15 = stack_depth_13 + 1;
3510   stack_depth_16 = stack_depth_15 + -1;
3511   y_17 = stack[stack_depth_16];
3512   stack_depth_18 = stack_depth_16 + -1;
3513   x_19 = stack[stack_depth_18];
3514   _20 = x_19 < y_17;
3515   _21 = (signed int) _20;
3516   stack[stack_depth_18] = _21;
3517   stack_depth_23 = stack_depth_18 + 1;
3518   stack_depth_24 = stack_depth_23 + -1;
3519   x_25 = stack[stack_depth_24];
3520   if (x_25 != 0)
3521     goto <bb 4> (instr9);
3522   else
3523     goto <bb 3> (instr4);
3525 instr4:
3526 /* DUP */:
3527   stack_depth_26 = stack_depth_24 + -1;
3528   x_27 = stack[stack_depth_26];
3529   stack[stack_depth_26] = x_27;
3530   stack_depth_29 = stack_depth_26 + 1;
3531   stack[stack_depth_29] = x_27;
3532   stack_depth_31 = stack_depth_29 + 1;
3533   stack[stack_depth_31] = 1;
3534   stack_depth_33 = stack_depth_31 + 1;
3535   stack_depth_34 = stack_depth_33 + -1;
3536   y_35 = stack[stack_depth_34];
3537   stack_depth_36 = stack_depth_34 + -1;
3538   x_37 = stack[stack_depth_36];
3539   _38 = x_37 - y_35;
3540   stack[stack_depth_36] = _38;
3541   stack_depth_40 = stack_depth_36 + 1;
3542   stack_depth_41 = stack_depth_40 + -1;
3543   x_42 = stack[stack_depth_41];
3544   _44 = factorial (x_42);
3545   stack[stack_depth_41] = _44;
3546   stack_depth_46 = stack_depth_41 + 1;
3547   stack_depth_47 = stack_depth_46 + -1;
3548   y_48 = stack[stack_depth_47];
3549   stack_depth_49 = stack_depth_47 + -1;
3550   x_50 = stack[stack_depth_49];
3551   _51 = x_50 * y_48;
3552   stack[stack_depth_49] = _51;
3553   stack_depth_53 = stack_depth_49 + 1;
3555   # stack_depth_1 = PHI <stack_depth_24(2), stack_depth_53(3)>
3556 instr9:
3557 /* RETURN */:
3558   stack_depth_54 = stack_depth_1 + -1;
3559   x_55 = stack[stack_depth_54];
3560   _56 = x_55;
3561   stack =@{v@} @{CLOBBER@};
3562   return _56;
3565 @end example
3567 @noindent
3569 Note in the above how all the @pxref{28,,gcc_jit_block} instances we
3570 created have been consolidated into just 3 blocks in GCC's internal
3571 representation: @code{initial}, @code{instr4} and @code{instr9}.
3573 @menu
3574 * Optimizing away stack manipulation:: 
3575 * Elimination of tail recursion:: 
3577 @end menu
3579 @node Optimizing away stack manipulation,Elimination of tail recursion,,Behind the curtain How does our code get optimized?
3580 @anchor{intro/tutorial04 optimizing-away-stack-manipulation}@anchor{46}
3581 @subsubsection Optimizing away stack manipulation
3584 Recall our simple implementation of stack operations.  Let's examine
3585 how the stack operations are optimized away.
3587 After a pass of constant-propagation, the depth of the stack at each
3588 opcode can be determined at compile-time:
3590 @example
3591 $ less /tmp/libgccjit-1Hywc0/fake.c.021t.ccp1
3592 @end example
3594 @noindent
3596 @example
3597 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3599 factorial (signed int arg)
3601   signed int stack[8];
3602   signed int stack_depth;
3603   signed int x;
3604   signed int y;
3605   <unnamed type> _20;
3606   signed int _21;
3607   signed int _38;
3608   signed int _44;
3609   signed int _51;
3611 initial:
3612   stack[0] = arg_5(D);
3613   x_9 = stack[0];
3614   stack[0] = x_9;
3615   stack[1] = x_9;
3616   stack[2] = 2;
3617   y_17 = stack[2];
3618   x_19 = stack[1];
3619   _20 = x_19 < y_17;
3620   _21 = (signed int) _20;
3621   stack[1] = _21;
3622   x_25 = stack[1];
3623   if (x_25 != 0)
3624     goto <bb 4> (instr9);
3625   else
3626     goto <bb 3> (instr4);
3628 instr4:
3629 /* DUP */:
3630   x_27 = stack[0];
3631   stack[0] = x_27;
3632   stack[1] = x_27;
3633   stack[2] = 1;
3634   y_35 = stack[2];
3635   x_37 = stack[1];
3636   _38 = x_37 - y_35;
3637   stack[1] = _38;
3638   x_42 = stack[1];
3639   _44 = factorial (x_42);
3640   stack[1] = _44;
3641   y_48 = stack[1];
3642   x_50 = stack[0];
3643   _51 = x_50 * y_48;
3644   stack[0] = _51;
3646 instr9:
3647 /* RETURN */:
3648   x_55 = stack[0];
3649   x_56 = x_55;
3650   stack =@{v@} @{CLOBBER@};
3651   return x_56;
3654 @end example
3656 @noindent
3658 Note how, in the above, all those @code{stack_depth} values are now just
3659 constants: we're accessing specific stack locations at each opcode.
3661 The "esra" pass ("Early Scalar Replacement of Aggregates") breaks
3662 out our "stack" array into individual elements:
3664 @example
3665 $ less /tmp/libgccjit-1Hywc0/fake.c.024t.esra
3666 @end example
3668 @noindent
3670 @example
3671 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3673 Created a replacement for stack offset: 0, size: 32: stack$0
3674 Created a replacement for stack offset: 32, size: 32: stack$1
3675 Created a replacement for stack offset: 64, size: 32: stack$2
3677 Symbols to be put in SSA form
3678 @{ D.89 D.90 D.91 @}
3679 Incremental SSA update started at block: 0
3680 Number of blocks in CFG: 5
3681 Number of blocks to update: 4 ( 80%)
3684 factorial (signed int arg)
3686   signed int stack$2;
3687   signed int stack$1;
3688   signed int stack$0;
3689   signed int stack[8];
3690   signed int stack_depth;
3691   signed int x;
3692   signed int y;
3693   <unnamed type> _20;
3694   signed int _21;
3695   signed int _38;
3696   signed int _44;
3697   signed int _51;
3699 initial:
3700   stack$0_45 = arg_5(D);
3701   x_9 = stack$0_45;
3702   stack$0_39 = x_9;
3703   stack$1_32 = x_9;
3704   stack$2_30 = 2;
3705   y_17 = stack$2_30;
3706   x_19 = stack$1_32;
3707   _20 = x_19 < y_17;
3708   _21 = (signed int) _20;
3709   stack$1_28 = _21;
3710   x_25 = stack$1_28;
3711   if (x_25 != 0)
3712     goto <bb 4> (instr9);
3713   else
3714     goto <bb 3> (instr4);
3716 instr4:
3717 /* DUP */:
3718   x_27 = stack$0_39;
3719   stack$0_22 = x_27;
3720   stack$1_14 = x_27;
3721   stack$2_12 = 1;
3722   y_35 = stack$2_12;
3723   x_37 = stack$1_14;
3724   _38 = x_37 - y_35;
3725   stack$1_10 = _38;
3726   x_42 = stack$1_10;
3727   _44 = factorial (x_42);
3728   stack$1_6 = _44;
3729   y_48 = stack$1_6;
3730   x_50 = stack$0_22;
3731   _51 = x_50 * y_48;
3732   stack$0_1 = _51;
3734   # stack$0_52 = PHI <stack$0_39(2), stack$0_1(3)>
3735 instr9:
3736 /* RETURN */:
3737   x_55 = stack$0_52;
3738   x_56 = x_55;
3739   stack =@{v@} @{CLOBBER@};
3740   return x_56;
3743 @end example
3745 @noindent
3747 Hence at this point, all those pushes and pops of the stack are now
3748 simply assignments to specific temporary variables.
3750 After some copy propagation, the stack manipulation has been completely
3751 optimized away:
3753 @example
3754 $ less /tmp/libgccjit-1Hywc0/fake.c.026t.copyprop1
3755 @end example
3757 @noindent
3759 @example
3760 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3762 factorial (signed int arg)
3764   signed int stack$2;
3765   signed int stack$1;
3766   signed int stack$0;
3767   signed int stack[8];
3768   signed int stack_depth;
3769   signed int x;
3770   signed int y;
3771   <unnamed type> _20;
3772   signed int _21;
3773   signed int _38;
3774   signed int _44;
3775   signed int _51;
3777 initial:
3778   stack$0_39 = arg_5(D);
3779   _20 = arg_5(D) <= 1;
3780   _21 = (signed int) _20;
3781   if (_21 != 0)
3782     goto <bb 4> (instr9);
3783   else
3784     goto <bb 3> (instr4);
3786 instr4:
3787 /* DUP */:
3788   _38 = arg_5(D) + -1;
3789   _44 = factorial (_38);
3790   _51 = arg_5(D) * _44;
3791   stack$0_1 = _51;
3793   # stack$0_52 = PHI <arg_5(D)(2), _51(3)>
3794 instr9:
3795 /* RETURN */:
3796   stack =@{v@} @{CLOBBER@};
3797   return stack$0_52;
3800 @end example
3802 @noindent
3804 Later on, another pass finally eliminated @code{stack_depth} local and the
3805 unused parts of the @cite{stack`} array altogether:
3807 @example
3808 $ less /tmp/libgccjit-1Hywc0/fake.c.036t.release_ssa
3809 @end example
3811 @noindent
3813 @example
3814 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3816 Released 44 names, 314.29%, removed 44 holes
3817 factorial (signed int arg)
3819   signed int stack$0;
3820   signed int mult_acc_1;
3821   <unnamed type> _5;
3822   signed int _6;
3823   signed int _7;
3824   signed int mul_tmp_10;
3825   signed int mult_acc_11;
3826   signed int mult_acc_13;
3828   # arg_9 = PHI <arg_8(D)(0)>
3829   # mult_acc_13 = PHI <1(0)>
3830 initial:
3832   <bb 5>:
3833   # arg_4 = PHI <arg_9(2), _7(3)>
3834   # mult_acc_1 = PHI <mult_acc_13(2), mult_acc_11(3)>
3835   _5 = arg_4 <= 1;
3836   _6 = (signed int) _5;
3837   if (_6 != 0)
3838     goto <bb 4> (instr9);
3839   else
3840     goto <bb 3> (instr4);
3842 instr4:
3843 /* DUP */:
3844   _7 = arg_4 + -1;
3845   mult_acc_11 = mult_acc_1 * arg_4;
3846   goto <bb 5>;
3848   # stack$0_12 = PHI <arg_4(5)>
3849 instr9:
3850 /* RETURN */:
3851   mul_tmp_10 = mult_acc_1 * stack$0_12;
3852   return mul_tmp_10;
3855 @end example
3857 @noindent
3859 @node Elimination of tail recursion,,Optimizing away stack manipulation,Behind the curtain How does our code get optimized?
3860 @anchor{intro/tutorial04 elimination-of-tail-recursion}@anchor{47}
3861 @subsubsection Elimination of tail recursion
3864 Another significant optimization is the detection that the call to
3865 @code{factorial} is tail recursion, which can be eliminated in favor of
3866 an iteration:
3868 @example
3869 $ less /tmp/libgccjit-1Hywc0/fake.c.030t.tailr1
3870 @end example
3872 @noindent
3874 @example
3875 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3878 Symbols to be put in SSA form
3879 @{ D.88 @}
3880 Incremental SSA update started at block: 0
3881 Number of blocks in CFG: 5
3882 Number of blocks to update: 4 ( 80%)
3885 factorial (signed int arg)
3887   signed int stack$2;
3888   signed int stack$1;
3889   signed int stack$0;
3890   signed int stack[8];
3891   signed int stack_depth;
3892   signed int x;
3893   signed int y;
3894   signed int mult_acc_1;
3895   <unnamed type> _20;
3896   signed int _21;
3897   signed int _38;
3898   signed int mul_tmp_44;
3899   signed int mult_acc_51;
3901   # arg_5 = PHI <arg_39(D)(0), _38(3)>
3902   # mult_acc_1 = PHI <1(0), mult_acc_51(3)>
3903 initial:
3904   _20 = arg_5 <= 1;
3905   _21 = (signed int) _20;
3906   if (_21 != 0)
3907     goto <bb 4> (instr9);
3908   else
3909     goto <bb 3> (instr4);
3911 instr4:
3912 /* DUP */:
3913   _38 = arg_5 + -1;
3914   mult_acc_51 = mult_acc_1 * arg_5;
3915   goto <bb 2> (initial);
3917   # stack$0_52 = PHI <arg_5(2)>
3918 instr9:
3919 /* RETURN */:
3920   stack =@{v@} @{CLOBBER@};
3921   mul_tmp_44 = mult_acc_1 * stack$0_52;
3922   return mul_tmp_44;
3925 @end example
3927 @noindent
3929 @c Copyright (C) 2014 Free Software Foundation, Inc.
3930 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
3931 @c 
3932 @c This is free software: you can redistribute it and/or modify it
3933 @c under the terms of the GNU General Public License as published by
3934 @c the Free Software Foundation, either version 3 of the License, or
3935 @c (at your option) any later version.
3936 @c 
3937 @c This program is distributed in the hope that it will be useful, but
3938 @c WITHOUT ANY WARRANTY; without even the implied warranty of
3939 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
3940 @c General Public License for more details.
3941 @c 
3942 @c You should have received a copy of the GNU General Public License
3943 @c along with this program.  If not, see
3944 @c <http://www.gnu.org/licenses/>.
3946 @node Topic Reference,C++ bindings for libgccjit,Tutorial,Top
3947 @anchor{topics/index doc}@anchor{48}@anchor{topics/index topic-reference}@anchor{49}
3948 @chapter Topic Reference
3951 @c Copyright (C) 2014 Free Software Foundation, Inc.
3952 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
3953 @c 
3954 @c This is free software: you can redistribute it and/or modify it
3955 @c under the terms of the GNU General Public License as published by
3956 @c the Free Software Foundation, either version 3 of the License, or
3957 @c (at your option) any later version.
3958 @c 
3959 @c This program is distributed in the hope that it will be useful, but
3960 @c WITHOUT ANY WARRANTY; without even the implied warranty of
3961 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
3962 @c General Public License for more details.
3963 @c 
3964 @c You should have received a copy of the GNU General Public License
3965 @c along with this program.  If not, see
3966 @c <http://www.gnu.org/licenses/>.
3968 @menu
3969 * Compilation contexts:: 
3970 * Objects:: 
3971 * Types:: 
3972 * Expressions:: 
3973 * Creating and using functions:: 
3974 * Source Locations:: 
3975 * Compilation results:: 
3977 Compilation contexts
3979 * Lifetime-management:: 
3980 * Thread-safety:: 
3981 * Error-handling: Error-handling<2>. 
3982 * Debugging:: 
3983 * Options: Options<2>. 
3985 Options
3987 * String Options:: 
3988 * Boolean options:: 
3989 * Integer options:: 
3991 Types
3993 * Standard types:: 
3994 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile. 
3995 * Structures and unions:: 
3997 Expressions
3999 * Rvalues:: 
4000 * Lvalues:: 
4001 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions. 
4003 Rvalues
4005 * Simple expressions:: 
4006 * Unary Operations:: 
4007 * Binary Operations:: 
4008 * Comparisons:: 
4009 * Function calls:: 
4010 * Type-coercion:: 
4012 Lvalues
4014 * Global variables:: 
4016 Creating and using functions
4018 * Params:: 
4019 * Functions:: 
4020 * Blocks:: 
4021 * Statements:: 
4023 Source Locations
4025 * Faking it:: 
4027 @end menu
4030 @node Compilation contexts,Objects,,Topic Reference
4031 @anchor{topics/contexts compilation-contexts}@anchor{4a}@anchor{topics/contexts doc}@anchor{4b}
4032 @section Compilation contexts
4035 @geindex gcc_jit_context (C type)
4036 @anchor{topics/contexts gcc_jit_context}@anchor{8}
4037 @deffn {C Type} gcc_jit_context
4038 @end deffn
4040 The top-level of the API is the @pxref{8,,gcc_jit_context} type.
4042 A @pxref{8,,gcc_jit_context} instance encapsulates the state of a
4043 compilation.
4045 You can set up options on it, and add types, functions and code.
4046 Invoking @pxref{15,,gcc_jit_context_compile()} on it gives you a
4047 @pxref{16,,gcc_jit_result}.
4049 @menu
4050 * Lifetime-management:: 
4051 * Thread-safety:: 
4052 * Error-handling: Error-handling<2>. 
4053 * Debugging:: 
4054 * Options: Options<2>. 
4056 @end menu
4058 @node Lifetime-management,Thread-safety,,Compilation contexts
4059 @anchor{topics/contexts lifetime-management}@anchor{4c}
4060 @subsection Lifetime-management
4063 Contexts are the unit of lifetime-management within the API: objects
4064 have their lifetime bounded by the context they are created within, and
4065 cleanup of such objects is done for you when the context is released.
4067 @geindex gcc_jit_context_acquire (C function)
4068 @anchor{topics/contexts gcc_jit_context_acquire}@anchor{9}
4069 @deffn {C Function} gcc_jit_context *gcc_jit_context_acquire (void)
4071 This function acquires a new @pxref{e,,gcc_jit_object *} instance,
4072 which is independent of any others that may be present within this
4073 process.
4074 @end deffn
4076 @geindex gcc_jit_context_release (C function)
4077 @anchor{topics/contexts gcc_jit_context_release}@anchor{c}
4078 @deffn {C Function} void gcc_jit_context_release (gcc_jit_context@w{ }*ctxt)
4080 This function releases all resources associated with the given context.
4081 Both the context itself and all of its @pxref{e,,gcc_jit_object *}
4082 instances are cleaned up.  It should be called exactly once on a given
4083 context.
4085 It is invalid to use the context or any of its "contextual" objects
4086 after calling this.
4088 @example
4089 gcc_jit_context_release (ctxt);
4090 @end example
4092 @noindent
4093 @end deffn
4095 @geindex gcc_jit_context_new_child_context (C function)
4096 @anchor{topics/contexts gcc_jit_context_new_child_context}@anchor{4d}
4097 @deffn {C Function} gcc_jit_context * gcc_jit_context_new_child_context (gcc_jit_context@w{ }*parent_ctxt)
4099 Given an existing JIT context, create a child context.
4101 The child inherits a copy of all option-settings from the parent.
4103 The child can reference objects created within the parent, but not
4104 vice-versa.
4106 The lifetime of the child context must be bounded by that of the
4107 parent: you should release a child context before releasing the parent
4108 context.
4110 If you use a function from a parent context within a child context,
4111 you have to compile the parent context before you can compile the
4112 child context, and the gcc_jit_result of the parent context must
4113 outlive the gcc_jit_result of the child context.
4115 This allows caching of shared initializations.  For example, you could
4116 create types and declarations of global functions in a parent context
4117 once within a process, and then create child contexts whenever a
4118 function or loop becomes hot. Each such child context can be used for
4119 JIT-compiling just one function or loop, but can reference types
4120 and helper functions created within the parent context.
4122 Contexts can be arbitrarily nested, provided the above rules are
4123 followed, but it's probably not worth going above 2 or 3 levels, and
4124 there will likely be a performance hit for such nesting.
4125 @end deffn
4127 @node Thread-safety,Error-handling<2>,Lifetime-management,Compilation contexts
4128 @anchor{topics/contexts thread-safety}@anchor{4e}
4129 @subsection Thread-safety
4132 Instances of @pxref{8,,gcc_jit_context *} created via
4133 @pxref{9,,gcc_jit_context_acquire()} are independent from each other:
4134 only one thread may use a given context at once, but multiple threads
4135 could each have their own contexts without needing locks.
4137 Contexts created via @pxref{4d,,gcc_jit_context_new_child_context()} are
4138 related to their parent context.  They can be partitioned by their
4139 ultimate ancestor into independent "family trees".   Only one thread
4140 within a process may use a given "family tree" of such contexts at once,
4141 and if you're using multiple threads you should provide your own locking
4142 around entire such context partitions.
4144 @node Error-handling<2>,Debugging,Thread-safety,Compilation contexts
4145 @anchor{topics/contexts error-handling}@anchor{19}@anchor{topics/contexts id1}@anchor{4f}
4146 @subsection Error-handling
4149 Various kinds of errors are possible when using the API, such as
4150 mismatched types in an assignment.  You can only compile and get code from
4151 a context if no errors occur.
4153 Errors are printed on stderr and can be queried using
4154 @pxref{50,,gcc_jit_context_get_first_error()}.
4156 They typically contain the name of the API entrypoint where the error
4157 occurred, and pertinent information on the problem:
4159 @example
4160 ./buggy-program: error: gcc_jit_block_add_assignment: mismatching types: assignment to i (type: int) from "hello world" (type: const char *)
4161 @end example
4163 @noindent
4165 In general, if an error occurs when using an API entrypoint, the
4166 entrypoint returns NULL.  You don't have to check everywhere for NULL
4167 results, since the API handles a NULL being passed in for any
4168 argument by issuing another error.  This typically leads to a cascade of
4169 followup error messages, but is safe (albeit verbose).  The first error
4170 message is usually the one to pay attention to, since it is likely to
4171 be responsible for all of the rest:
4173 @geindex gcc_jit_context_get_first_error (C function)
4174 @anchor{topics/contexts gcc_jit_context_get_first_error}@anchor{50}
4175 @deffn {C Function} const char *           gcc_jit_context_get_first_error (gcc_jit_context@w{ }*ctxt)
4177 Returns the first error message that occurred on the context.
4179 The returned string is valid for the rest of the lifetime of the
4180 context.
4182 If no errors occurred, this will be NULL.
4183 @end deffn
4185 If you are wrapping the C API for a higher-level language that supports
4186 exception-handling, you may instead by interested in the last error that
4187 occurred on the context, so that you can embed this in an exception:
4189 @geindex gcc_jit_context_get_last_error (C function)
4190 @anchor{topics/contexts gcc_jit_context_get_last_error}@anchor{51}
4191 @deffn {C Function} const char *           gcc_jit_context_get_last_error (gcc_jit_context@w{ }*ctxt)
4193 Returns the last error message that occurred on the context.
4195 The returned string is valid for the rest of the lifetime of the
4196 context.
4198 If no errors occurred, this will be NULL.
4199 @end deffn
4201 @node Debugging,Options<2>,Error-handling<2>,Compilation contexts
4202 @anchor{topics/contexts debugging}@anchor{52}
4203 @subsection Debugging
4206 @geindex gcc_jit_context_dump_to_file (C function)
4207 @anchor{topics/contexts gcc_jit_context_dump_to_file}@anchor{53}
4208 @deffn {C Function} void           gcc_jit_context_dump_to_file (gcc_jit_context@w{ }*ctxt, const char@w{ }*path, int@w{ }update_locations)
4210 To help with debugging: dump a C-like representation to the given path,
4211 describing what's been set up on the context.
4213 If "update_locations" is true, then also set up @pxref{3b,,gcc_jit_location}
4214 information throughout the context, pointing at the dump file as if it
4215 were a source file.  This may be of use in conjunction with
4216 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} to allow stepping through the
4217 code in a debugger.
4218 @end deffn
4220 @geindex gcc_jit_context_set_logfile (C function)
4221 @anchor{topics/contexts gcc_jit_context_set_logfile}@anchor{54}
4222 @deffn {C Function} void           gcc_jit_context_set_logfile (gcc_jit_context@w{ }*ctxt, FILE@w{ }*logfile, int@w{ }flags, int@w{ }verbosity)
4224 To help with debugging; enable ongoing logging of the context's
4225 activity to the given file.
4227 For example, the following will enable logging to stderr.
4229 @example
4230 gcc_jit_context_set_logfile (ctxt, stderr, 0, 0);
4231 @end example
4233 @noindent
4235 Examples of information logged include:
4238 @itemize *
4240 @item 
4241 API calls
4243 @item 
4244 the various steps involved within compilation
4246 @item 
4247 activity on any @pxref{16,,gcc_jit_result} instances created by
4248 the context
4250 @item 
4251 activity within any child contexts
4252 @end itemize
4254 An example of a log can be seen @pxref{55,,here},
4255 though the precise format and kinds of information logged is subject
4256 to change.
4258 The caller remains responsible for closing @cite{logfile}, and it must not
4259 be closed until all users are released.  In particular, note that
4260 child contexts and @pxref{16,,gcc_jit_result} instances created by
4261 the context will use the logfile.
4263 There may a performance cost for logging.
4265 You can turn off logging on @cite{ctxt} by passing @cite{NULL} for @cite{logfile}.
4266 Doing so only affects the context; it does not affect child contexts
4267 or @pxref{16,,gcc_jit_result} instances already created by
4268 the context.
4270 The parameters "flags" and "verbosity" are reserved for future
4271 expansion, and must be zero for now.
4272 @end deffn
4274 To contrast the above: @pxref{53,,gcc_jit_context_dump_to_file()} dumps the
4275 current state of a context to the given path, whereas
4276 @pxref{54,,gcc_jit_context_set_logfile()} enables on-going logging of
4277 future activies on a context to the given @cite{FILE *}.
4279 @geindex gcc_jit_context_enable_dump (C function)
4280 @anchor{topics/contexts gcc_jit_context_enable_dump}@anchor{56}
4281 @deffn {C Function} void           gcc_jit_context_enable_dump (gcc_jit_context@w{ }*ctxt, const char@w{ }*dumpname, char@w{ }**out_ptr)
4283 Enable the dumping of a specific set of internal state from the
4284 compilation, capturing the result in-memory as a buffer.
4286 Parameter "dumpname" corresponds to the equivalent gcc command-line
4287 option, without the "-fdump-" prefix.
4288 For example, to get the equivalent of @code{-fdump-tree-vrp1},
4289 supply @code{"tree-vrp1"}:
4291 @example
4292 static char *dump_vrp1;
4294 void
4295 create_code (gcc_jit_context *ctxt)
4297    gcc_jit_context_enable_dump (ctxt, "tree-vrp1", &dump_vrp1);
4298    /* (other API calls omitted for brevity) */
4300 @end example
4302 @noindent
4304 The context directly stores the dumpname as a @code{(const char *)}, so
4305 the passed string must outlive the context.
4307 @pxref{15,,gcc_jit_context_compile()} will capture the dump as a
4308 dynamically-allocated buffer, writing it to @code{*out_ptr}.
4310 The caller becomes responsible for calling:
4312 @example
4313 free (*out_ptr)
4314 @end example
4316 @noindent
4318 each time that @pxref{15,,gcc_jit_context_compile()} is called.
4319 @code{*out_ptr} will be written to, either with the address of a buffer,
4320 or with @code{NULL} if an error occurred.
4322 @cartouche
4323 @quotation Warning 
4324 This API entrypoint is likely to be less stable than the others.
4325 In particular, both the precise dumpnames, and the format and content
4326 of the dumps are subject to change.
4328 It exists primarily for writing the library's own test suite.
4329 @end quotation
4330 @end cartouche
4331 @end deffn
4333 @node Options<2>,,Debugging,Compilation contexts
4334 @anchor{topics/contexts options}@anchor{57}
4335 @subsection Options
4338 @menu
4339 * String Options:: 
4340 * Boolean options:: 
4341 * Integer options:: 
4343 @end menu
4345 @node String Options,Boolean options,,Options<2>
4346 @anchor{topics/contexts string-options}@anchor{58}
4347 @subsubsection String Options
4350 @geindex gcc_jit_context_set_str_option (C function)
4351 @anchor{topics/contexts gcc_jit_context_set_str_option}@anchor{59}
4352 @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)
4354 Set a string option of the context.
4356 @geindex gcc_jit_str_option (C type)
4357 @anchor{topics/contexts gcc_jit_str_option}@anchor{5a}
4358 @deffn {C Type} enum gcc_jit_str_option
4359 @end deffn
4361 There is currently just one string option:
4363 @geindex GCC_JIT_STR_OPTION_PROGNAME (C macro)
4364 @anchor{topics/contexts GCC_JIT_STR_OPTION_PROGNAME}@anchor{5b}
4365 @deffn {C Macro} GCC_JIT_STR_OPTION_PROGNAME
4367 The name of the program, for use as a prefix when printing error
4368 messages to stderr.  If @cite{NULL}, or default, "libgccjit.so" is used.
4369 @end deffn
4370 @end deffn
4372 @node Boolean options,Integer options,String Options,Options<2>
4373 @anchor{topics/contexts boolean-options}@anchor{5c}
4374 @subsubsection Boolean options
4377 @geindex gcc_jit_context_set_bool_option (C function)
4378 @anchor{topics/contexts gcc_jit_context_set_bool_option}@anchor{1b}
4379 @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)
4381 Set a boolean option of the context.
4382 Zero is "false" (the default), non-zero is "true".
4384 @geindex gcc_jit_bool_option (C type)
4385 @anchor{topics/contexts gcc_jit_bool_option}@anchor{5d}
4386 @deffn {C Type} enum gcc_jit_bool_option
4387 @end deffn
4389 @geindex GCC_JIT_BOOL_OPTION_DEBUGINFO (C macro)
4390 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DEBUGINFO}@anchor{42}
4391 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DEBUGINFO
4393 If true, @pxref{15,,gcc_jit_context_compile()} will attempt to do the right
4394 thing so that if you attach a debugger to the process, it will
4395 be able to inspect variables and step through your code.
4397 Note that you can't step through code unless you set up source
4398 location information for the code (by creating and passing in
4399 @pxref{3b,,gcc_jit_location} instances).
4400 @end deffn
4402 @geindex GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE (C macro)
4403 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE}@anchor{5e}
4404 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE
4406 If true, @pxref{15,,gcc_jit_context_compile()} will dump its initial
4407 "tree" representation of your code to stderr (before any
4408 optimizations).
4410 Here's some sample output (from the @cite{square} example):
4412 @example
4413 <statement_list 0x7f4875a62cc0
4414    type <void_type 0x7f4875a64bd0 VOID
4415        align 8 symtab 0 alias set -1 canonical type 0x7f4875a64bd0
4416        pointer_to_this <pointer_type 0x7f4875a64c78>>
4417    side-effects head 0x7f4875a761e0 tail 0x7f4875a761f8 stmts 0x7f4875a62d20 0x7f4875a62d00
4419    stmt <label_expr 0x7f4875a62d20 type <void_type 0x7f4875a64bd0>
4420        side-effects
4421        arg 0 <label_decl 0x7f4875a79080 entry type <void_type 0x7f4875a64bd0>
4422            VOID file (null) line 0 col 0
4423            align 1 context <function_decl 0x7f4875a77500 square>>>
4424    stmt <return_expr 0x7f4875a62d00
4425        type <integer_type 0x7f4875a645e8 public SI
4426            size <integer_cst 0x7f4875a623a0 constant 32>
4427            unit size <integer_cst 0x7f4875a623c0 constant 4>
4428            align 32 symtab 0 alias set -1 canonical type 0x7f4875a645e8 precision 32 min <integer_cst 0x7f4875a62340 -2147483648> max <integer_cst 0x7f4875a62360 2147483647>
4429            pointer_to_this <pointer_type 0x7f4875a6b348>>
4430        side-effects
4431        arg 0 <modify_expr 0x7f4875a72a78 type <integer_type 0x7f4875a645e8>
4432            side-effects arg 0 <result_decl 0x7f4875a7a000 D.54>
4433            arg 1 <mult_expr 0x7f4875a72a50 type <integer_type 0x7f4875a645e8>
4434                arg 0 <parm_decl 0x7f4875a79000 i> arg 1 <parm_decl 0x7f4875a79000 i>>>>>
4435 @end example
4437 @noindent
4438 @end deffn
4440 @geindex GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE (C macro)
4441 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE}@anchor{1c}
4442 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE
4444 If true, @pxref{15,,gcc_jit_context_compile()} will dump the "gimple"
4445 representation of your code to stderr, before any optimizations
4446 are performed.  The dump resembles C code:
4448 @example
4449 square (signed int i)
4451   signed int D.56;
4453   entry:
4454   D.56 = i * i;
4455   return D.56;
4457 @end example
4459 @noindent
4460 @end deffn
4462 @geindex GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE (C macro)
4463 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE}@anchor{1d}
4464 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE
4466 If true, @pxref{15,,gcc_jit_context_compile()} will dump the final
4467 generated code to stderr, in the form of assembly language:
4469 @example
4470     .file    "fake.c"
4471     .text
4472     .globl    square
4473     .type    square, @@function
4474 square:
4475 .LFB0:
4476     .cfi_startproc
4477     pushq    %rbp
4478     .cfi_def_cfa_offset 16
4479     .cfi_offset 6, -16
4480     movq    %rsp, %rbp
4481     .cfi_def_cfa_register 6
4482     movl    %edi, -4(%rbp)
4483 .L2:
4484     movl    -4(%rbp), %eax
4485     imull    -4(%rbp), %eax
4486     popq    %rbp
4487     .cfi_def_cfa 7, 8
4488     ret
4489     .cfi_endproc
4490 .LFE0:
4491     .size    square, .-square
4492     .ident    "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.1-%@{gcc_release@})"
4493     .section    .note.GNU-stack,"",@@progbits
4494 @end example
4496 @noindent
4497 @end deffn
4499 @geindex GCC_JIT_BOOL_OPTION_DUMP_SUMMARY (C macro)
4500 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_SUMMARY}@anchor{5f}
4501 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_SUMMARY
4503 If true, @pxref{15,,gcc_jit_context_compile()} will print information to stderr
4504 on the actions it is performing, followed by a profile showing
4505 the time taken and memory usage of each phase.
4506 @end deffn
4508 @geindex GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING (C macro)
4509 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING}@anchor{60}
4510 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING
4512 If true, @pxref{15,,gcc_jit_context_compile()} will dump copious
4513 amount of information on what it's doing to various
4514 files within a temporary directory.  Use
4515 @pxref{61,,GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES} (see below) to
4516 see the results.  The files are intended to be human-readable,
4517 but the exact files and their formats are subject to change.
4518 @end deffn
4520 @geindex GCC_JIT_BOOL_OPTION_SELFCHECK_GC (C macro)
4521 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_SELFCHECK_GC}@anchor{62}
4522 @deffn {C Macro} GCC_JIT_BOOL_OPTION_SELFCHECK_GC
4524 If true, libgccjit will aggressively run its garbage collector, to
4525 shake out bugs (greatly slowing down the compile).  This is likely
4526 to only be of interest to developers @emph{of} the library.  It is
4527 used when running the selftest suite.
4528 @end deffn
4530 @geindex GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES (C macro)
4531 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES}@anchor{61}
4532 @deffn {C Macro} GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES
4534 If true, the @pxref{8,,gcc_jit_context} will not clean up intermediate files
4535 written to the filesystem, and will display their location on stderr.
4536 @end deffn
4537 @end deffn
4539 @node Integer options,,Boolean options,Options<2>
4540 @anchor{topics/contexts integer-options}@anchor{63}
4541 @subsubsection Integer options
4544 @geindex gcc_jit_context_set_int_option (C function)
4545 @anchor{topics/contexts gcc_jit_context_set_int_option}@anchor{1e}
4546 @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)
4548 Set an integer option of the context.
4550 @geindex gcc_jit_int_option (C type)
4551 @anchor{topics/contexts gcc_jit_int_option}@anchor{64}
4552 @deffn {C Type} enum gcc_jit_int_option
4553 @end deffn
4555 There is currently just one integer option:
4557 @geindex GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL (C macro)
4558 @anchor{topics/contexts GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}@anchor{1f}
4559 @deffn {C Macro} GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL
4561 How much to optimize the code.
4563 Valid values are 0-3, corresponding to GCC's command-line options
4564 -O0 through -O3.
4566 The default value is 0 (unoptimized).
4567 @end deffn
4568 @end deffn
4570 @c Copyright (C) 2014 Free Software Foundation, Inc.
4571 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
4572 @c 
4573 @c This is free software: you can redistribute it and/or modify it
4574 @c under the terms of the GNU General Public License as published by
4575 @c the Free Software Foundation, either version 3 of the License, or
4576 @c (at your option) any later version.
4577 @c 
4578 @c This program is distributed in the hope that it will be useful, but
4579 @c WITHOUT ANY WARRANTY; without even the implied warranty of
4580 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
4581 @c General Public License for more details.
4582 @c 
4583 @c You should have received a copy of the GNU General Public License
4584 @c along with this program.  If not, see
4585 @c <http://www.gnu.org/licenses/>.
4587 @node Objects,Types,Compilation contexts,Topic Reference
4588 @anchor{topics/objects objects}@anchor{65}@anchor{topics/objects doc}@anchor{66}
4589 @section Objects
4592 @geindex gcc_jit_object (C type)
4593 @anchor{topics/objects gcc_jit_object}@anchor{e}
4594 @deffn {C Type} gcc_jit_object
4595 @end deffn
4597 Almost every entity in the API (with the exception of
4598 @pxref{8,,gcc_jit_context *} and @pxref{16,,gcc_jit_result *}) is a
4599 "contextual" object, a @pxref{e,,gcc_jit_object *}
4601 A JIT object:
4603 @quotation
4606 @itemize *
4608 @item 
4609 is associated with a @pxref{8,,gcc_jit_context *}.
4611 @item 
4612 is automatically cleaned up for you when its context is released so
4613 you don't need to manually track and cleanup all objects, just the
4614 contexts.
4615 @end itemize
4616 @end quotation
4618 Although the API is C-based, there is a form of class hierarchy, which
4619 looks like this:
4621 @example
4622 +- gcc_jit_object
4623     +- gcc_jit_location
4624     +- gcc_jit_type
4625        +- gcc_jit_struct
4626     +- gcc_jit_field
4627     +- gcc_jit_function
4628     +- gcc_jit_block
4629     +- gcc_jit_rvalue
4630         +- gcc_jit_lvalue
4631            +- gcc_jit_param
4632 @end example
4634 @noindent
4636 There are casting methods for upcasting from subclasses to parent classes.
4637 For example, @pxref{d,,gcc_jit_type_as_object()}:
4639 @example
4640 gcc_jit_object *obj = gcc_jit_type_as_object (int_type);
4641 @end example
4643 @noindent
4645 The object "base class" has the following operations:
4647 @geindex gcc_jit_object_get_context (C function)
4648 @anchor{topics/objects gcc_jit_object_get_context}@anchor{67}
4649 @deffn {C Function} gcc_jit_context *gcc_jit_object_get_context (gcc_jit_object@w{ }*obj)
4651 Which context is "obj" within?
4652 @end deffn
4654 @geindex gcc_jit_object_get_debug_string (C function)
4655 @anchor{topics/objects gcc_jit_object_get_debug_string}@anchor{f}
4656 @deffn {C Function} const char *gcc_jit_object_get_debug_string (gcc_jit_object@w{ }*obj)
4658 Generate a human-readable description for the given object.
4660 For example,
4662 @example
4663 printf ("obj: %s\n", gcc_jit_object_get_debug_string (obj));
4664 @end example
4666 @noindent
4668 might give this text on stdout:
4670 @example
4671 obj: 4.0 * (float)i
4672 @end example
4674 @noindent
4676 @cartouche
4677 @quotation Note 
4678 If you call this on an object, the @cite{const char *} buffer is allocated
4679 and generated on the first call for that object, and the buffer will
4680 have the same lifetime as the object  i.e. it will exist until the
4681 object's context is released.
4682 @end quotation
4683 @end cartouche
4684 @end deffn
4686 @c Copyright (C) 2014 Free Software Foundation, Inc.
4687 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
4688 @c 
4689 @c This is free software: you can redistribute it and/or modify it
4690 @c under the terms of the GNU General Public License as published by
4691 @c the Free Software Foundation, either version 3 of the License, or
4692 @c (at your option) any later version.
4693 @c 
4694 @c This program is distributed in the hope that it will be useful, but
4695 @c WITHOUT ANY WARRANTY; without even the implied warranty of
4696 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
4697 @c General Public License for more details.
4698 @c 
4699 @c You should have received a copy of the GNU General Public License
4700 @c along with this program.  If not, see
4701 @c <http://www.gnu.org/licenses/>.
4703 @node Types,Expressions,Objects,Topic Reference
4704 @anchor{topics/types doc}@anchor{68}@anchor{topics/types types}@anchor{69}
4705 @section Types
4708 @geindex gcc_jit_type (C type)
4709 @anchor{topics/types gcc_jit_type}@anchor{a}
4710 @deffn {C Type} gcc_jit_type
4712 gcc_jit_type represents a type within the library.
4713 @end deffn
4715 @geindex gcc_jit_type_as_object (C function)
4716 @anchor{topics/types gcc_jit_type_as_object}@anchor{d}
4717 @deffn {C Function} gcc_jit_object *gcc_jit_type_as_object (gcc_jit_type@w{ }*type)
4719 Upcast a type to an object.
4720 @end deffn
4722 Types can be created in several ways:
4725 @itemize *
4727 @item 
4728 fundamental types can be accessed using
4729 @pxref{b,,gcc_jit_context_get_type()}:
4731 @example
4732 gcc_jit_type *int_type = gcc_jit_context_get_type (GCC_JIT_TYPE_INT);
4733 @end example
4735 @noindent
4737 See @pxref{b,,gcc_jit_context_get_type()} for the available types.
4739 @item 
4740 derived types can be accessed by using functions such as
4741 @pxref{6a,,gcc_jit_type_get_pointer()} and @pxref{6b,,gcc_jit_type_get_const()}:
4743 @example
4744 gcc_jit_type *const_int_star = gcc_jit_type_get_pointer (gcc_jit_type_get_const (int_type));
4745 gcc_jit_type *int_const_star = gcc_jit_type_get_const (gcc_jit_type_get_pointer (int_type));
4746 @end example
4748 @noindent
4750 @item 
4751 by creating structures (see below).
4752 @end itemize
4754 @menu
4755 * Standard types:: 
4756 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile. 
4757 * Structures and unions:: 
4759 @end menu
4761 @node Standard types,Pointers const and volatile,,Types
4762 @anchor{topics/types standard-types}@anchor{6c}
4763 @subsection Standard types
4766 @geindex gcc_jit_context_get_type (C function)
4767 @anchor{topics/types gcc_jit_context_get_type}@anchor{b}
4768 @deffn {C Function} gcc_jit_type *gcc_jit_context_get_type (gcc_jit_context@w{ }*ctxt, enum gcc_jit_types@w{ }type_)
4770 Access a specific type.  The available types are:
4773 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
4774 @headitem
4776 @cite{enum gcc_jit_types} value
4778 @tab
4780 Meaning
4782 @item
4784 @code{GCC_JIT_TYPE_VOID}
4786 @tab
4788 C's @code{void} type.
4790 @item
4792 @code{GCC_JIT_TYPE_VOID_PTR}
4794 @tab
4796 C's @code{void *}.
4798 @item
4800 @code{GCC_JIT_TYPE_BOOL}
4802 @tab
4804 C++'s @code{bool} type; also C99's
4805 @code{_Bool} type, aka @code{bool} if
4806 using stdbool.h.
4808 @item
4810 @code{GCC_JIT_TYPE_CHAR}
4812 @tab
4814 C's @code{char} (of some signedness)
4816 @item
4818 @code{GCC_JIT_TYPE_SIGNED_CHAR}
4820 @tab
4822 C's @code{signed char}
4824 @item
4826 @code{GCC_JIT_TYPE_UNSIGNED_CHAR}
4828 @tab
4830 C's @code{unsigned char}
4832 @item
4834 @code{GCC_JIT_TYPE_SHORT}
4836 @tab
4838 C's @code{short} (signed)
4840 @item
4842 @code{GCC_JIT_TYPE_UNSIGNED_SHORT}
4844 @tab
4846 C's @code{unsigned short}
4848 @item
4850 @code{GCC_JIT_TYPE_INT}
4852 @tab
4854 C's @code{int} (signed)
4856 @item
4858 @code{GCC_JIT_TYPE_UNSIGNED_INT}
4860 @tab
4862 C's @code{unsigned int}
4864 @item
4866 @code{GCC_JIT_TYPE_LONG}
4868 @tab
4870 C's @code{long} (signed)
4872 @item
4874 @code{GCC_JIT_TYPE_UNSIGNED_LONG}
4876 @tab
4878 C's @code{unsigned long}
4880 @item
4882 @code{GCC_JIT_TYPE_LONG_LONG}
4884 @tab
4886 C99's @code{long long} (signed)
4888 @item
4890 @code{GCC_JIT_TYPE_UNSIGNED_LONG_LONG}
4892 @tab
4894 C99's @code{unsigned long long}
4896 @item
4898 @code{GCC_JIT_TYPE_FLOAT}
4900 @tab
4902 @item
4904 @code{GCC_JIT_TYPE_DOUBLE}
4906 @tab
4908 @item
4910 @code{GCC_JIT_TYPE_LONG_DOUBLE}
4912 @tab
4914 @item
4916 @code{GCC_JIT_TYPE_CONST_CHAR_PTR}
4918 @tab
4920 C type: @code{(const char *)}
4922 @item
4924 @code{GCC_JIT_TYPE_SIZE_T}
4926 @tab
4928 C's @code{size_t} type
4930 @item
4932 @code{GCC_JIT_TYPE_FILE_PTR}
4934 @tab
4936 C type: @code{(FILE *)}
4938 @item
4940 @code{GCC_JIT_TYPE_COMPLEX_FLOAT}
4942 @tab
4944 C99's @code{_Complex float}
4946 @item
4948 @code{GCC_JIT_TYPE_COMPLEX_DOUBLE}
4950 @tab
4952 C99's @code{_Complex double}
4954 @item
4956 @code{GCC_JIT_TYPE_COMPLEX_LONG_DOUBLE}
4958 @tab
4960 C99's @code{_Complex long double}
4962 @end multitable
4964 @end deffn
4966 @geindex gcc_jit_context_get_int_type (C function)
4967 @anchor{topics/types gcc_jit_context_get_int_type}@anchor{6d}
4968 @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)
4970 Access the integer type of the given size.
4971 @end deffn
4973 @node Pointers const and volatile,Structures and unions,Standard types,Types
4974 @anchor{topics/types pointers-const-and-volatile}@anchor{6e}
4975 @subsection Pointers, @cite{const}, and @cite{volatile}
4978 @geindex gcc_jit_type_get_pointer (C function)
4979 @anchor{topics/types gcc_jit_type_get_pointer}@anchor{6a}
4980 @deffn {C Function} gcc_jit_type *gcc_jit_type_get_pointer (gcc_jit_type@w{ }*type)
4982 Given type "T", get type "T*".
4983 @end deffn
4985 @geindex gcc_jit_type_get_const (C function)
4986 @anchor{topics/types gcc_jit_type_get_const}@anchor{6b}
4987 @deffn {C Function} gcc_jit_type *gcc_jit_type_get_const (gcc_jit_type@w{ }*type)
4989 Given type "T", get type "const T".
4990 @end deffn
4992 @geindex gcc_jit_type_get_volatile (C function)
4993 @anchor{topics/types gcc_jit_type_get_volatile}@anchor{6f}
4994 @deffn {C Function} gcc_jit_type *gcc_jit_type_get_volatile (gcc_jit_type@w{ }*type)
4996 Given type "T", get type "volatile T".
4997 @end deffn
4999 @geindex gcc_jit_context_new_array_type (C function)
5000 @anchor{topics/types gcc_jit_context_new_array_type}@anchor{70}
5001 @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)
5003 Given type "T", get type "T[N]" (for a constant N).
5004 @end deffn
5006 @node Structures and unions,,Pointers const and volatile,Types
5007 @anchor{topics/types structures-and-unions}@anchor{71}
5008 @subsection Structures and unions
5011 @geindex gcc_jit_struct (C type)
5012 @anchor{topics/types gcc_jit_struct}@anchor{72}
5013 @deffn {C Type} gcc_jit_struct
5014 @end deffn
5016 A compound type analagous to a C @cite{struct}.
5018 @geindex gcc_jit_field (C type)
5019 @anchor{topics/types gcc_jit_field}@anchor{73}
5020 @deffn {C Type} gcc_jit_field
5021 @end deffn
5023 A field within a @pxref{72,,gcc_jit_struct}.
5025 You can model C @cite{struct} types by creating @pxref{72,,gcc_jit_struct *} and
5026 @pxref{73,,gcc_jit_field} instances, in either order:
5029 @itemize *
5031 @item 
5032 by creating the fields, then the structure.  For example, to model:
5034 @example
5035 struct coord @{double x; double y; @};
5036 @end example
5038 @noindent
5040 you could call:
5042 @example
5043 gcc_jit_field *field_x =
5044   gcc_jit_context_new_field (ctxt, NULL, double_type, "x");
5045 gcc_jit_field *field_y =
5046   gcc_jit_context_new_field (ctxt, NULL, double_type, "y");
5047 gcc_jit_field *fields[2] = @{field_x, field_y@};
5048 gcc_jit_struct *coord =
5049   gcc_jit_context_new_struct_type (ctxt, NULL, "coord", 2, fields);
5050 @end example
5052 @noindent
5054 @item 
5055 by creating the structure, then populating it with fields, typically
5056 to allow modelling self-referential structs such as:
5058 @example
5059 struct node @{ int m_hash; struct node *m_next; @};
5060 @end example
5062 @noindent
5064 like this:
5066 @example
5067 gcc_jit_type *node =
5068   gcc_jit_context_new_opaque_struct (ctxt, NULL, "node");
5069 gcc_jit_type *node_ptr =
5070   gcc_jit_type_get_pointer (node);
5071 gcc_jit_field *field_hash =
5072   gcc_jit_context_new_field (ctxt, NULL, int_type, "m_hash");
5073 gcc_jit_field *field_next =
5074   gcc_jit_context_new_field (ctxt, NULL, node_ptr, "m_next");
5075 gcc_jit_field *fields[2] = @{field_hash, field_next@};
5076 gcc_jit_struct_set_fields (node, NULL, 2, fields);
5077 @end example
5079 @noindent
5080 @end itemize
5082 @geindex gcc_jit_context_new_field (C function)
5083 @anchor{topics/types gcc_jit_context_new_field}@anchor{74}
5084 @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)
5086 Construct a new field, with the given type and name.
5087 @end deffn
5089 @geindex gcc_jit_field_as_object (C function)
5090 @anchor{topics/types gcc_jit_field_as_object}@anchor{75}
5091 @deffn {C Function} gcc_jit_object *           gcc_jit_field_as_object (gcc_jit_field@w{ }*field)
5093 Upcast from field to object.
5094 @end deffn
5096 @geindex gcc_jit_context_new_struct_type (C function)
5097 @anchor{topics/types gcc_jit_context_new_struct_type}@anchor{76}
5098 @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)
5100 @quotation
5102 Construct a new struct type, with the given name and fields.
5103 @end quotation
5104 @end deffn
5106 @geindex gcc_jit_context_new_opaque_struct (C function)
5107 @anchor{topics/types gcc_jit_context_new_opaque_struct}@anchor{77}
5108 @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)
5110 Construct a new struct type, with the given name, but without
5111 specifying the fields.   The fields can be omitted (in which case the
5112 size of the struct is not known), or later specified using
5113 @pxref{78,,gcc_jit_struct_set_fields()}.
5114 @end deffn
5116 @geindex gcc_jit_struct_as_type (C function)
5117 @anchor{topics/types gcc_jit_struct_as_type}@anchor{79}
5118 @deffn {C Function} gcc_jit_type *           gcc_jit_struct_as_type (gcc_jit_struct@w{ }*struct_type)
5120 Upcast from struct to type.
5121 @end deffn
5123 @geindex gcc_jit_struct_set_fields (C function)
5124 @anchor{topics/types gcc_jit_struct_set_fields}@anchor{78}
5125 @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)
5127 Populate the fields of a formerly-opaque struct type.
5129 This can only be called once on a given struct type.
5130 @end deffn
5132 @c Copyright (C) 2014 Free Software Foundation, Inc.
5133 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
5134 @c 
5135 @c This is free software: you can redistribute it and/or modify it
5136 @c under the terms of the GNU General Public License as published by
5137 @c the Free Software Foundation, either version 3 of the License, or
5138 @c (at your option) any later version.
5139 @c 
5140 @c This program is distributed in the hope that it will be useful, but
5141 @c WITHOUT ANY WARRANTY; without even the implied warranty of
5142 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
5143 @c General Public License for more details.
5144 @c 
5145 @c You should have received a copy of the GNU General Public License
5146 @c along with this program.  If not, see
5147 @c <http://www.gnu.org/licenses/>.
5149 @node Expressions,Creating and using functions,Types,Topic Reference
5150 @anchor{topics/expressions expressions}@anchor{7a}@anchor{topics/expressions doc}@anchor{7b}
5151 @section Expressions
5154 @menu
5155 * Rvalues:: 
5156 * Lvalues:: 
5157 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions. 
5159 Rvalues
5161 * Simple expressions:: 
5162 * Unary Operations:: 
5163 * Binary Operations:: 
5164 * Comparisons:: 
5165 * Function calls:: 
5166 * Type-coercion:: 
5168 Lvalues
5170 * Global variables:: 
5172 @end menu
5175 @node Rvalues,Lvalues,,Expressions
5176 @anchor{topics/expressions rvalues}@anchor{7c}
5177 @subsection Rvalues
5180 @geindex gcc_jit_rvalue (C type)
5181 @anchor{topics/expressions gcc_jit_rvalue}@anchor{13}
5182 @deffn {C Type} gcc_jit_rvalue
5183 @end deffn
5185 A @pxref{13,,gcc_jit_rvalue *} is an expression that can be computed.
5187 It can be simple, e.g.:
5189 @quotation
5192 @itemize *
5194 @item 
5195 an integer value e.g. @cite{0} or @cite{42}
5197 @item 
5198 a string literal e.g. @cite{"Hello world"}
5200 @item 
5201 a variable e.g. @cite{i}.  These are also lvalues (see below).
5202 @end itemize
5203 @end quotation
5205 or compound e.g.:
5207 @quotation
5210 @itemize *
5212 @item 
5213 a unary expression e.g. @cite{!cond}
5215 @item 
5216 a binary expression e.g. @cite{(a + b)}
5218 @item 
5219 a function call e.g. @cite{get_distance (&player_ship@comma{} &target)}
5221 @item 
5222 etc.
5223 @end itemize
5224 @end quotation
5226 Every rvalue has an associated type, and the API will check to ensure
5227 that types match up correctly (otherwise the context will emit an error).
5229 @geindex gcc_jit_rvalue_get_type (C function)
5230 @anchor{topics/expressions gcc_jit_rvalue_get_type}@anchor{7d}
5231 @deffn {C Function} gcc_jit_type *gcc_jit_rvalue_get_type (gcc_jit_rvalue@w{ }*rvalue)
5233 Get the type of this rvalue.
5234 @end deffn
5236 @geindex gcc_jit_rvalue_as_object (C function)
5237 @anchor{topics/expressions gcc_jit_rvalue_as_object}@anchor{14}
5238 @deffn {C Function} gcc_jit_object *gcc_jit_rvalue_as_object (gcc_jit_rvalue@w{ }*rvalue)
5240 Upcast the given rvalue to be an object.
5241 @end deffn
5243 @menu
5244 * Simple expressions:: 
5245 * Unary Operations:: 
5246 * Binary Operations:: 
5247 * Comparisons:: 
5248 * Function calls:: 
5249 * Type-coercion:: 
5251 @end menu
5253 @node Simple expressions,Unary Operations,,Rvalues
5254 @anchor{topics/expressions simple-expressions}@anchor{7e}
5255 @subsubsection Simple expressions
5258 @geindex gcc_jit_context_new_rvalue_from_int (C function)
5259 @anchor{topics/expressions gcc_jit_context_new_rvalue_from_int}@anchor{30}
5260 @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)
5262 Given a numeric type (integer or floating point), build an rvalue for
5263 the given constant value.
5264 @end deffn
5266 @geindex gcc_jit_context_zero (C function)
5267 @anchor{topics/expressions gcc_jit_context_zero}@anchor{2b}
5268 @deffn {C Function} gcc_jit_rvalue *gcc_jit_context_zero (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*numeric_type)
5270 Given a numeric type (integer or floating point), get the rvalue for
5271 zero.  Essentially this is just a shortcut for:
5273 @example
5274 gcc_jit_context_new_rvalue_from_int (ctxt, numeric_type, 0)
5275 @end example
5277 @noindent
5278 @end deffn
5280 @geindex gcc_jit_context_one (C function)
5281 @anchor{topics/expressions gcc_jit_context_one}@anchor{2f}
5282 @deffn {C Function} gcc_jit_rvalue *gcc_jit_context_one (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*numeric_type)
5284 Given a numeric type (integer or floating point), get the rvalue for
5285 zero.  Essentially this is just a shortcut for:
5287 @example
5288 gcc_jit_context_new_rvalue_from_int (ctxt, numeric_type, 1)
5289 @end example
5291 @noindent
5292 @end deffn
5294 @geindex gcc_jit_context_new_rvalue_from_double (C function)
5295 @anchor{topics/expressions gcc_jit_context_new_rvalue_from_double}@anchor{31}
5296 @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)
5298 Given a numeric type (integer or floating point), build an rvalue for
5299 the given constant value.
5300 @end deffn
5302 @geindex gcc_jit_context_new_rvalue_from_ptr (C function)
5303 @anchor{topics/expressions gcc_jit_context_new_rvalue_from_ptr}@anchor{7f}
5304 @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)
5306 Given a pointer type, build an rvalue for the given address.
5307 @end deffn
5309 @geindex gcc_jit_context_null (C function)
5310 @anchor{topics/expressions gcc_jit_context_null}@anchor{80}
5311 @deffn {C Function} gcc_jit_rvalue *gcc_jit_context_null (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*pointer_type)
5313 Given a pointer type, build an rvalue for @code{NULL}.  Essentially this
5314 is just a shortcut for:
5316 @example
5317 gcc_jit_context_new_rvalue_from_ptr (ctxt, pointer_type, NULL)
5318 @end example
5320 @noindent
5321 @end deffn
5323 @geindex gcc_jit_context_new_string_literal (C function)
5324 @anchor{topics/expressions gcc_jit_context_new_string_literal}@anchor{81}
5325 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_context_new_string_literal (gcc_jit_context@w{ }*ctxt, const char@w{ }*value)
5327 Generate an rvalue for the given NIL-terminated string, of type
5328 @code{GCC_JIT_TYPE_CONST_CHAR_PTR}.
5329 @end deffn
5331 @node Unary Operations,Binary Operations,Simple expressions,Rvalues
5332 @anchor{topics/expressions unary-operations}@anchor{82}
5333 @subsubsection Unary Operations
5336 @geindex gcc_jit_context_new_unary_op (C function)
5337 @anchor{topics/expressions gcc_jit_context_new_unary_op}@anchor{83}
5338 @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)
5340 Build a unary operation out of an input rvalue.
5341 @end deffn
5343 @geindex gcc_jit_unary_op (C type)
5344 @anchor{topics/expressions gcc_jit_unary_op}@anchor{84}
5345 @deffn {C Type} enum gcc_jit_unary_op
5346 @end deffn
5348 The available unary operations are:
5351 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
5352 @headitem
5354 Unary Operation
5356 @tab
5358 C equivalent
5360 @item
5362 @pxref{85,,GCC_JIT_UNARY_OP_MINUS}
5364 @tab
5366 @cite{-(EXPR)}
5368 @item
5370 @pxref{86,,GCC_JIT_UNARY_OP_BITWISE_NEGATE}
5372 @tab
5374 @cite{~(EXPR)}
5376 @item
5378 @pxref{87,,GCC_JIT_UNARY_OP_LOGICAL_NEGATE}
5380 @tab
5382 @cite{!(EXPR)}
5384 @item
5386 @pxref{88,,GCC_JIT_UNARY_OP_ABS}
5388 @tab
5390 @cite{abs (EXPR)}
5392 @end multitable
5395 @geindex GCC_JIT_UNARY_OP_MINUS (C macro)
5396 @anchor{topics/expressions GCC_JIT_UNARY_OP_MINUS}@anchor{85}
5397 @deffn {C Macro} GCC_JIT_UNARY_OP_MINUS
5399 Negate an arithmetic value; analogous to:
5401 @example
5402 -(EXPR)
5403 @end example
5405 @noindent
5407 in C.
5408 @end deffn
5410 @geindex GCC_JIT_UNARY_OP_BITWISE_NEGATE (C macro)
5411 @anchor{topics/expressions GCC_JIT_UNARY_OP_BITWISE_NEGATE}@anchor{86}
5412 @deffn {C Macro} GCC_JIT_UNARY_OP_BITWISE_NEGATE
5414 Bitwise negation of an integer value (one's complement); analogous
5417 @example
5418 ~(EXPR)
5419 @end example
5421 @noindent
5423 in C.
5424 @end deffn
5426 @geindex GCC_JIT_UNARY_OP_LOGICAL_NEGATE (C macro)
5427 @anchor{topics/expressions GCC_JIT_UNARY_OP_LOGICAL_NEGATE}@anchor{87}
5428 @deffn {C Macro} GCC_JIT_UNARY_OP_LOGICAL_NEGATE
5430 Logical negation of an arithmetic or pointer value; analogous to:
5432 @example
5433 !(EXPR)
5434 @end example
5436 @noindent
5438 in C.
5439 @end deffn
5441 @geindex GCC_JIT_UNARY_OP_ABS (C macro)
5442 @anchor{topics/expressions GCC_JIT_UNARY_OP_ABS}@anchor{88}
5443 @deffn {C Macro} GCC_JIT_UNARY_OP_ABS
5445 Absolute value of an arithmetic expression; analogous to:
5447 @example
5448 abs (EXPR)
5449 @end example
5451 @noindent
5453 in C.
5454 @end deffn
5456 @node Binary Operations,Comparisons,Unary Operations,Rvalues
5457 @anchor{topics/expressions binary-operations}@anchor{89}
5458 @subsubsection Binary Operations
5461 @geindex gcc_jit_context_new_binary_op (C function)
5462 @anchor{topics/expressions gcc_jit_context_new_binary_op}@anchor{12}
5463 @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)
5465 Build a binary operation out of two constituent rvalues.
5466 @end deffn
5468 @geindex gcc_jit_binary_op (C type)
5469 @anchor{topics/expressions gcc_jit_binary_op}@anchor{8a}
5470 @deffn {C Type} enum gcc_jit_binary_op
5471 @end deffn
5473 The available binary operations are:
5476 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
5477 @headitem
5479 Binary Operation
5481 @tab
5483 C equivalent
5485 @item
5487 @pxref{8b,,GCC_JIT_BINARY_OP_PLUS}
5489 @tab
5491 @cite{x + y}
5493 @item
5495 @code{GCC_JIT_BINARY_OP_MINUS}
5497 @tab
5499 @cite{x - y}
5501 @item
5503 @pxref{8c,,GCC_JIT_BINARY_OP_MULT}
5505 @tab
5507 @cite{x * y}
5509 @item
5511 @pxref{8d,,GCC_JIT_BINARY_OP_DIVIDE}
5513 @tab
5515 @cite{x / y}
5517 @item
5519 @pxref{8e,,GCC_JIT_BINARY_OP_MODULO}
5521 @tab
5523 @cite{x % y}
5525 @item
5527 @pxref{8f,,GCC_JIT_BINARY_OP_BITWISE_AND}
5529 @tab
5531 @cite{x & y}
5533 @item
5535 @pxref{90,,GCC_JIT_BINARY_OP_BITWISE_XOR}
5537 @tab
5539 @cite{x ^ y}
5541 @item
5543 @pxref{91,,GCC_JIT_BINARY_OP_BITWISE_OR}
5545 @tab
5547 @cite{x | y}
5549 @item
5551 @pxref{92,,GCC_JIT_BINARY_OP_LOGICAL_AND}
5553 @tab
5555 @cite{x && y}
5557 @item
5559 @pxref{93,,GCC_JIT_BINARY_OP_LOGICAL_OR}
5561 @tab
5563 @cite{x || y}
5565 @item
5567 @pxref{94,,GCC_JIT_BINARY_OP_LSHIFT}
5569 @tab
5571 @cite{x << y}
5573 @item
5575 @pxref{95,,GCC_JIT_BINARY_OP_RSHIFT}
5577 @tab
5579 @cite{x >> y}
5581 @end multitable
5584 @geindex GCC_JIT_BINARY_OP_PLUS (C macro)
5585 @anchor{topics/expressions GCC_JIT_BINARY_OP_PLUS}@anchor{8b}
5586 @deffn {C Macro} GCC_JIT_BINARY_OP_PLUS
5588 Addition of arithmetic values; analogous to:
5590 @example
5591 (EXPR_A) + (EXPR_B)
5592 @end example
5594 @noindent
5596 in C.
5598 For pointer addition, use @pxref{96,,gcc_jit_context_new_array_access()}.
5599 @end deffn
5602 @deffn {C Macro} GCC_JIT_BINARY_OP_MINUS`
5604 Subtraction of arithmetic values; analogous to:
5606 @example
5607 (EXPR_A) - (EXPR_B)
5608 @end example
5610 @noindent
5612 in C.
5613 @end deffn
5615 @geindex GCC_JIT_BINARY_OP_MULT (C macro)
5616 @anchor{topics/expressions GCC_JIT_BINARY_OP_MULT}@anchor{8c}
5617 @deffn {C Macro} GCC_JIT_BINARY_OP_MULT
5619 Multiplication of a pair of arithmetic values; analogous to:
5621 @example
5622 (EXPR_A) * (EXPR_B)
5623 @end example
5625 @noindent
5627 in C.
5628 @end deffn
5630 @geindex GCC_JIT_BINARY_OP_DIVIDE (C macro)
5631 @anchor{topics/expressions GCC_JIT_BINARY_OP_DIVIDE}@anchor{8d}
5632 @deffn {C Macro} GCC_JIT_BINARY_OP_DIVIDE
5634 Quotient of division of arithmetic values; analogous to:
5636 @example
5637 (EXPR_A) / (EXPR_B)
5638 @end example
5640 @noindent
5642 in C.
5644 The result type affects the kind of division: if the result type is
5645 integer-based, then the result is truncated towards zero, whereas
5646 a floating-point result type indicates floating-point division.
5647 @end deffn
5649 @geindex GCC_JIT_BINARY_OP_MODULO (C macro)
5650 @anchor{topics/expressions GCC_JIT_BINARY_OP_MODULO}@anchor{8e}
5651 @deffn {C Macro} GCC_JIT_BINARY_OP_MODULO
5653 Remainder of division of arithmetic values; analogous to:
5655 @example
5656 (EXPR_A) % (EXPR_B)
5657 @end example
5659 @noindent
5661 in C.
5662 @end deffn
5664 @geindex GCC_JIT_BINARY_OP_BITWISE_AND (C macro)
5665 @anchor{topics/expressions GCC_JIT_BINARY_OP_BITWISE_AND}@anchor{8f}
5666 @deffn {C Macro} GCC_JIT_BINARY_OP_BITWISE_AND
5668 Bitwise AND; analogous to:
5670 @example
5671 (EXPR_A) & (EXPR_B)
5672 @end example
5674 @noindent
5676 in C.
5677 @end deffn
5679 @geindex GCC_JIT_BINARY_OP_BITWISE_XOR (C macro)
5680 @anchor{topics/expressions GCC_JIT_BINARY_OP_BITWISE_XOR}@anchor{90}
5681 @deffn {C Macro} GCC_JIT_BINARY_OP_BITWISE_XOR
5683 Bitwise exclusive OR; analogous to:
5685 @example
5686 (EXPR_A) ^ (EXPR_B)
5687 @end example
5689 @noindent
5691 in C.
5692 @end deffn
5694 @geindex GCC_JIT_BINARY_OP_BITWISE_OR (C macro)
5695 @anchor{topics/expressions GCC_JIT_BINARY_OP_BITWISE_OR}@anchor{91}
5696 @deffn {C Macro} GCC_JIT_BINARY_OP_BITWISE_OR
5698 Bitwise inclusive OR; analogous to:
5700 @example
5701 (EXPR_A) | (EXPR_B)
5702 @end example
5704 @noindent
5706 in C.
5707 @end deffn
5709 @geindex GCC_JIT_BINARY_OP_LOGICAL_AND (C macro)
5710 @anchor{topics/expressions GCC_JIT_BINARY_OP_LOGICAL_AND}@anchor{92}
5711 @deffn {C Macro} GCC_JIT_BINARY_OP_LOGICAL_AND
5713 Logical AND; analogous to:
5715 @example
5716 (EXPR_A) && (EXPR_B)
5717 @end example
5719 @noindent
5721 in C.
5722 @end deffn
5724 @geindex GCC_JIT_BINARY_OP_LOGICAL_OR (C macro)
5725 @anchor{topics/expressions GCC_JIT_BINARY_OP_LOGICAL_OR}@anchor{93}
5726 @deffn {C Macro} GCC_JIT_BINARY_OP_LOGICAL_OR
5728 Logical OR; analogous to:
5730 @example
5731 (EXPR_A) || (EXPR_B)
5732 @end example
5734 @noindent
5736 in C.
5737 @end deffn
5739 @geindex GCC_JIT_BINARY_OP_LSHIFT (C macro)
5740 @anchor{topics/expressions GCC_JIT_BINARY_OP_LSHIFT}@anchor{94}
5741 @deffn {C Macro} GCC_JIT_BINARY_OP_LSHIFT
5743 Left shift; analogous to:
5745 @example
5746 (EXPR_A) << (EXPR_B)
5747 @end example
5749 @noindent
5751 in C.
5752 @end deffn
5754 @geindex GCC_JIT_BINARY_OP_RSHIFT (C macro)
5755 @anchor{topics/expressions GCC_JIT_BINARY_OP_RSHIFT}@anchor{95}
5756 @deffn {C Macro} GCC_JIT_BINARY_OP_RSHIFT
5758 Right shift; analogous to:
5760 @example
5761 (EXPR_A) >> (EXPR_B)
5762 @end example
5764 @noindent
5766 in C.
5767 @end deffn
5769 @node Comparisons,Function calls,Binary Operations,Rvalues
5770 @anchor{topics/expressions comparisons}@anchor{97}
5771 @subsubsection Comparisons
5774 @geindex gcc_jit_context_new_comparison (C function)
5775 @anchor{topics/expressions gcc_jit_context_new_comparison}@anchor{2c}
5776 @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)
5778 Build a boolean rvalue out of the comparison of two other rvalues.
5779 @end deffn
5781 @geindex gcc_jit_comparison (C type)
5782 @anchor{topics/expressions gcc_jit_comparison}@anchor{98}
5783 @deffn {C Type} enum gcc_jit_comparison
5784 @end deffn
5787 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
5788 @headitem
5790 Comparison
5792 @tab
5794 C equivalent
5796 @item
5798 @code{GCC_JIT_COMPARISON_EQ}
5800 @tab
5802 @cite{x == y}
5804 @item
5806 @code{GCC_JIT_COMPARISON_NE}
5808 @tab
5810 @cite{x != y}
5812 @item
5814 @code{GCC_JIT_COMPARISON_LT}
5816 @tab
5818 @cite{x < y}
5820 @item
5822 @code{GCC_JIT_COMPARISON_LE}
5824 @tab
5826 @cite{x <= y}
5828 @item
5830 @code{GCC_JIT_COMPARISON_GT}
5832 @tab
5834 @cite{x > y}
5836 @item
5838 @code{GCC_JIT_COMPARISON_GE}
5840 @tab
5842 @cite{x >= y}
5844 @end multitable
5847 @node Function calls,Type-coercion,Comparisons,Rvalues
5848 @anchor{topics/expressions function-calls}@anchor{99}
5849 @subsubsection Function calls
5852 @geindex gcc_jit_context_new_call (C function)
5853 @anchor{topics/expressions gcc_jit_context_new_call}@anchor{9a}
5854 @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)
5856 Given a function and the given table of argument rvalues, construct a
5857 call to the function, with the result as an rvalue.
5859 @cartouche
5860 @quotation Note 
5861 @pxref{9a,,gcc_jit_context_new_call()} merely builds a
5862 @pxref{13,,gcc_jit_rvalue} i.e. an expression that can be evaluated,
5863 perhaps as part of a more complicated expression.
5864 The call @emph{won't} happen unless you add a statement to a function
5865 that evaluates the expression.
5867 For example, if you want to call a function and discard the result
5868 (or to call a function with @code{void} return type), use
5869 @pxref{9b,,gcc_jit_block_add_eval()}:
5871 @example
5872 /* Add "(void)printf (arg0, arg1);".  */
5873 gcc_jit_block_add_eval (
5874   block, NULL,
5875   gcc_jit_context_new_call (
5876     ctxt,
5877     NULL,
5878     printf_func,
5879     2, args));
5880 @end example
5882 @noindent
5883 @end quotation
5884 @end cartouche
5885 @end deffn
5887 @node Type-coercion,,Function calls,Rvalues
5888 @anchor{topics/expressions type-coercion}@anchor{9c}
5889 @subsubsection Type-coercion
5892 @geindex gcc_jit_context_new_cast (C function)
5893 @anchor{topics/expressions gcc_jit_context_new_cast}@anchor{9d}
5894 @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)
5896 Given an rvalue of T, construct another rvalue of another type.
5898 Currently only a limited set of conversions are possible:
5900 @quotation
5903 @itemize *
5905 @item 
5906 int <-> float
5908 @item 
5909 int <-> bool
5911 @item 
5912 P*  <-> Q*, for pointer types P and Q
5913 @end itemize
5914 @end quotation
5915 @end deffn
5917 @node Lvalues,Working with pointers structs and unions,Rvalues,Expressions
5918 @anchor{topics/expressions lvalues}@anchor{9e}
5919 @subsection Lvalues
5922 @geindex gcc_jit_lvalue (C type)
5923 @anchor{topics/expressions gcc_jit_lvalue}@anchor{24}
5924 @deffn {C Type} gcc_jit_lvalue
5925 @end deffn
5927 An lvalue is something that can of the @emph{left}-hand side of an assignment:
5928 a storage area (such as a variable).  It is also usable as an rvalue,
5929 where the rvalue is computed by reading from the storage area.
5931 @geindex gcc_jit_lvalue_as_object (C function)
5932 @anchor{topics/expressions gcc_jit_lvalue_as_object}@anchor{9f}
5933 @deffn {C Function} gcc_jit_object *           gcc_jit_lvalue_as_object (gcc_jit_lvalue@w{ }*lvalue)
5935 Upcast an lvalue to be an object.
5936 @end deffn
5938 @geindex gcc_jit_lvalue_as_rvalue (C function)
5939 @anchor{topics/expressions gcc_jit_lvalue_as_rvalue}@anchor{a0}
5940 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_lvalue_as_rvalue (gcc_jit_lvalue@w{ }*lvalue)
5942 Upcast an lvalue to be an rvalue.
5943 @end deffn
5945 @geindex gcc_jit_lvalue_get_address (C function)
5946 @anchor{topics/expressions gcc_jit_lvalue_get_address}@anchor{a1}
5947 @deffn {C Function} gcc_jit_rvalue *           gcc_jit_lvalue_get_address (gcc_jit_lvalue@w{ }*lvalue, gcc_jit_location@w{ }*loc)
5949 Take the address of an lvalue; analogous to:
5951 @example
5952 &(EXPR)
5953 @end example
5955 @noindent
5957 in C.
5958 @end deffn
5960 @menu
5961 * Global variables:: 
5963 @end menu
5965 @node Global variables,,,Lvalues
5966 @anchor{topics/expressions global-variables}@anchor{a2}
5967 @subsubsection Global variables
5970 @geindex gcc_jit_context_new_global (C function)
5971 @anchor{topics/expressions gcc_jit_context_new_global}@anchor{a3}
5972 @deffn {C Function} gcc_jit_lvalue *           gcc_jit_context_new_global (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, gcc_jit_type@w{ }*type, const char@w{ }*name)
5974 Add a new global variable of the given type and name to the context.
5975 @end deffn
5977 @node Working with pointers structs and unions,,Lvalues,Expressions
5978 @anchor{topics/expressions working-with-pointers-structs-and-unions}@anchor{a4}
5979 @subsection Working with pointers, structs and unions
5982 @geindex gcc_jit_rvalue_dereference (C function)
5983 @anchor{topics/expressions gcc_jit_rvalue_dereference}@anchor{a5}
5984 @deffn {C Function} gcc_jit_lvalue *           gcc_jit_rvalue_dereference (gcc_jit_rvalue@w{ }*rvalue, gcc_jit_location@w{ }*loc)
5986 Given an rvalue of pointer type @code{T *}, dereferencing the pointer,
5987 getting an lvalue of type @code{T}.  Analogous to:
5989 @example
5990 *(EXPR)
5991 @end example
5993 @noindent
5995 in C.
5996 @end deffn
5998 Field access is provided separately for both lvalues and rvalues.
6000 @geindex gcc_jit_lvalue_access_field (C function)
6001 @anchor{topics/expressions gcc_jit_lvalue_access_field}@anchor{a6}
6002 @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)
6004 Given an lvalue of struct or union type, access the given field,
6005 getting an lvalue of the field's type.  Analogous to:
6007 @example
6008 (EXPR).field = ...;
6009 @end example
6011 @noindent
6013 in C.
6014 @end deffn
6016 @geindex gcc_jit_rvalue_access_field (C function)
6017 @anchor{topics/expressions gcc_jit_rvalue_access_field}@anchor{a7}
6018 @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)
6020 Given an rvalue of struct or union type, access the given field
6021 as an rvalue.  Analogous to:
6023 @example
6024 (EXPR).field
6025 @end example
6027 @noindent
6029 in C.
6030 @end deffn
6032 @geindex gcc_jit_rvalue_dereference_field (C function)
6033 @anchor{topics/expressions gcc_jit_rvalue_dereference_field}@anchor{a8}
6034 @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)
6036 Given an rvalue of pointer type @code{T *} where T is of struct or union
6037 type, access the given field as an lvalue.  Analogous to:
6039 @example
6040 (EXPR)->field
6041 @end example
6043 @noindent
6045 in C, itself equivalent to @code{(*EXPR).FIELD}.
6046 @end deffn
6048 @geindex gcc_jit_context_new_array_access (C function)
6049 @anchor{topics/expressions gcc_jit_context_new_array_access}@anchor{96}
6050 @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)
6052 Given an rvalue of pointer type @code{T *}, get at the element @cite{T} at
6053 the given index, using standard C array indexing rules i.e. each
6054 increment of @code{index} corresponds to @code{sizeof(T)} bytes.
6055 Analogous to:
6057 @example
6058 PTR[INDEX]
6059 @end example
6061 @noindent
6063 in C (or, indeed, to @code{PTR + INDEX}).
6064 @end deffn
6066 @c Copyright (C) 2014 Free Software Foundation, Inc.
6067 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6068 @c 
6069 @c This is free software: you can redistribute it and/or modify it
6070 @c under the terms of the GNU General Public License as published by
6071 @c the Free Software Foundation, either version 3 of the License, or
6072 @c (at your option) any later version.
6073 @c 
6074 @c This program is distributed in the hope that it will be useful, but
6075 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6076 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6077 @c General Public License for more details.
6078 @c 
6079 @c You should have received a copy of the GNU General Public License
6080 @c along with this program.  If not, see
6081 @c <http://www.gnu.org/licenses/>.
6083 @node Creating and using functions,Source Locations,Expressions,Topic Reference
6084 @anchor{topics/functions doc}@anchor{a9}@anchor{topics/functions creating-and-using-functions}@anchor{aa}
6085 @section Creating and using functions
6088 @menu
6089 * Params:: 
6090 * Functions:: 
6091 * Blocks:: 
6092 * Statements:: 
6094 @end menu
6096 @node Params,Functions,,Creating and using functions
6097 @anchor{topics/functions params}@anchor{ab}
6098 @subsection Params
6101 @geindex gcc_jit_param (C type)
6102 @anchor{topics/functions gcc_jit_param}@anchor{25}
6103 @deffn {C Type} gcc_jit_param
6105 A @cite{gcc_jit_param} represents a parameter to a function.
6106 @end deffn
6108 @geindex gcc_jit_context_new_param (C function)
6109 @anchor{topics/functions gcc_jit_context_new_param}@anchor{10}
6110 @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)
6112 In preparation for creating a function, create a new parameter of the
6113 given type and name.
6114 @end deffn
6116 Parameters are lvalues, and thus are also rvalues (and objects), so the
6117 following upcasts are available:
6119 @geindex gcc_jit_param_as_lvalue (C function)
6120 @anchor{topics/functions gcc_jit_param_as_lvalue}@anchor{ac}
6121 @deffn {C Function} gcc_jit_lvalue *            gcc_jit_param_as_lvalue (gcc_jit_param@w{ }*param)
6123 Upcasting from param to lvalue.
6124 @end deffn
6126 @geindex gcc_jit_param_as_rvalue (C function)
6127 @anchor{topics/functions gcc_jit_param_as_rvalue}@anchor{ad}
6128 @deffn {C Function} gcc_jit_rvalue *            gcc_jit_param_as_rvalue (gcc_jit_param@w{ }*param)
6130 Upcasting from param to rvalue.
6131 @end deffn
6133 @geindex gcc_jit_param_as_object (C function)
6134 @anchor{topics/functions gcc_jit_param_as_object}@anchor{ae}
6135 @deffn {C Function} gcc_jit_object *            gcc_jit_param_as_object (gcc_jit_param@w{ }*param)
6137 Upcasting from param to object.
6138 @end deffn
6140 @node Functions,Blocks,Params,Creating and using functions
6141 @anchor{topics/functions functions}@anchor{af}
6142 @subsection Functions
6145 @geindex gcc_jit_function (C type)
6146 @anchor{topics/functions gcc_jit_function}@anchor{29}
6147 @deffn {C Type} gcc_jit_function
6149 A @cite{gcc_jit_function} represents a function - either one that we're
6150 creating ourselves, or one that we're referencing.
6151 @end deffn
6153 @geindex gcc_jit_context_new_function (C function)
6154 @anchor{topics/functions gcc_jit_context_new_function}@anchor{11}
6155 @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)
6157 Create a gcc_jit_function with the given name and parameters.
6159 @geindex gcc_jit_function_kind (C type)
6160 @anchor{topics/functions gcc_jit_function_kind}@anchor{b0}
6161 @deffn {C Type} enum gcc_jit_function_kind
6162 @end deffn
6164 This enum controls the kind of function created, and has the following
6165 values:
6167 @quotation
6169 @geindex GCC_JIT_FUNCTION_EXPORTED (C macro)
6170 @anchor{topics/functions GCC_JIT_FUNCTION_EXPORTED}@anchor{b1}
6171 @deffn {C Macro} GCC_JIT_FUNCTION_EXPORTED
6173 Function is defined by the client code and visible
6174 by name outside of the JIT.
6176 This value is required if you want to extract machine code
6177 for this function from a @pxref{16,,gcc_jit_result} via
6178 @pxref{17,,gcc_jit_result_get_code()}.
6179 @end deffn
6181 @geindex GCC_JIT_FUNCTION_INTERNAL (C macro)
6182 @anchor{topics/functions GCC_JIT_FUNCTION_INTERNAL}@anchor{b2}
6183 @deffn {C Macro} GCC_JIT_FUNCTION_INTERNAL
6185 Function is defined by the client code, but is invisible
6186 outside of the JIT.  Analogous to a "static" function.
6187 @end deffn
6189 @geindex GCC_JIT_FUNCTION_IMPORTED (C macro)
6190 @anchor{topics/functions GCC_JIT_FUNCTION_IMPORTED}@anchor{b3}
6191 @deffn {C Macro} GCC_JIT_FUNCTION_IMPORTED
6193 Function is not defined by the client code; we're merely
6194 referring to it.  Analogous to using an "extern" function from a
6195 header file.
6196 @end deffn
6198 @geindex GCC_JIT_FUNCTION_ALWAYS_INLINE (C macro)
6199 @anchor{topics/functions GCC_JIT_FUNCTION_ALWAYS_INLINE}@anchor{b4}
6200 @deffn {C Macro} GCC_JIT_FUNCTION_ALWAYS_INLINE
6202 Function is only ever inlined into other functions, and is
6203 invisible outside of the JIT.
6205 Analogous to prefixing with @code{inline} and adding
6206 @code{__attribute__((always_inline))}
6208 Inlining will only occur when the optimization level is
6209 above 0; when optimization is off, this is essentially the
6210 same as GCC_JIT_FUNCTION_INTERNAL.
6211 @end deffn
6212 @end quotation
6213 @end deffn
6215 @geindex gcc_jit_context_get_builtin_function (C function)
6216 @anchor{topics/functions gcc_jit_context_get_builtin_function}@anchor{b5}
6217 @deffn {C Function} gcc_jit_function *gcc_jit_context_get_builtin_function (gcc_jit_context@w{ }*ctxt, const char@w{ }*name)
6218 @end deffn
6220 @geindex gcc_jit_function_as_object (C function)
6221 @anchor{topics/functions gcc_jit_function_as_object}@anchor{b6}
6222 @deffn {C Function} gcc_jit_object *           gcc_jit_function_as_object (gcc_jit_function@w{ }*func)
6224 Upcasting from function to object.
6225 @end deffn
6227 @geindex gcc_jit_function_get_param (C function)
6228 @anchor{topics/functions gcc_jit_function_get_param}@anchor{b7}
6229 @deffn {C Function} gcc_jit_param *            gcc_jit_function_get_param (gcc_jit_function@w{ }*func, int@w{ }index)
6231 Get the param of the given index (0-based).
6232 @end deffn
6234 @geindex gcc_jit_function_dump_to_dot (C function)
6235 @anchor{topics/functions gcc_jit_function_dump_to_dot}@anchor{33}
6236 @deffn {C Function} void             gcc_jit_function_dump_to_dot (gcc_jit_function@w{ }*func, const char@w{ }*path)
6238 Emit the function in graphviz format to the given path.
6239 @end deffn
6241 @geindex gcc_jit_function_new_local (C function)
6242 @anchor{topics/functions gcc_jit_function_new_local}@anchor{26}
6243 @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)
6245 Create a new local variable within the function, of the given type and
6246 name.
6247 @end deffn
6249 @node Blocks,Statements,Functions,Creating and using functions
6250 @anchor{topics/functions blocks}@anchor{b8}
6251 @subsection Blocks
6254 @geindex gcc_jit_block (C type)
6255 @anchor{topics/functions gcc_jit_block}@anchor{28}
6256 @deffn {C Type} gcc_jit_block
6258 A @cite{gcc_jit_block} represents a basic block within a function  i.e. a
6259 sequence of statements with a single entry point and a single exit
6260 point.
6262 The first basic block that you create within a function will
6263 be the entrypoint.
6265 Each basic block that you create within a function must be
6266 terminated, either with a conditional, a jump, or a return.
6268 It's legal to have multiple basic blocks that return within
6269 one function.
6270 @end deffn
6272 @geindex gcc_jit_function_new_block (C function)
6273 @anchor{topics/functions gcc_jit_function_new_block}@anchor{b9}
6274 @deffn {C Function} gcc_jit_block *            gcc_jit_function_new_block (gcc_jit_function@w{ }*func, const char@w{ }*name)
6276 Create a basic block of the given name.  The name may be NULL, but
6277 providing meaningful names is often helpful when debugging: it may
6278 show up in dumps of the internal representation, and in error
6279 messages.
6280 @end deffn
6282 @geindex gcc_jit_block_as_object (C function)
6283 @anchor{topics/functions gcc_jit_block_as_object}@anchor{ba}
6284 @deffn {C Function} gcc_jit_object *            gcc_jit_block_as_object (gcc_jit_block@w{ }*block)
6286 Upcast from block to object.
6287 @end deffn
6289 @geindex gcc_jit_block_get_function (C function)
6290 @anchor{topics/functions gcc_jit_block_get_function}@anchor{bb}
6291 @deffn {C Function} gcc_jit_function *            gcc_jit_block_get_function (gcc_jit_block@w{ }*block)
6293 Which function is this block within?
6294 @end deffn
6296 @node Statements,,Blocks,Creating and using functions
6297 @anchor{topics/functions statements}@anchor{bc}
6298 @subsection Statements
6301 @geindex gcc_jit_block_add_eval (C function)
6302 @anchor{topics/functions gcc_jit_block_add_eval}@anchor{9b}
6303 @deffn {C Function} void           gcc_jit_block_add_eval (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, gcc_jit_rvalue@w{ }*rvalue)
6305 Add evaluation of an rvalue, discarding the result
6306 (e.g. a function call that "returns" void).
6308 This is equivalent to this C code:
6310 @example
6311 (void)expression;
6312 @end example
6314 @noindent
6315 @end deffn
6317 @geindex gcc_jit_block_add_assignment (C function)
6318 @anchor{topics/functions gcc_jit_block_add_assignment}@anchor{2a}
6319 @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)
6321 Add evaluation of an rvalue, assigning the result to the given
6322 lvalue.
6324 This is roughly equivalent to this C code:
6326 @example
6327 lvalue = rvalue;
6328 @end example
6330 @noindent
6331 @end deffn
6333 @geindex gcc_jit_block_add_assignment_op (C function)
6334 @anchor{topics/functions gcc_jit_block_add_assignment_op}@anchor{2e}
6335 @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)
6337 Add evaluation of an rvalue, using the result to modify an
6338 lvalue.
6340 This is analogous to "+=" and friends:
6342 @example
6343 lvalue += rvalue;
6344 lvalue *= rvalue;
6345 lvalue /= rvalue;
6346 @end example
6348 @noindent
6350 etc.  For example:
6352 @example
6353 /* "i++" */
6354 gcc_jit_block_add_assignment_op (
6355   loop_body, NULL,
6356   i,
6357   GCC_JIT_BINARY_OP_PLUS,
6358   gcc_jit_context_one (ctxt, int_type));
6359 @end example
6361 @noindent
6362 @end deffn
6364 @geindex gcc_jit_block_add_comment (C function)
6365 @anchor{topics/functions gcc_jit_block_add_comment}@anchor{3d}
6366 @deffn {C Function} void           gcc_jit_block_add_comment (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, const char@w{ }*text)
6368 Add a no-op textual comment to the internal representation of the
6369 code.  It will be optimized away, but will be visible in the dumps
6370 seen via @pxref{5e,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE}
6371 and @pxref{1c,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE},
6372 and thus may be of use when debugging how your project's internal
6373 representation gets converted to the libgccjit IR.
6374 @end deffn
6376 @geindex gcc_jit_block_end_with_conditional (C function)
6377 @anchor{topics/functions gcc_jit_block_end_with_conditional}@anchor{2d}
6378 @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)
6380 Terminate a block by adding evaluation of an rvalue, branching on the
6381 result to the appropriate successor block.
6383 This is roughly equivalent to this C code:
6385 @example
6386 if (boolval)
6387   goto on_true;
6388 else
6389   goto on_false;
6390 @end example
6392 @noindent
6394 block, boolval, on_true, and on_false must be non-NULL.
6395 @end deffn
6397 @geindex gcc_jit_block_end_with_jump (C function)
6398 @anchor{topics/functions gcc_jit_block_end_with_jump}@anchor{bd}
6399 @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)
6401 Terminate a block by adding a jump to the given target block.
6403 This is roughly equivalent to this C code:
6405 @example
6406 goto target;
6407 @end example
6409 @noindent
6410 @end deffn
6412 @geindex gcc_jit_block_end_with_return (C function)
6413 @anchor{topics/functions gcc_jit_block_end_with_return}@anchor{be}
6414 @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)
6416 Terminate a block by adding evaluation of an rvalue, returning the value.
6418 This is roughly equivalent to this C code:
6420 @example
6421 return expression;
6422 @end example
6424 @noindent
6425 @end deffn
6427 @geindex gcc_jit_block_end_with_void_return (C function)
6428 @anchor{topics/functions gcc_jit_block_end_with_void_return}@anchor{bf}
6429 @deffn {C Function} void           gcc_jit_block_end_with_void_return (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc)
6431 Terminate a block by adding a valueless return, for use within a function
6432 with "void" return type.
6434 This is equivalent to this C code:
6436 @example
6437 return;
6438 @end example
6440 @noindent
6441 @end deffn
6443 @c Copyright (C) 2014 Free Software Foundation, Inc.
6444 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6445 @c 
6446 @c This is free software: you can redistribute it and/or modify it
6447 @c under the terms of the GNU General Public License as published by
6448 @c the Free Software Foundation, either version 3 of the License, or
6449 @c (at your option) any later version.
6450 @c 
6451 @c This program is distributed in the hope that it will be useful, but
6452 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6453 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6454 @c General Public License for more details.
6455 @c 
6456 @c You should have received a copy of the GNU General Public License
6457 @c along with this program.  If not, see
6458 @c <http://www.gnu.org/licenses/>.
6460 @node Source Locations,Compilation results,Creating and using functions,Topic Reference
6461 @anchor{topics/locations source-locations}@anchor{c0}@anchor{topics/locations doc}@anchor{c1}
6462 @section Source Locations
6465 @geindex gcc_jit_location (C type)
6466 @anchor{topics/locations gcc_jit_location}@anchor{3b}
6467 @deffn {C Type} gcc_jit_location
6469 A @cite{gcc_jit_location} encapsulates a source code location, so that
6470 you can (optionally) associate locations in your language with
6471 statements in the JIT-compiled code, allowing the debugger to
6472 single-step through your language.
6474 @cite{gcc_jit_location} instances are optional: you can always pass NULL to
6475 any API entrypoint accepting one.
6477 You can construct them using @pxref{41,,gcc_jit_context_new_location()}.
6479 You need to enable @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} on the
6480 @pxref{8,,gcc_jit_context} for these locations to actually be usable by
6481 the debugger:
6483 @example
6484 gcc_jit_context_set_bool_option (
6485   ctxt,
6486   GCC_JIT_BOOL_OPTION_DEBUGINFO,
6487   1);
6488 @end example
6490 @noindent
6491 @end deffn
6493 @geindex gcc_jit_context_new_location (C function)
6494 @anchor{topics/locations gcc_jit_context_new_location}@anchor{41}
6495 @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)
6497 Create a @cite{gcc_jit_location} instance representing the given source
6498 location.
6499 @end deffn
6501 @menu
6502 * Faking it:: 
6504 @end menu
6506 @node Faking it,,,Source Locations
6507 @anchor{topics/locations faking-it}@anchor{c2}
6508 @subsection Faking it
6511 If you don't have source code for your internal representation, but need
6512 to debug, you can generate a C-like representation of the functions in
6513 your context using @pxref{53,,gcc_jit_context_dump_to_file()}:
6515 @example
6516 gcc_jit_context_dump_to_file (ctxt, "/tmp/something.c",
6517                               1 /* update_locations */);
6518 @end example
6520 @noindent
6522 This will dump C-like code to the given path.  If the @cite{update_locations}
6523 argument is true, this will also set up @cite{gcc_jit_location} information
6524 throughout the context, pointing at the dump file as if it were a source
6525 file, giving you @emph{something} you can step through in the debugger.
6527 @c Copyright (C) 2014 Free Software Foundation, Inc.
6528 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6529 @c 
6530 @c This is free software: you can redistribute it and/or modify it
6531 @c under the terms of the GNU General Public License as published by
6532 @c the Free Software Foundation, either version 3 of the License, or
6533 @c (at your option) any later version.
6534 @c 
6535 @c This program is distributed in the hope that it will be useful, but
6536 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6537 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6538 @c General Public License for more details.
6539 @c 
6540 @c You should have received a copy of the GNU General Public License
6541 @c along with this program.  If not, see
6542 @c <http://www.gnu.org/licenses/>.
6544 @node Compilation results,,Source Locations,Topic Reference
6545 @anchor{topics/results compilation-results}@anchor{c3}@anchor{topics/results doc}@anchor{c4}
6546 @section Compilation results
6549 @geindex gcc_jit_result (C type)
6550 @anchor{topics/results gcc_jit_result}@anchor{16}
6551 @deffn {C Type} gcc_jit_result
6553 A @cite{gcc_jit_result} encapsulates the result of compiling a context,
6554 and the lifetimes of any machine code functions that are
6555 returned.
6556 @end deffn
6558 @geindex gcc_jit_context_compile (C function)
6559 @anchor{topics/results gcc_jit_context_compile}@anchor{15}
6560 @deffn {C Function} gcc_jit_result *           gcc_jit_context_compile (gcc_jit_context@w{ }*ctxt)
6562 This calls into GCC and builds the code, returning a
6563 @cite{gcc_jit_result *}.
6564 @end deffn
6566 @geindex gcc_jit_result_get_code (C function)
6567 @anchor{topics/results gcc_jit_result_get_code}@anchor{17}
6568 @deffn {C Function} void *           gcc_jit_result_get_code (gcc_jit_result@w{ }*result, const char@w{ }*funcname)
6570 Locate a given function within the built machine code.
6572 Functions are looked up by name.  For this to succeed, a function
6573 with a name matching @cite{funcname} must have been created on
6574 @cite{result}'s context (or a parent context) via a call to
6575 @pxref{11,,gcc_jit_context_new_function()} with @cite{kind}
6576 @pxref{b1,,GCC_JIT_FUNCTION_EXPORTED}:
6578 @example
6579 gcc_jit_context_new_function (ctxt,
6580                               any_location, /* or NULL */
6581                               /* Required for func to be visible to
6582                                  gcc_jit_result_get_code: */
6583                               GCC_JIT_FUNCTION_EXPORTED,
6584                               any_return_type,
6585                               /* Must string-compare equal: */
6586                               funcname,
6587                               /* etc */);
6588 @end example
6590 @noindent
6592 If such a function is not found (or @cite{result} or @cite{funcname} are
6593 @code{NULL}), an error message will be emitted on stderr and
6594 @code{NULL} will be returned.
6596 If the function is found, the result will need to be cast to a
6597 function pointer of the correct type before it can be called.
6599 Note that the resulting machine code becomes invalid after
6600 @pxref{39,,gcc_jit_result_release()} is called on the
6601 @cite{gcc_jit_result *}; attempting to call it after that may lead
6602 to a segmentation fault.
6603 @end deffn
6605 @geindex gcc_jit_result_release (C function)
6606 @anchor{topics/results gcc_jit_result_release}@anchor{39}
6607 @deffn {C Function} void           gcc_jit_result_release (gcc_jit_result@w{ }*result)
6609 Once we're done with the code, this unloads the built .so file.
6610 This cleans up the result; after calling this, it's no longer
6611 valid to use the result, or any code that was obtained by calling
6612 @pxref{17,,gcc_jit_result_get_code()} on it.
6613 @end deffn
6615 @c Copyright (C) 2014 Free Software Foundation, Inc.
6616 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6617 @c 
6618 @c This is free software: you can redistribute it and/or modify it
6619 @c under the terms of the GNU General Public License as published by
6620 @c the Free Software Foundation, either version 3 of the License, or
6621 @c (at your option) any later version.
6622 @c 
6623 @c This program is distributed in the hope that it will be useful, but
6624 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6625 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6626 @c General Public License for more details.
6627 @c 
6628 @c You should have received a copy of the GNU General Public License
6629 @c along with this program.  If not, see
6630 @c <http://www.gnu.org/licenses/>.
6632 @node C++ bindings for libgccjit,Internals,Topic Reference,Top
6633 @anchor{cp/index c-bindings-for-libgccjit}@anchor{c5}@anchor{cp/index doc}@anchor{c6}
6634 @chapter C++ bindings for libgccjit
6637 This document describes the C++ bindings to
6638 libgccjit@footnote{http://gcc.gnu.org/wiki/JIT}, an API for embedding GCC
6639 inside programs and libraries.
6641 The C++ bindings consist of a single header file @code{libgccjit++.h}.
6643 This is a collection of "thin" wrapper classes around the C API.
6644 Everything is an inline function, implemented in terms of the C API,
6645 so there is nothing extra to link against.
6647 Note that libgccjit is currently of "Alpha" quality;
6648 the APIs are not yet set in stone, and they shouldn't be used in
6649 production yet.
6651 Contents:
6653 @c Copyright (C) 2014 Free Software Foundation, Inc.
6654 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6655 @c 
6656 @c This is free software: you can redistribute it and/or modify it
6657 @c under the terms of the GNU General Public License as published by
6658 @c the Free Software Foundation, either version 3 of the License, or
6659 @c (at your option) any later version.
6660 @c 
6661 @c This program is distributed in the hope that it will be useful, but
6662 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6663 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6664 @c General Public License for more details.
6665 @c 
6666 @c You should have received a copy of the GNU General Public License
6667 @c along with this program.  If not, see
6668 @c <http://www.gnu.org/licenses/>.
6670 @menu
6671 * Tutorial: Tutorial<2>. 
6672 * Topic Reference: Topic Reference<2>. 
6674 Tutorial
6676 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world"<2>. 
6677 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function<2>. 
6678 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables<2>. 
6679 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>. 
6681 Tutorial part 2: Creating a trivial machine code function
6683 * Options: Options<3>. 
6684 * Full example: Full example<3>. 
6686 Tutorial part 3: Loops and variables
6688 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues<2>. 
6689 * Control flow: Control flow<2>. 
6690 * Visualizing the control flow graph: Visualizing the control flow graph<2>. 
6691 * Full example: Full example<4>. 
6693 Tutorial part 4: Adding JIT-compilation to a toy interpreter
6695 * Our toy interpreter: Our toy interpreter<2>. 
6696 * Compiling to machine code: Compiling to machine code<2>. 
6697 * Setting things up: Setting things up<2>. 
6698 * Populating the function: Populating the function<2>. 
6699 * Verifying the control flow graph: Verifying the control flow graph<2>. 
6700 * Compiling the context: Compiling the context<2>. 
6701 * Single-stepping through the generated code: Single-stepping through the generated code<2>. 
6702 * Examining the generated code: Examining the generated code<2>. 
6703 * Putting it all together: Putting it all together<2>. 
6704 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?<2>. 
6706 Behind the curtain: How does our code get optimized?
6708 * Optimizing away stack manipulation: Optimizing away stack manipulation<2>. 
6709 * Elimination of tail recursion: Elimination of tail recursion<2>. 
6711 Topic Reference
6713 * Compilation contexts: Compilation contexts<2>. 
6714 * Objects: Objects<2>. 
6715 * Types: Types<2>. 
6716 * Expressions: Expressions<2>. 
6717 * Creating and using functions: Creating and using functions<2>. 
6718 * Source Locations: Source Locations<2>. 
6719 * Compilation results: Compilation results<2>. 
6721 Compilation contexts
6723 * Lifetime-management: Lifetime-management<2>. 
6724 * Thread-safety: Thread-safety<2>. 
6725 * Error-handling: Error-handling<3>. 
6726 * Debugging: Debugging<2>. 
6727 * Options: Options<4>. 
6729 Options
6731 * String Options: String Options<2>. 
6732 * Boolean options: Boolean options<2>. 
6733 * Integer options: Integer options<2>. 
6735 Types
6737 * Standard types: Standard types<2>. 
6738 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile<2>. 
6739 * Structures and unions: Structures and unions<2>. 
6741 Expressions
6743 * Rvalues: Rvalues<2>. 
6744 * Lvalues: Lvalues<2>. 
6745 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions<2>. 
6747 Rvalues
6749 * Simple expressions: Simple expressions<2>. 
6750 * Unary Operations: Unary Operations<2>. 
6751 * Binary Operations: Binary Operations<2>. 
6752 * Comparisons: Comparisons<2>. 
6753 * Function calls: Function calls<2>. 
6754 * Type-coercion: Type-coercion<2>. 
6756 Lvalues
6758 * Global variables: Global variables<2>. 
6760 Creating and using functions
6762 * Params: Params<2>. 
6763 * Functions: Functions<2>. 
6764 * Blocks: Blocks<2>. 
6765 * Statements: Statements<2>. 
6767 Source Locations
6769 * Faking it: Faking it<2>. 
6771 @end menu
6774 @node Tutorial<2>,Topic Reference<2>,,C++ bindings for libgccjit
6775 @anchor{cp/intro/index doc}@anchor{c7}@anchor{cp/intro/index tutorial}@anchor{c8}
6776 @section Tutorial
6779 @c Copyright (C) 2014 Free Software Foundation, Inc.
6780 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6781 @c 
6782 @c This is free software: you can redistribute it and/or modify it
6783 @c under the terms of the GNU General Public License as published by
6784 @c the Free Software Foundation, either version 3 of the License, or
6785 @c (at your option) any later version.
6786 @c 
6787 @c This program is distributed in the hope that it will be useful, but
6788 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6789 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6790 @c General Public License for more details.
6791 @c 
6792 @c You should have received a copy of the GNU General Public License
6793 @c along with this program.  If not, see
6794 @c <http://www.gnu.org/licenses/>.
6796 @menu
6797 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world"<2>. 
6798 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function<2>. 
6799 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables<2>. 
6800 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>. 
6802 @end menu
6804 @node Tutorial part 1 "Hello world"<2>,Tutorial part 2 Creating a trivial machine code function<2>,,Tutorial<2>
6805 @anchor{cp/intro/tutorial01 doc}@anchor{c9}@anchor{cp/intro/tutorial01 tutorial-part-1-hello-world}@anchor{ca}
6806 @subsection Tutorial part 1: "Hello world"
6809 Before we look at the details of the API, let's look at building and
6810 running programs that use the library.
6812 Here's a toy "hello world" program that uses the library's C++ API to
6813 synthesize a call to @cite{printf} and uses it to write a message to stdout.
6815 Don't worry about the content of the program for now; we'll cover
6816 the details in later parts of this tutorial.
6818 @quotation
6820 @example
6821 /* Smoketest example for libgccjit.so C++ API
6822    Copyright (C) 2014 Free Software Foundation, Inc.
6824 This file is part of GCC.
6826 GCC is free software; you can redistribute it and/or modify it
6827 under the terms of the GNU General Public License as published by
6828 the Free Software Foundation; either version 3, or (at your option)
6829 any later version.
6831 GCC is distributed in the hope that it will be useful, but
6832 WITHOUT ANY WARRANTY; without even the implied warranty of
6833 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6834 General Public License for more details.
6836 You should have received a copy of the GNU General Public License
6837 along with GCC; see the file COPYING3.  If not see
6838 <http://www.gnu.org/licenses/>.  */
6840 #include <libgccjit++.h>
6842 #include <stdlib.h>
6843 #include <stdio.h>
6845 static void
6846 create_code (gccjit::context ctxt)
6848   /* Let's try to inject the equivalent of this C code:
6849      void
6850      greet (const char *name)
6851      @{
6852         printf ("hello %s\n", name);
6853      @}
6854   */
6855   gccjit::type void_type = ctxt.get_type (GCC_JIT_TYPE_VOID);
6856   gccjit::type const_char_ptr_type =
6857     ctxt.get_type (GCC_JIT_TYPE_CONST_CHAR_PTR);
6858   gccjit::param param_name =
6859     ctxt.new_param (const_char_ptr_type, "name");
6860   std::vector<gccjit::param> func_params;
6861   func_params.push_back (param_name);
6862   gccjit::function func =
6863     ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
6864                        void_type,
6865                        "greet",
6866                        func_params, 0);
6868   gccjit::param param_format =
6869     ctxt.new_param (const_char_ptr_type, "format");
6870   std::vector<gccjit::param> printf_params;
6871   printf_params.push_back (param_format);
6872   gccjit::function printf_func =
6873     ctxt.new_function (GCC_JIT_FUNCTION_IMPORTED,
6874                        ctxt.get_type (GCC_JIT_TYPE_INT),
6875                        "printf",
6876                        printf_params, 1);
6878   gccjit::block block = func.new_block ();
6879   block.add_eval (ctxt.new_call (printf_func,
6880                                  ctxt.new_rvalue ("hello %s\n"),
6881                                  param_name));
6882   block.end_with_return ();
6886 main (int argc, char **argv)
6888   gccjit::context ctxt;
6889   gcc_jit_result *result;
6891   /* Get a "context" object for working with the library.  */
6892   ctxt = gccjit::context::acquire ();
6894   /* Set some options on the context.
6895      Turn this on to see the code being generated, in assembler form.  */
6896   ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE, 0);
6898   /* Populate the context.  */
6899   create_code (ctxt);
6901   /* Compile the code.  */
6902   result = ctxt.compile ();
6903   if (!result)
6904     @{
6905       fprintf (stderr, "NULL result");
6906       exit (1);
6907     @}
6909   ctxt.release ();
6911   /* Extract the generated code from "result".  */
6912   typedef void (*fn_type) (const char *);
6913   fn_type greet =
6914     (fn_type)gcc_jit_result_get_code (result, "greet");
6915   if (!greet)
6916     @{
6917       fprintf (stderr, "NULL greet");
6918       exit (1);
6919     @}
6921   /* Now call the generated function: */
6922   greet ("world");
6923   fflush (stdout);
6925   gcc_jit_result_release (result);
6926   return 0;
6929 @end example
6931 @noindent
6932 @end quotation
6934 Copy the above to @cite{tut01-hello-world.cc}.
6936 Assuming you have the jit library installed, build the test program
6937 using:
6939 @example
6940 $ gcc \
6941     tut01-hello-world.cc \
6942     -o tut01-hello-world \
6943     -lgccjit
6944 @end example
6946 @noindent
6948 You should then be able to run the built program:
6950 @example
6951 $ ./tut01-hello-world
6952 hello world
6953 @end example
6955 @noindent
6957 @c Copyright (C) 2014 Free Software Foundation, Inc.
6958 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6959 @c 
6960 @c This is free software: you can redistribute it and/or modify it
6961 @c under the terms of the GNU General Public License as published by
6962 @c the Free Software Foundation, either version 3 of the License, or
6963 @c (at your option) any later version.
6964 @c 
6965 @c This program is distributed in the hope that it will be useful, but
6966 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6967 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
6968 @c General Public License for more details.
6969 @c 
6970 @c You should have received a copy of the GNU General Public License
6971 @c along with this program.  If not, see
6972 @c <http://www.gnu.org/licenses/>.
6974 @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>
6975 @anchor{cp/intro/tutorial02 doc}@anchor{cb}@anchor{cp/intro/tutorial02 tutorial-part-2-creating-a-trivial-machine-code-function}@anchor{cc}
6976 @subsection Tutorial part 2: Creating a trivial machine code function
6979 Consider this C function:
6981 @example
6982 int square (int i)
6984   return i * i;
6986 @end example
6988 @noindent
6990 How can we construct this at run-time using libgccjit's C++ API?
6992 First we need to include the relevant header:
6994 @example
6995 #include <libgccjit++.h>
6996 @end example
6998 @noindent
7000 All state associated with compilation is associated with a
7001 @code{gccjit::context}, which is a thin C++ wrapper around the C API's
7002 @pxref{8,,gcc_jit_context *}.
7004 Create one using @pxref{cd,,gccjit;;context;;acquire()}:
7006 @example
7007 gccjit::context ctxt;
7008 ctxt = gccjit::context::acquire ();
7009 @end example
7011 @noindent
7013 The JIT library has a system of types.  It is statically-typed: every
7014 expression is of a specific type, fixed at compile-time.  In our example,
7015 all of the expressions are of the C @cite{int} type, so let's obtain this from
7016 the context, as a @code{gccjit::type}, using
7017 @pxref{ce,,gccjit;;context;;get_type()}:
7019 @example
7020 gccjit::type int_type = ctxt.get_type (GCC_JIT_TYPE_INT);
7021 @end example
7023 @noindent
7025 @code{gccjit::type} is an example of a "contextual" object: every
7026 entity in the API is associated with a @code{gccjit::context}.
7028 Memory management is easy: all such "contextual" objects are automatically
7029 cleaned up for you when the context is released, using
7030 @pxref{cf,,gccjit;;context;;release()}:
7032 @example
7033 ctxt.release ();
7034 @end example
7036 @noindent
7038 so you don't need to manually track and cleanup all objects, just the
7039 contexts.
7041 All of the C++ classes in the API are thin wrappers around pointers to
7042 types in the C API.
7044 The C++ class hierarchy within the @code{gccjit} namespace looks like this:
7046 @example
7047 +- object
7048     +- location
7049     +- type
7050        +- struct
7051     +- field
7052     +- function
7053     +- block
7054     +- rvalue
7055         +- lvalue
7056            +- param
7057 @end example
7059 @noindent
7061 One thing you can do with a @code{gccjit::object} is
7062 to ask it for a human-readable description as a @code{std::string}, using
7063 @pxref{d0,,gccjit;;object;;get_debug_string()}:
7065 @example
7066 printf ("obj: %s\n", obj.get_debug_string ().c_str ());
7067 @end example
7069 @noindent
7071 giving this text on stdout:
7073 @example
7074 obj: int
7075 @end example
7077 @noindent
7079 This is invaluable when debugging.
7081 Let's create the function.  To do so, we first need to construct
7082 its single parameter, specifying its type and giving it a name,
7083 using @pxref{d1,,gccjit;;context;;new_param()}:
7085 @example
7086 gccjit::param param_i = ctxt.new_param (int_type, "i");
7087 @end example
7089 @noindent
7091 and we can then make a vector of all of the params of the function,
7092 in this case just one:
7094 @example
7095 std::vector<gccjit::param> params;
7096 params.push_back (param_i);
7097 @end example
7099 @noindent
7101 Now we can create the function, using
7102 @code{gccjit::context::new_function()}:
7104 @example
7105 gccjit::function func =
7106   ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
7107                      int_type,
7108                      "square",
7109                      params,
7110                      0);
7111 @end example
7113 @noindent
7115 To define the code within the function, we must create basic blocks
7116 containing statements.
7118 Every basic block contains a list of statements, eventually terminated
7119 by a statement that either returns, or jumps to another basic block.
7121 Our function has no control-flow, so we just need one basic block:
7123 @example
7124 gccjit::block block = func.new_block ();
7125 @end example
7127 @noindent
7129 Our basic block is relatively simple: it immediately terminates by
7130 returning the value of an expression.
7132 We can build the expression using @pxref{d2,,gccjit;;context;;new_binary_op()}:
7134 @example
7135 gccjit::rvalue expr =
7136   ctxt.new_binary_op (
7137     GCC_JIT_BINARY_OP_MULT, int_type,
7138     param_i, param_i);
7139 @end example
7141 @noindent
7143 A @code{gccjit::rvalue} is another example of a
7144 @code{gccjit::object} subclass.  As before, we can print it with
7145 @pxref{d0,,gccjit;;object;;get_debug_string()}.
7147 @example
7148 printf ("expr: %s\n", expr.get_debug_string ().c_str ());
7149 @end example
7151 @noindent
7153 giving this output:
7155 @example
7156 expr: i * i
7157 @end example
7159 @noindent
7161 Note that @code{gccjit::rvalue} provides numerous overloaded operators
7162 which can be used to dramatically reduce the amount of typing needed.
7163 We can build the above binary operation more directly with this one-liner:
7165 @example
7166 gccjit::rvalue expr = param_i * param_i;
7167 @end example
7169 @noindent
7171 Creating the expression in itself doesn't do anything; we have to add
7172 this expression to a statement within the block.  In this case, we use it
7173 to build a return statement, which terminates the basic block:
7175 @example
7176 block.end_with_return (expr);
7177 @end example
7179 @noindent
7181 OK, we've populated the context.  We can now compile it using
7182 @pxref{d3,,gccjit;;context;;compile()}:
7184 @example
7185 gcc_jit_result *result;
7186 result = ctxt.compile ();
7187 @end example
7189 @noindent
7191 and get a @pxref{16,,gcc_jit_result *}.
7193 We can now use @pxref{17,,gcc_jit_result_get_code()} to look up a specific
7194 machine code routine within the result, in this case, the function we
7195 created above.
7197 @example
7198 void *fn_ptr = gcc_jit_result_get_code (result, "square");
7199 if (!fn_ptr)
7200   @{
7201     fprintf (stderr, "NULL fn_ptr");
7202     goto error;
7203   @}
7204 @end example
7206 @noindent
7208 We can now cast the pointer to an appropriate function pointer type, and
7209 then call it:
7211 @example
7212 typedef int (*fn_type) (int);
7213 fn_type square = (fn_type)fn_ptr;
7214 printf ("result: %d", square (5));
7215 @end example
7217 @noindent
7219 @example
7220 result: 25
7221 @end example
7223 @noindent
7225 @menu
7226 * Options: Options<3>. 
7227 * Full example: Full example<3>. 
7229 @end menu
7231 @node Options<3>,Full example<3>,,Tutorial part 2 Creating a trivial machine code function<2>
7232 @anchor{cp/intro/tutorial02 options}@anchor{d4}
7233 @subsubsection Options
7236 To get more information on what's going on, you can set debugging flags
7237 on the context using @pxref{d5,,gccjit;;context;;set_bool_option()}.
7239 @c (I'm deliberately not mentioning
7240 @c :c:macro:`GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE` here since I think
7241 @c it's probably more of use to implementors than to users)
7243 Setting @pxref{1c,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE} will dump a
7244 C-like representation to stderr when you compile (GCC's "GIMPLE"
7245 representation):
7247 @example
7248 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE, 1);
7249 result = ctxt.compile ();
7250 @end example
7252 @noindent
7254 @example
7255 square (signed int i)
7257   signed int D.260;
7259   entry:
7260   D.260 = i * i;
7261   return D.260;
7263 @end example
7265 @noindent
7267 We can see the generated machine code in assembler form (on stderr) by
7268 setting @pxref{1d,,GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE} on the context
7269 before compiling:
7271 @example
7272 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE, 1);
7273 result = ctxt.compile ();
7274 @end example
7276 @noindent
7278 @example
7279       .file   "fake.c"
7280       .text
7281       .globl  square
7282       .type   square, @@function
7283 square:
7284 .LFB6:
7285       .cfi_startproc
7286       pushq   %rbp
7287       .cfi_def_cfa_offset 16
7288       .cfi_offset 6, -16
7289       movq    %rsp, %rbp
7290       .cfi_def_cfa_register 6
7291       movl    %edi, -4(%rbp)
7292 .L14:
7293       movl    -4(%rbp), %eax
7294       imull   -4(%rbp), %eax
7295       popq    %rbp
7296       .cfi_def_cfa 7, 8
7297       ret
7298       .cfi_endproc
7299 .LFE6:
7300       .size   square, .-square
7301       .ident  "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)"
7302       .section       .note.GNU-stack,"",@@progbits
7303 @end example
7305 @noindent
7307 By default, no optimizations are performed, the equivalent of GCC's
7308 @cite{-O0} option.  We can turn things up to e.g. @cite{-O3} by calling
7309 @pxref{d6,,gccjit;;context;;set_int_option()} with
7310 @pxref{1f,,GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}:
7312 @example
7313 ctxt.set_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL, 3);
7314 @end example
7316 @noindent
7318 @example
7319       .file   "fake.c"
7320       .text
7321       .p2align 4,,15
7322       .globl  square
7323       .type   square, @@function
7324 square:
7325 .LFB7:
7326       .cfi_startproc
7327 .L16:
7328       movl    %edi, %eax
7329       imull   %edi, %eax
7330       ret
7331       .cfi_endproc
7332 .LFE7:
7333       .size   square, .-square
7334       .ident  "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)"
7335       .section        .note.GNU-stack,"",@@progbits
7336 @end example
7338 @noindent
7340 Naturally this has only a small effect on such a trivial function.
7342 @node Full example<3>,,Options<3>,Tutorial part 2 Creating a trivial machine code function<2>
7343 @anchor{cp/intro/tutorial02 full-example}@anchor{d7}
7344 @subsubsection Full example
7347 Here's what the above looks like as a complete program:
7349 @quotation
7351 @example
7352 /* Usage example for libgccjit.so's C++ API
7353    Copyright (C) 2014 Free Software Foundation, Inc.
7355 This file is part of GCC.
7357 GCC is free software; you can redistribute it and/or modify it
7358 under the terms of the GNU General Public License as published by
7359 the Free Software Foundation; either version 3, or (at your option)
7360 any later version.
7362 GCC is distributed in the hope that it will be useful, but
7363 WITHOUT ANY WARRANTY; without even the implied warranty of
7364 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
7365 General Public License for more details.
7367 You should have received a copy of the GNU General Public License
7368 along with GCC; see the file COPYING3.  If not see
7369 <http://www.gnu.org/licenses/>.  */
7371 #include <libgccjit++.h>
7373 #include <stdlib.h>
7374 #include <stdio.h>
7376 void
7377 create_code (gccjit::context ctxt)
7379   /* Let's try to inject the equivalent of this C code:
7381       int square (int i)
7382       @{
7383         return i * i;
7384       @}
7385   */
7386   gccjit::type int_type = ctxt.get_type (GCC_JIT_TYPE_INT);
7387   gccjit::param param_i = ctxt.new_param (int_type, "i");
7388   std::vector<gccjit::param> params;
7389   params.push_back (param_i);
7390   gccjit::function func = ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
7391                                              int_type,
7392                                              "square",
7393                                              params, 0);
7395   gccjit::block block = func.new_block ();
7397   gccjit::rvalue expr =
7398     ctxt.new_binary_op (GCC_JIT_BINARY_OP_MULT, int_type,
7399                         param_i, param_i);
7401   block.end_with_return (expr);
7405 main (int argc, char **argv)
7407   /* Get a "context" object for working with the library.  */
7408   gccjit::context ctxt = gccjit::context::acquire ();
7410   /* Set some options on the context.
7411      Turn this on to see the code being generated, in assembler form.  */
7412   ctxt.set_bool_option (
7413     GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
7414     0);
7416   /* Populate the context.  */
7417   create_code (ctxt);
7419   /* Compile the code.  */
7420   gcc_jit_result *result = ctxt.compile ();
7422   /* We're done with the context; we can release it: */
7423   ctxt.release ();
7425   if (!result)
7426     @{
7427       fprintf (stderr, "NULL result");
7428       return 1;
7429     @}
7431   /* Extract the generated code from "result".  */
7432   void *fn_ptr = gcc_jit_result_get_code (result, "square");
7433   if (!fn_ptr)
7434      @{
7435        fprintf (stderr, "NULL fn_ptr");
7436        gcc_jit_result_release (result);
7437        return 1;
7438      @}
7440   typedef int (*fn_type) (int);
7441   fn_type square = (fn_type)fn_ptr;
7442   printf ("result: %d\n", square (5));
7444   gcc_jit_result_release (result);
7445   return 0;
7448 @end example
7450 @noindent
7451 @end quotation
7453 Building and running it:
7455 @example
7456 $ gcc \
7457     tut02-square.cc \
7458     -o tut02-square \
7459     -lgccjit
7461 # Run the built program:
7462 $ ./tut02-square
7463 result: 25
7464 @end example
7466 @noindent
7468 @c Copyright (C) 2014 Free Software Foundation, Inc.
7469 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
7470 @c 
7471 @c This is free software: you can redistribute it and/or modify it
7472 @c under the terms of the GNU General Public License as published by
7473 @c the Free Software Foundation, either version 3 of the License, or
7474 @c (at your option) any later version.
7475 @c 
7476 @c This program is distributed in the hope that it will be useful, but
7477 @c WITHOUT ANY WARRANTY; without even the implied warranty of
7478 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
7479 @c General Public License for more details.
7480 @c 
7481 @c You should have received a copy of the GNU General Public License
7482 @c along with this program.  If not, see
7483 @c <http://www.gnu.org/licenses/>.
7485 @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>
7486 @anchor{cp/intro/tutorial03 tutorial-part-3-loops-and-variables}@anchor{d8}@anchor{cp/intro/tutorial03 doc}@anchor{d9}
7487 @subsection Tutorial part 3: Loops and variables
7490 Consider this C function:
7492 @quotation
7494 @example
7495 int loop_test (int n)
7497   int sum = 0;
7498   for (int i = 0; i < n; i++)
7499     sum += i * i;
7500   return sum;
7502 @end example
7504 @noindent
7505 @end quotation
7507 This example demonstrates some more features of libgccjit, with local
7508 variables and a loop.
7510 To break this down into libgccjit terms, it's usually easier to reword
7511 the @cite{for} loop as a @cite{while} loop, giving:
7513 @quotation
7515 @example
7516 int loop_test (int n)
7518   int sum = 0;
7519   int i = 0;
7520   while (i < n)
7521   @{
7522     sum += i * i;
7523     i++;
7524   @}
7525   return sum;
7527 @end example
7529 @noindent
7530 @end quotation
7532 Here's what the final control flow graph will look like:
7534 @quotation
7537 @float Figure
7539 @image{sum-of-squares,,,image of a control flow graph,png}
7541 @end float
7543 @end quotation
7545 As before, we include the libgccjit++ header and make a
7546 @code{gccjit::context}.
7548 @example
7549 #include <libgccjit++.h>
7551 void test (void)
7553   gccjit::context ctxt;
7554   ctxt = gccjit::context::acquire ();
7555 @end example
7557 @noindent
7559 The function works with the C @cite{int} type.
7561 In the previous tutorial we acquired this via
7563 @example
7564 gccjit::type the_type = ctxt.get_type (ctxt, GCC_JIT_TYPE_INT);
7565 @end example
7567 @noindent
7569 though we could equally well make it work on, say, @cite{double}:
7571 @example
7572 gccjit::type the_type = ctxt.get_type (ctxt, GCC_JIT_TYPE_DOUBLE);
7573 @end example
7575 @noindent
7577 For integer types we can use @code{gccjit::context::get_int_type}
7578 to directly bind a specific type:
7580 @example
7581 gccjit::type the_type = ctxt.get_int_type <int> ();
7582 @end example
7584 @noindent
7586 Let's build the function:
7588 @example
7589 gcc_jit_param n = ctxt.new_param (the_type, "n");
7590 std::vector<gccjit::param> params;
7591 params.push_back (n);
7592 gccjit::function func =
7593   ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
7594                      return_type,
7595                      "loop_test",
7596                      params, 0);
7597 @end example
7599 @noindent
7601 @menu
7602 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues<2>. 
7603 * Control flow: Control flow<2>. 
7604 * Visualizing the control flow graph: Visualizing the control flow graph<2>. 
7605 * Full example: Full example<4>. 
7607 @end menu
7609 @node Expressions lvalues and rvalues<2>,Control flow<2>,,Tutorial part 3 Loops and variables<2>
7610 @anchor{cp/intro/tutorial03 expressions-lvalues-and-rvalues}@anchor{da}
7611 @subsubsection Expressions: lvalues and rvalues
7614 The base class of expression is the @code{gccjit::rvalue},
7615 representing an expression that can be on the @emph{right}-hand side of
7616 an assignment: a value that can be computed somehow, and assigned
7617 @emph{to} a storage area (such as a variable).  It has a specific
7618 @code{gccjit::type}.
7620 Anothe important class is @code{gccjit::lvalue}.
7621 A @code{gccjit::lvalue}. is something that can of the @emph{left}-hand
7622 side of an assignment: a storage area (such as a variable).
7624 In other words, every assignment can be thought of as:
7626 @example
7627 LVALUE = RVALUE;
7628 @end example
7630 @noindent
7632 Note that @code{gccjit::lvalue} is a subclass of
7633 @code{gccjit::rvalue}, where in an assignment of the form:
7635 @example
7636 LVALUE_A = LVALUE_B;
7637 @end example
7639 @noindent
7641 the @cite{LVALUE_B} implies reading the current value of that storage
7642 area, assigning it into the @cite{LVALUE_A}.
7644 So far the only expressions we've seen are from the previous tutorial:
7647 @enumerate 
7649 @item 
7650 the multiplication @cite{i * i}:
7651 @end enumerate
7653 @quotation
7655 @example
7656 gccjit::rvalue expr =
7657   ctxt.new_binary_op (
7658     GCC_JIT_BINARY_OP_MULT, int_type,
7659     param_i, param_i);
7661 /* Alternatively, using operator-overloading: */
7662 gccjit::rvalue expr = param_i * param_i;
7663 @end example
7665 @noindent
7667 which is a @code{gccjit::rvalue}, and
7668 @end quotation
7671 @enumerate 2
7673 @item 
7674 the various function parameters: @cite{param_i} and @cite{param_n}, instances of
7675 @code{gccjit::param}, which is a subclass of @code{gccjit::lvalue}
7676 (and, in turn, of @code{gccjit::rvalue}):
7677 we can both read from and write to function parameters within the
7678 body of a function.
7679 @end enumerate
7681 Our new example has a new kind of expression: we have two local
7682 variables.  We create them by calling
7683 @pxref{db,,gccjit;;function;;new_local()}, supplying a type and a name:
7685 @example
7686 /* Build locals:  */
7687 gccjit::lvalue i = func.new_local (the_type, "i");
7688 gccjit::lvalue sum = func.new_local (the_type, "sum");
7689 @end example
7691 @noindent
7693 These are instances of @code{gccjit::lvalue} - they can be read from
7694 and written to.
7696 Note that there is no precanned way to create @emph{and} initialize a variable
7697 like in C:
7699 @example
7700 int i = 0;
7701 @end example
7703 @noindent
7705 Instead, having added the local to the function, we have to separately add
7706 an assignment of @cite{0} to @cite{local_i} at the beginning of the function.
7708 @node Control flow<2>,Visualizing the control flow graph<2>,Expressions lvalues and rvalues<2>,Tutorial part 3 Loops and variables<2>
7709 @anchor{cp/intro/tutorial03 control-flow}@anchor{dc}
7710 @subsubsection Control flow
7713 This function has a loop, so we need to build some basic blocks to
7714 handle the control flow.  In this case, we need 4 blocks:
7717 @enumerate 
7719 @item 
7720 before the loop (initializing the locals)
7722 @item 
7723 the conditional at the top of the loop (comparing @cite{i < n})
7725 @item 
7726 the body of the loop
7728 @item 
7729 after the loop terminates (@cite{return sum})
7730 @end enumerate
7732 so we create these as @code{gccjit::block} instances within the
7733 @code{gccjit::function}:
7735 @example
7736 gccjit::block b_initial = func.new_block ("initial");
7737 gccjit::block b_loop_cond = func.new_block ("loop_cond");
7738 gccjit::block b_loop_body = func.new_block ("loop_body");
7739 gccjit::block b_after_loop = func.new_block ("after_loop");
7740 @end example
7742 @noindent
7744 We now populate each block with statements.
7746 The entry block @cite{b_initial} consists of initializations followed by a jump
7747 to the conditional.  We assign @cite{0} to @cite{i} and to @cite{sum}, using
7748 @pxref{dd,,gccjit;;block;;add_assignment()} to add
7749 an assignment statement, and using @pxref{de,,gccjit;;context;;zero()} to get
7750 the constant value @cite{0} for the relevant type for the right-hand side of
7751 the assignment:
7753 @example
7754 /* sum = 0; */
7755 b_initial.add_assignment (sum, ctxt.zero (the_type));
7757 /* i = 0; */
7758 b_initial.add_assignment (i, ctxt.zero (the_type));
7759 @end example
7761 @noindent
7763 We can then terminate the entry block by jumping to the conditional:
7765 @example
7766 b_initial.end_with_jump (b_loop_cond);
7767 @end example
7769 @noindent
7771 The conditional block is equivalent to the line @cite{while (i < n)} from our
7772 C example. It contains a single statement: a conditional, which jumps to
7773 one of two destination blocks depending on a boolean
7774 @code{gccjit::rvalue}, in this case the comparison of @cite{i} and @cite{n}.
7776 We could build the comparison using @pxref{df,,gccjit;;context;;new_comparison()}:
7778 @example
7779 gccjit::rvalue guard =
7780   ctxt.new_comparison (GCC_JIT_COMPARISON_GE,
7781                        i, n);
7782 @end example
7784 @noindent
7786 and can then use this to add @cite{b_loop_cond}'s sole statement, via
7787 @pxref{e0,,gccjit;;block;;end_with_conditional()}:
7789 @example
7790 b_loop_cond.end_with_conditional (guard);
7791 @end example
7793 @noindent
7795 However @code{gccjit::rvalue} has overloaded operators for this, so we
7796 express the conditional as
7798 @example
7799 gccjit::rvalue guard = (i >= n);
7800 @end example
7802 @noindent
7804 and hence write the block more concisely as:
7806 @example
7807 b_loop_cond.end_with_conditional (
7808   i >= n,
7809   b_after_loop,
7810   b_loop_body);
7811 @end example
7813 @noindent
7815 Next, we populate the body of the loop.
7817 The C statement @cite{sum += i * i;} is an assignment operation, where an
7818 lvalue is modified "in-place".  We use
7819 @pxref{e1,,gccjit;;block;;add_assignment_op()} to handle these operations:
7821 @example
7822 /* sum += i * i */
7823 b_loop_body.add_assignment_op (sum,
7824                                GCC_JIT_BINARY_OP_PLUS,
7825                                i * i);
7826 @end example
7828 @noindent
7830 The @cite{i++} can be thought of as @cite{i += 1}, and can thus be handled in
7831 a similar way.  We use @pxref{2f,,gcc_jit_context_one()} to get the constant
7832 value @cite{1} (for the relevant type) for the right-hand side
7833 of the assignment.
7835 @example
7836 /* i++ */
7837 b_loop_body.add_assignment_op (i,
7838                                GCC_JIT_BINARY_OP_PLUS,
7839                                ctxt.one (the_type));
7840 @end example
7842 @noindent
7844 @cartouche
7845 @quotation Note 
7846 For numeric constants other than 0 or 1, we could use
7847 @pxref{e2,,gccjit;;context;;new_rvalue()}, which has overloads
7848 for both @code{int} and @code{double}.
7849 @end quotation
7850 @end cartouche
7852 The loop body completes by jumping back to the conditional:
7854 @example
7855 b_loop_body.end_with_jump (b_loop_cond);
7856 @end example
7858 @noindent
7860 Finally, we populate the @cite{b_after_loop} block, reached when the loop
7861 conditional is false.  We want to generate the equivalent of:
7863 @example
7864 return sum;
7865 @end example
7867 @noindent
7869 so the block is just one statement:
7871 @example
7872 /* return sum */
7873 b_after_loop.end_with_return (sum);
7874 @end example
7876 @noindent
7878 @cartouche
7879 @quotation Note 
7880 You can intermingle block creation with statement creation,
7881 but given that the terminator statements generally include references
7882 to other blocks, I find it's clearer to create all the blocks,
7883 @emph{then} all the statements.
7884 @end quotation
7885 @end cartouche
7887 We've finished populating the function.  As before, we can now compile it
7888 to machine code:
7890 @example
7891 gcc_jit_result *result;
7892 result = ctxt.compile ();
7894 ctxt.release ();
7896 if (!result)
7897   @{
7898     fprintf (stderr, "NULL result");
7899     return 1;
7900   @}
7902 typedef int (*loop_test_fn_type) (int);
7903 loop_test_fn_type loop_test =
7904  (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
7905 if (!loop_test)
7906   @{
7907     fprintf (stderr, "NULL loop_test");
7908     gcc_jit_result_release (result);
7909     return 1;
7910   @}
7911 printf ("result: %d", loop_test (10));
7912 @end example
7914 @noindent
7916 @example
7917 result: 285
7918 @end example
7920 @noindent
7922 @node Visualizing the control flow graph<2>,Full example<4>,Control flow<2>,Tutorial part 3 Loops and variables<2>
7923 @anchor{cp/intro/tutorial03 visualizing-the-control-flow-graph}@anchor{e3}
7924 @subsubsection Visualizing the control flow graph
7927 You can see the control flow graph of a function using
7928 @pxref{e4,,gccjit;;function;;dump_to_dot()}:
7930 @example
7931 func.dump_to_dot ("/tmp/sum-of-squares.dot");
7932 @end example
7934 @noindent
7936 giving a .dot file in GraphViz format.
7938 You can convert this to an image using @cite{dot}:
7940 @example
7941 $ dot -Tpng /tmp/sum-of-squares.dot -o /tmp/sum-of-squares.png
7942 @end example
7944 @noindent
7946 or use a viewer (my preferred one is xdot.py; see
7947 @indicateurl{https://github.com/jrfonseca/xdot.py}; on Fedora you can
7948 install it with @cite{yum install python-xdot}):
7950 @quotation
7953 @float Figure
7955 @image{sum-of-squares,,,image of a control flow graph,png}
7957 @end float
7959 @end quotation
7961 @node Full example<4>,,Visualizing the control flow graph<2>,Tutorial part 3 Loops and variables<2>
7962 @anchor{cp/intro/tutorial03 full-example}@anchor{e5}
7963 @subsubsection Full example
7966 @quotation
7968 @example
7969 /* Usage example for libgccjit.so's C++ API
7970    Copyright (C) 2014 Free Software Foundation, Inc.
7972 This file is part of GCC.
7974 GCC is free software; you can redistribute it and/or modify it
7975 under the terms of the GNU General Public License as published by
7976 the Free Software Foundation; either version 3, or (at your option)
7977 any later version.
7979 GCC is distributed in the hope that it will be useful, but
7980 WITHOUT ANY WARRANTY; without even the implied warranty of
7981 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
7982 General Public License for more details.
7984 You should have received a copy of the GNU General Public License
7985 along with GCC; see the file COPYING3.  If not see
7986 <http://www.gnu.org/licenses/>.  */
7988 #include <libgccjit++.h>
7990 #include <stdlib.h>
7991 #include <stdio.h>
7993 void
7994 create_code (gccjit::context ctxt)
7996   /*
7997     Simple sum-of-squares, to test conditionals and looping
7999     int loop_test (int n)
8000     @{
8001       int i;
8002       int sum = 0;
8003       for (i = 0; i < n ; i ++)
8004       @{
8005         sum += i * i;
8006       @}
8007       return sum;
8008    */
8009   gccjit::type the_type = ctxt.get_int_type <int> ();
8010   gccjit::type return_type = the_type;
8012   gccjit::param n = ctxt.new_param (the_type, "n");
8013   std::vector<gccjit::param> params;
8014   params.push_back (n);
8015   gccjit::function func =
8016     ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
8017                        return_type,
8018                        "loop_test",
8019                        params, 0);
8021   /* Build locals:  */
8022   gccjit::lvalue i = func.new_local (the_type, "i");
8023   gccjit::lvalue sum = func.new_local (the_type, "sum");
8025   gccjit::block b_initial = func.new_block ("initial");
8026   gccjit::block b_loop_cond = func.new_block ("loop_cond");
8027   gccjit::block b_loop_body = func.new_block ("loop_body");
8028   gccjit::block b_after_loop = func.new_block ("after_loop");
8030   /* sum = 0; */
8031   b_initial.add_assignment (sum, ctxt.zero (the_type));
8033   /* i = 0; */
8034   b_initial.add_assignment (i, ctxt.zero (the_type));
8036   b_initial.end_with_jump (b_loop_cond);
8038   /* if (i >= n) */
8039   b_loop_cond.end_with_conditional (
8040     i >= n,
8041     b_after_loop,
8042     b_loop_body);
8044   /* sum += i * i */
8045   b_loop_body.add_assignment_op (sum,
8046                                  GCC_JIT_BINARY_OP_PLUS,
8047                                  i * i);
8049   /* i++ */
8050   b_loop_body.add_assignment_op (i,
8051                                 GCC_JIT_BINARY_OP_PLUS,
8052                                 ctxt.one (the_type));
8054   b_loop_body.end_with_jump (b_loop_cond);
8056   /* return sum */
8057   b_after_loop.end_with_return (sum);
8061 main (int argc, char **argv)
8063   gccjit::context ctxt;
8064   gcc_jit_result *result = NULL;
8066   /* Get a "context" object for working with the library.  */
8067   ctxt = gccjit::context::acquire ();
8069   /* Set some options on the context.
8070      Turn this on to see the code being generated, in assembler form.  */
8071   ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
8072                         0);
8074   /* Populate the context.  */
8075   create_code (ctxt);
8077   /* Compile the code.  */
8078   result = ctxt.compile ();
8080   ctxt.release ();
8082   if (!result)
8083     @{
8084       fprintf (stderr, "NULL result");
8085       return 1;
8086     @}
8088   /* Extract the generated code from "result".  */
8089   typedef int (*loop_test_fn_type) (int);
8090   loop_test_fn_type loop_test =
8091     (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
8092   if (!loop_test)
8093     @{
8094       fprintf (stderr, "NULL loop_test");
8095       gcc_jit_result_release (result);
8096       return 1;
8097     @}
8099   /* Run the generated code.  */
8100   int val = loop_test (10);
8101   printf("loop_test returned: %d\n", val);
8103   gcc_jit_result_release (result);
8104   return 0;
8107 @end example
8109 @noindent
8110 @end quotation
8112 Building and running it:
8114 @example
8115 $ gcc \
8116     tut03-sum-of-squares.cc \
8117     -o tut03-sum-of-squares \
8118     -lgccjit
8120 # Run the built program:
8121 $ ./tut03-sum-of-squares
8122 loop_test returned: 285
8123 @end example
8125 @noindent
8127 @c Copyright (C) 2014 Free Software Foundation, Inc.
8128 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
8129 @c 
8130 @c This is free software: you can redistribute it and/or modify it
8131 @c under the terms of the GNU General Public License as published by
8132 @c the Free Software Foundation, either version 3 of the License, or
8133 @c (at your option) any later version.
8134 @c 
8135 @c This program is distributed in the hope that it will be useful, but
8136 @c WITHOUT ANY WARRANTY; without even the implied warranty of
8137 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
8138 @c General Public License for more details.
8139 @c 
8140 @c You should have received a copy of the GNU General Public License
8141 @c along with this program.  If not, see
8142 @c <http://www.gnu.org/licenses/>.
8144 @node Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>,,Tutorial part 3 Loops and variables<2>,Tutorial<2>
8145 @anchor{cp/intro/tutorial04 tutorial-part-4-adding-jit-compilation-to-a-toy-interpreter}@anchor{e6}@anchor{cp/intro/tutorial04 doc}@anchor{e7}
8146 @subsection Tutorial part 4: Adding JIT-compilation to a toy interpreter
8149 In this example we construct a "toy" interpreter, and add JIT-compilation
8150 to it.
8152 @menu
8153 * Our toy interpreter: Our toy interpreter<2>. 
8154 * Compiling to machine code: Compiling to machine code<2>. 
8155 * Setting things up: Setting things up<2>. 
8156 * Populating the function: Populating the function<2>. 
8157 * Verifying the control flow graph: Verifying the control flow graph<2>. 
8158 * Compiling the context: Compiling the context<2>. 
8159 * Single-stepping through the generated code: Single-stepping through the generated code<2>. 
8160 * Examining the generated code: Examining the generated code<2>. 
8161 * Putting it all together: Putting it all together<2>. 
8162 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?<2>. 
8164 @end menu
8166 @node Our toy interpreter<2>,Compiling to machine code<2>,,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
8167 @anchor{cp/intro/tutorial04 our-toy-interpreter}@anchor{e8}
8168 @subsubsection Our toy interpreter
8171 It's a stack-based interpreter, and is intended as a (very simple) example
8172 of the kind of bytecode interpreter seen in dynamic languages such as
8173 Python, Ruby etc.
8175 For the sake of simplicity, our toy virtual machine is very limited:
8177 @quotation
8180 @itemize *
8182 @item 
8183 The only data type is @cite{int}
8185 @item 
8186 It can only work on one function at a time (so that the only
8187 function call that can be made is to recurse).
8189 @item 
8190 Functions can only take one parameter.
8192 @item 
8193 Functions have a stack of @cite{int} values.
8195 @item 
8196 We'll implement function call within the interpreter by calling a
8197 function in our implementation, rather than implementing our own
8198 frame stack.
8200 @item 
8201 The parser is only good enough to get the examples to work.
8202 @end itemize
8203 @end quotation
8205 Naturally, a real interpreter would be much more complicated that this.
8207 The following operations are supported:
8210 @multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxx} 
8211 @headitem
8213 Operation
8215 @tab
8217 Meaning
8219 @tab
8221 Old Stack
8223 @tab
8225 New Stack
8227 @item
8231 @tab
8233 Duplicate top of stack.
8235 @tab
8237 @code{[..., x]}
8239 @tab
8241 @code{[..., x, x]}
8243 @item
8247 @tab
8249 Swap top two elements
8250 of stack.
8252 @tab
8254 @code{[..., x, y]}
8256 @tab
8258 @code{[..., y, x]}
8260 @item
8262 BINARY_ADD
8264 @tab
8266 Add the top two elements
8267 on the stack.
8269 @tab
8271 @code{[..., x, y]}
8273 @tab
8275 @code{[..., (x+y)]}
8277 @item
8279 BINARY_SUBTRACT
8281 @tab
8283 Likewise, but subtract.
8285 @tab
8287 @code{[..., x, y]}
8289 @tab
8291 @code{[..., (x-y)]}
8293 @item
8295 BINARY_MULT
8297 @tab
8299 Likewise, but multiply.
8301 @tab
8303 @code{[..., x, y]}
8305 @tab
8307 @code{[..., (x*y)]}
8309 @item
8311 BINARY_COMPARE_LT
8313 @tab
8315 Compare the top two
8316 elements on the stack
8317 and push a nonzero/zero
8318 if (x<y).
8320 @tab
8322 @code{[..., x, y]}
8324 @tab
8326 @code{[..., (x<y)]}
8328 @item
8330 RECURSE
8332 @tab
8334 Recurse, passing the top
8335 of the stack, and
8336 popping the result.
8338 @tab
8340 @code{[..., x]}
8342 @tab
8344 @code{[..., fn(x)]}
8346 @item
8348 RETURN
8350 @tab
8352 Return the top of the
8353 stack.
8355 @tab
8357 @code{[x]}
8359 @tab
8361 @code{[]}
8363 @item
8365 PUSH_CONST @cite{arg}
8367 @tab
8369 Push an int const.
8371 @tab
8373 @code{[...]}
8375 @tab
8377 @code{[..., arg]}
8379 @item
8381 JUMP_ABS_IF_TRUE @cite{arg}
8383 @tab
8385 Pop; if top of stack was
8386 nonzero, jump to
8387 @code{arg}.
8389 @tab
8391 @code{[..., x]}
8393 @tab
8395 @code{[...]}
8397 @end multitable
8400 Programs can be interpreted, disassembled, and compiled to machine code.
8402 The interpreter reads @code{.toy} scripts.  Here's what a simple recursive
8403 factorial program looks like, the script @code{factorial.toy}.
8404 The parser ignores lines beginning with a @cite{#}.
8406 @quotation
8408 @example
8409 # Simple recursive factorial implementation, roughly equivalent to:
8411 #  int factorial (int arg)
8412 #  @{
8413 #     if (arg < 2)
8414 #       return arg
8415 #     return arg * factorial (arg - 1)
8416 #  @}
8418 # Initial state:
8419 # stack: [arg]
8421 # 0:
8423 # stack: [arg, arg]
8425 # 1:
8426 PUSH_CONST 2
8427 # stack: [arg, arg, 2]
8429 # 2:
8430 BINARY_COMPARE_LT
8431 # stack: [arg, (arg < 2)]
8433 # 3:
8434 JUMP_ABS_IF_TRUE 9
8435 # stack: [arg]
8437 # 4:
8439 # stack: [arg, arg]
8441 # 5:
8442 PUSH_CONST 1
8443 # stack: [arg, arg, 1]
8445 # 6:
8446 BINARY_SUBTRACT
8447 # stack: [arg,  (arg - 1)
8449 # 7:
8450 RECURSE
8451 # stack: [arg, factorial(arg - 1)]
8453 # 8:
8454 BINARY_MULT
8455 # stack: [arg * factorial(arg - 1)]
8457 # 9:
8458 RETURN
8460 @end example
8462 @noindent
8463 @end quotation
8465 The interpreter is a simple infinite loop with a big @code{switch} statement
8466 based on what the next opcode is:
8468 @quotation
8470 @example
8473 toyvm_function::interpret (int arg, FILE *trace)
8475   toyvm_frame frame;
8476 #define PUSH(ARG) (frame.push (ARG))
8477 #define POP(ARG) (frame.pop ())
8479   frame.frm_function = this;
8480   frame.frm_pc = 0;
8481   frame.frm_cur_depth = 0;
8483   PUSH (arg);
8485   while (1)
8486     @{
8487       toyvm_op *op;
8488       int x, y;
8489       assert (frame.frm_pc < fn_num_ops);
8490       op = &fn_ops[frame.frm_pc++];
8492       if (trace)
8493         @{
8494           frame.dump_stack (trace);
8495           disassemble_op (op, frame.frm_pc, trace);
8496         @}
8498       switch (op->op_opcode)
8499         @{
8500           /* Ops taking no operand.  */
8501         case DUP:
8502           x = POP ();
8503           PUSH (x);
8504           PUSH (x);
8505           break;
8507         case ROT:
8508           y = POP ();
8509           x = POP ();
8510           PUSH (y);
8511           PUSH (x);
8512           break;
8514         case BINARY_ADD:
8515           y = POP ();
8516           x = POP ();
8517           PUSH (x + y);
8518           break;
8520         case BINARY_SUBTRACT:
8521           y = POP ();
8522           x = POP ();
8523           PUSH (x - y);
8524           break;
8526         case BINARY_MULT:
8527           y = POP ();
8528           x = POP ();
8529           PUSH (x * y);
8530           break;
8532         case BINARY_COMPARE_LT:
8533           y = POP ();
8534           x = POP ();
8535           PUSH (x < y);
8536           break;
8538         case RECURSE:
8539           x = POP ();
8540           x = interpret (x, trace);
8541           PUSH (x);
8542           break;
8544         case RETURN:
8545           return POP ();
8547           /* Ops taking an operand.  */
8548         case PUSH_CONST:
8549           PUSH (op->op_operand);
8550           break;
8552         case JUMP_ABS_IF_TRUE:
8553           x = POP ();
8554           if (x)
8555             frame.frm_pc = op->op_operand;
8556           break;
8558         default:
8559           assert (0); /* unknown opcode */
8561         @} /* end of switch on opcode */
8562     @} /* end of while loop */
8564 #undef PUSH
8565 #undef POP
8569 @end example
8571 @noindent
8572 @end quotation
8574 @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>
8575 @anchor{cp/intro/tutorial04 compiling-to-machine-code}@anchor{e9}
8576 @subsubsection Compiling to machine code
8579 We want to generate machine code that can be cast to this type and
8580 then directly executed in-process:
8582 @quotation
8584 @example
8585 typedef int (*toyvm_compiled_func) (int);
8588 @end example
8590 @noindent
8591 @end quotation
8593 Our compiler isn't very sophisticated; it takes the implementation of
8594 each opcode above, and maps it directly to the operations supported by
8595 the libgccjit API.
8597 How should we handle the stack?  In theory we could calculate what the
8598 stack depth will be at each opcode, and optimize away the stack
8599 manipulation "by hand".  We'll see below that libgccjit is able to do
8600 this for us, so we'll implement stack manipulation
8601 in a direct way, by creating a @code{stack} array and @code{stack_depth}
8602 variables, local within the generated function, equivalent to this C code:
8604 @example
8605 int stack_depth;
8606 int stack[MAX_STACK_DEPTH];
8607 @end example
8609 @noindent
8611 We'll also have local variables @code{x} and @code{y} for use when implementing
8612 the opcodes, equivalent to this:
8614 @example
8615 int x;
8616 int y;
8617 @end example
8619 @noindent
8621 This means our compiler has the following state:
8623 @quotation
8625 @example
8627   toyvm_function &toyvmfn;
8629   gccjit::context ctxt;
8631   gccjit::type int_type;
8632   gccjit::type bool_type;
8633   gccjit::type stack_type; /* int[MAX_STACK_DEPTH] */
8635   gccjit::rvalue const_one;
8637   gccjit::function fn;
8638   gccjit::param param_arg;
8639   gccjit::lvalue stack;
8640   gccjit::lvalue stack_depth;
8641   gccjit::lvalue x;
8642   gccjit::lvalue y;
8644   gccjit::location op_locs[MAX_OPS];
8645   gccjit::block initial_block;
8646   gccjit::block op_blocks[MAX_OPS];
8649 @end example
8651 @noindent
8652 @end quotation
8654 @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>
8655 @anchor{cp/intro/tutorial04 setting-things-up}@anchor{ea}
8656 @subsubsection Setting things up
8659 First we create our types:
8661 @quotation
8663 @example
8665 void
8666 compilation_state::create_types ()
8668   /* Create types.  */
8669   int_type = ctxt.get_type (GCC_JIT_TYPE_INT);
8670   bool_type = ctxt.get_type (GCC_JIT_TYPE_BOOL);
8671   stack_type = ctxt.new_array_type (int_type, MAX_STACK_DEPTH);
8674 @end example
8676 @noindent
8677 @end quotation
8679 along with extracting a useful @cite{int} constant:
8681 @quotation
8683 @example
8684   const_one = ctxt.one (int_type);
8689 @end example
8691 @noindent
8692 @end quotation
8694 We'll implement push and pop in terms of the @code{stack} array and
8695 @code{stack_depth}.  Here are helper functions for adding statements to
8696 a block, implementing pushing and popping values:
8698 @quotation
8700 @example
8702 void
8703 compilation_state::add_push (gccjit::block block,
8704                              gccjit::rvalue rvalue,
8705                              gccjit::location loc)
8707   /* stack[stack_depth] = RVALUE */
8708   block.add_assignment (
8709     /* stack[stack_depth] */
8710     ctxt.new_array_access (
8711       stack,
8712       stack_depth,
8713       loc),
8714     rvalue,
8715     loc);
8717   /* "stack_depth++;".  */
8718   block.add_assignment_op (
8719     stack_depth,
8720     GCC_JIT_BINARY_OP_PLUS,
8721     const_one,
8722     loc);
8725 void
8726 compilation_state::add_pop (gccjit::block block,
8727                             gccjit::lvalue lvalue,
8728                             gccjit::location loc)
8730   /* "--stack_depth;".  */
8731   block.add_assignment_op (
8732     stack_depth,
8733     GCC_JIT_BINARY_OP_MINUS,
8734     const_one,
8735     loc);
8737   /* "LVALUE = stack[stack_depth];".  */
8738   block.add_assignment (
8739     lvalue,
8740     /* stack[stack_depth] */
8741     ctxt.new_array_access (stack,
8742                            stack_depth,
8743                            loc),
8744     loc);
8748 @end example
8750 @noindent
8751 @end quotation
8753 We will support single-stepping through the generated code in the
8754 debugger, so we need to create @code{gccjit::location} instances, one
8755 per operation in the source code.  These will reference the lines of
8756 e.g. @code{factorial.toy}.
8758 @quotation
8760 @example
8762 void
8763 compilation_state::create_locations ()
8765   for (int pc = 0; pc < toyvmfn.fn_num_ops; pc++)
8766     @{
8767       toyvm_op *op = &toyvmfn.fn_ops[pc];
8769       op_locs[pc] = ctxt.new_location (toyvmfn.fn_filename,
8770                                        op->op_linenum,
8771                                        0); /* column */
8772     @}
8776 @end example
8778 @noindent
8779 @end quotation
8781 Let's create the function itself.  As usual, we create its parameter
8782 first, then use the parameter to create the function:
8784 @quotation
8786 @example
8788 void
8789 compilation_state::create_function (const char *funcname)
8791   std::vector <gccjit::param> params;
8792   param_arg = ctxt.new_param (int_type, "arg", op_locs[0]);
8793   params.push_back (param_arg);
8794   fn = ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
8795                           int_type,
8796                           funcname,
8797                           params, 0,
8798                           op_locs[0]);
8801 @end example
8803 @noindent
8804 @end quotation
8806 We create the locals within the function.
8808 @quotation
8810 @example
8811   stack = fn.new_local (stack_type, "stack");
8812   stack_depth = fn.new_local (int_type, "stack_depth");
8813   x = fn.new_local (int_type, "x");
8814   y = fn.new_local (int_type, "y");
8817 @end example
8819 @noindent
8820 @end quotation
8822 @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>
8823 @anchor{cp/intro/tutorial04 populating-the-function}@anchor{eb}
8824 @subsubsection Populating the function
8827 There's some one-time initialization, and the API treats the first block
8828 you create as the entrypoint of the function, so we need to create that
8829 block first:
8831 @quotation
8833 @example
8834   initial_block = fn.new_block ("initial");
8837 @end example
8839 @noindent
8840 @end quotation
8842 We can now create blocks for each of the operations.  Most of these will
8843 be consolidated into larger blocks when the optimizer runs.
8845 @quotation
8847 @example
8848   for (int pc = 0; pc < toyvmfn.fn_num_ops; pc++)
8849     @{
8850       char buf[16];
8851       sprintf (buf, "instr%i", pc);
8852       op_blocks[pc] = fn.new_block (buf);
8853     @}
8856 @end example
8858 @noindent
8859 @end quotation
8861 Now that we have a block it can jump to when it's done, we can populate
8862 the initial block:
8864 @quotation
8866 @example
8868   /* "stack_depth = 0;".  */
8869   initial_block.add_assignment (stack_depth,
8870                                 ctxt.zero (int_type),
8871                                 op_locs[0]);
8873   /* "PUSH (arg);".  */
8874   add_push (initial_block,
8875             param_arg,
8876             op_locs[0]);
8878   /* ...and jump to insn 0.  */
8879   initial_block.end_with_jump (op_blocks[0],
8880                                op_locs[0]);
8883 @end example
8885 @noindent
8886 @end quotation
8888 We can now populate the blocks for the individual operations.  We loop
8889 through them, adding instructions to their blocks:
8891 @quotation
8893 @example
8894   for (int pc = 0; pc < toyvmfn.fn_num_ops; pc++)
8895     @{
8896       gccjit::location loc = op_locs[pc];
8898       gccjit::block block = op_blocks[pc];
8899       gccjit::block next_block = (pc < toyvmfn.fn_num_ops
8900                                   ? op_blocks[pc + 1]
8901                                   : NULL);
8903       toyvm_op *op;
8904       op = &toyvmfn.fn_ops[pc];
8907 @end example
8909 @noindent
8910 @end quotation
8912 We're going to have another big @code{switch} statement for implementing
8913 the opcodes, this time for compiling them, rather than interpreting
8914 them.  It's helpful to have macros for implementing push and pop, so that
8915 we can make the @code{switch} statement that's coming up look as much as
8916 possible like the one above within the interpreter:
8918 @example
8920 #define X_EQUALS_POP()\
8921       add_pop (block, x, loc)
8922 #define Y_EQUALS_POP()\
8923       add_pop (block, y, loc)
8924 #define PUSH_RVALUE(RVALUE)\
8925       add_push (block, (RVALUE), loc)
8926 #define PUSH_X()\
8927       PUSH_RVALUE (x)
8928 #define PUSH_Y() \
8929       PUSH_RVALUE (y)
8932 @end example
8934 @noindent
8936 @cartouche
8937 @quotation Note 
8938 A particularly clever implementation would have an @emph{identical}
8939 @code{switch} statement shared by the interpreter and the compiler, with
8940 some preprocessor "magic".  We're not doing that here, for the sake
8941 of simplicity.
8942 @end quotation
8943 @end cartouche
8945 When I first implemented this compiler, I accidentally missed an edit
8946 when copying and pasting the @code{Y_EQUALS_POP} macro, so that popping the
8947 stack into @code{y} instead erroneously assigned it to @code{x}, leaving @code{y}
8948 uninitialized.
8950 To track this kind of thing down, we can use
8951 @pxref{ec,,gccjit;;block;;add_comment()} to add descriptive comments
8952 to the internal representation.  This is invaluable when looking through
8953 the generated IR for, say @code{factorial}:
8955 @quotation
8957 @example
8959       block.add_comment (opcode_names[op->op_opcode], loc);
8962 @end example
8964 @noindent
8965 @end quotation
8967 We can now write the big @code{switch} statement that implements the
8968 individual opcodes, populating the relevant block with statements:
8970 @quotation
8972 @example
8974       switch (op->op_opcode)
8975         @{
8976         case DUP:
8977           X_EQUALS_POP ();
8978           PUSH_X ();
8979           PUSH_X ();
8980           break;
8982         case ROT:
8983           Y_EQUALS_POP ();
8984           X_EQUALS_POP ();
8985           PUSH_Y ();
8986           PUSH_X ();
8987           break;
8989         case BINARY_ADD:
8990           Y_EQUALS_POP ();
8991           X_EQUALS_POP ();
8992           PUSH_RVALUE (
8993            ctxt.new_binary_op (
8994              GCC_JIT_BINARY_OP_PLUS,
8995              int_type,
8996              x, y,
8997              loc));
8998           break;
9000         case BINARY_SUBTRACT:
9001           Y_EQUALS_POP ();
9002           X_EQUALS_POP ();
9003           PUSH_RVALUE (
9004            ctxt.new_binary_op (
9005              GCC_JIT_BINARY_OP_MINUS,
9006              int_type,
9007              x, y,
9008              loc));
9009           break;
9011         case BINARY_MULT:
9012           Y_EQUALS_POP ();
9013           X_EQUALS_POP ();
9014           PUSH_RVALUE (
9015            ctxt.new_binary_op (
9016              GCC_JIT_BINARY_OP_MULT,
9017              int_type,
9018              x, y,
9019              loc));
9020           break;
9022         case BINARY_COMPARE_LT:
9023           Y_EQUALS_POP ();
9024           X_EQUALS_POP ();
9025           PUSH_RVALUE (
9026              /* cast of bool to int */
9027              ctxt.new_cast (
9028                /* (x < y) as a bool */
9029                ctxt.new_comparison (
9030                  GCC_JIT_COMPARISON_LT,
9031                  x, y,
9032                  loc),
9033                int_type,
9034                loc));
9035           break;
9037         case RECURSE:
9038           @{
9039             X_EQUALS_POP ();
9040             PUSH_RVALUE (
9041               ctxt.new_call (
9042                 fn,
9043                 x,
9044                 loc));
9045             break;
9046           @}
9048         case RETURN:
9049           X_EQUALS_POP ();
9050           block.end_with_return (x, loc);
9051           break;
9053           /* Ops taking an operand.  */
9054         case PUSH_CONST:
9055           PUSH_RVALUE (
9056             ctxt.new_rvalue (int_type, op->op_operand));
9057           break;
9059         case JUMP_ABS_IF_TRUE:
9060           X_EQUALS_POP ();
9061           block.end_with_conditional (
9062             /* "(bool)x".  */
9063             ctxt.new_cast (x, bool_type, loc),
9064             op_blocks[op->op_operand], /* on_true */
9065             next_block, /* on_false */
9066             loc); 
9067           break;
9069         default:
9070           assert(0);
9071         @} /* end of switch on opcode */
9074 @end example
9076 @noindent
9077 @end quotation
9079 Every block must be terminated, via a call to one of the
9080 @code{gccjit::block::end_with_} entrypoints.  This has been done for two
9081 of the opcodes, but we need to do it for the other ones, by jumping
9082 to the next block.
9084 @quotation
9086 @example
9087       if (op->op_opcode != JUMP_ABS_IF_TRUE
9088           && op->op_opcode != RETURN)
9089         block.end_with_jump (next_block, loc);
9092 @end example
9094 @noindent
9095 @end quotation
9097 This is analogous to simply incrementing the program counter.
9099 @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>
9100 @anchor{cp/intro/tutorial04 verifying-the-control-flow-graph}@anchor{ed}
9101 @subsubsection Verifying the control flow graph
9104 Having finished looping over the blocks, the context is complete.
9106 As before, we can verify that the control flow and statements are sane by
9107 using @pxref{e4,,gccjit;;function;;dump_to_dot()}:
9109 @example
9110 fn.dump_to_dot ("/tmp/factorial.dot");
9111 @end example
9113 @noindent
9115 and viewing the result.  Note how the label names, comments, and
9116 variable names show up in the dump, to make it easier to spot
9117 errors in our compiler.
9119 @quotation
9122 @float Figure
9124 @image{factorial,,,image of a control flow graph,png}
9126 @end float
9128 @end quotation
9130 @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>
9131 @anchor{cp/intro/tutorial04 compiling-the-context}@anchor{ee}
9132 @subsubsection Compiling the context
9135 Having finished looping over the blocks and populating them with
9136 statements, the context is complete.
9138 We can now compile it, and extract machine code from the result:
9140 @quotation
9142 @example
9143   gcc_jit_result *result = state.compile ();
9145   return (toyvm_compiled_func)gcc_jit_result_get_code (result, funcname);
9147 @end example
9149 @noindent
9150 @end quotation
9152 We can now run the result:
9154 @quotation
9156 @example
9157   toyvm_compiled_func code = fn->compile ();
9158   printf ("compiler result: %d\n",
9159           code (atoi (argv[2])));
9162 @end example
9164 @noindent
9165 @end quotation
9167 @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>
9168 @anchor{cp/intro/tutorial04 single-stepping-through-the-generated-code}@anchor{ef}
9169 @subsubsection Single-stepping through the generated code
9172 It's possible to debug the generated code.  To do this we need to both:
9174 @quotation
9177 @itemize *
9179 @item 
9180 Set up source code locations for our statements, so that we can
9181 meaningfully step through the code.  We did this above by
9182 calling @pxref{f0,,gccjit;;context;;new_location()} and using the
9183 results.
9185 @item 
9186 Enable the generation of debugging information, by setting
9187 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} on the
9188 @code{gccjit::context} via
9189 @pxref{d5,,gccjit;;context;;set_bool_option()}:
9191 @example
9192 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DEBUGINFO, 1);
9193 @end example
9195 @noindent
9196 @end itemize
9197 @end quotation
9199 Having done this, we can put a breakpoint on the generated function:
9201 @example
9202 $ gdb --args ./toyvm factorial.toy 10
9203 (gdb) break factorial
9204 Function "factorial" not defined.
9205 Make breakpoint pending on future shared library load? (y or [n]) y
9206 Breakpoint 1 (factorial) pending.
9207 (gdb) run
9208 Breakpoint 1, factorial (arg=10) at factorial.toy:14
9209 14    DUP
9210 @end example
9212 @noindent
9214 We've set up location information, which references @code{factorial.toy}.
9215 This allows us to use e.g. @code{list} to see where we are in the script:
9217 @example
9218 (gdb) list
9220 10    # Initial state:
9221 11    # stack: [arg]
9223 13    # 0:
9224 14    DUP
9225 15    # stack: [arg, arg]
9227 17    # 1:
9228 18    PUSH_CONST 2
9229 @end example
9231 @noindent
9233 and to step through the function, examining the data:
9235 @example
9236 (gdb) n
9237 18    PUSH_CONST 2
9238 (gdb) n
9239 22    BINARY_COMPARE_LT
9240 (gdb) print stack
9241 $5 = @{10, 10, 2, 0, -7152, 32767, 0, 0@}
9242 (gdb) print stack_depth
9243 $6 = 3
9244 @end example
9246 @noindent
9248 You'll see that the parts of the @code{stack} array that haven't been
9249 touched yet are uninitialized.
9251 @cartouche
9252 @quotation Note 
9253 Turning on optimizations may lead to unpredictable results when
9254 stepping through the generated code: the execution may appear to
9255 "jump around" the source code.  This is analogous to turning up the
9256 optimization level in a regular compiler.
9257 @end quotation
9258 @end cartouche
9260 @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>
9261 @anchor{cp/intro/tutorial04 examining-the-generated-code}@anchor{f1}
9262 @subsubsection Examining the generated code
9265 How good is the optimized code?
9267 We can turn up optimizations, by calling
9268 @pxref{d6,,gccjit;;context;;set_int_option()} with
9269 @pxref{1f,,GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}:
9271 @example
9272 ctxt.set_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL, 3);
9273 @end example
9275 @noindent
9277 One of GCC's internal representations is called "gimple".  A dump of the
9278 initial gimple representation of the code can be seen by setting:
9280 @example
9281 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE, 1);
9282 @end example
9284 @noindent
9286 With optimization on and source locations displayed, this gives:
9288 @c We'll use "c" for gimple dumps
9290 @example
9291 factorial (signed int arg)
9293   <unnamed type> D.80;
9294   signed int D.81;
9295   signed int D.82;
9296   signed int D.83;
9297   signed int D.84;
9298   signed int D.85;
9299   signed int y;
9300   signed int x;
9301   signed int stack_depth;
9302   signed int stack[8];
9304   try
9305     @{
9306       initial:
9307       stack_depth = 0;
9308       stack[stack_depth] = arg;
9309       stack_depth = stack_depth + 1;
9310       goto instr0;
9311       instr0:
9312       /* DUP */:
9313       stack_depth = stack_depth + -1;
9314       x = stack[stack_depth];
9315       stack[stack_depth] = x;
9316       stack_depth = stack_depth + 1;
9317       stack[stack_depth] = x;
9318       stack_depth = stack_depth + 1;
9319       goto instr1;
9320       instr1:
9321       /* PUSH_CONST */:
9322       stack[stack_depth] = 2;
9323       stack_depth = stack_depth + 1;
9324       goto instr2;
9326       /* etc */
9327 @end example
9329 @noindent
9331 You can see the generated machine code in assembly form via:
9333 @example
9334 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE, 1);
9335 result = ctxt.compile ();
9336 @end example
9338 @noindent
9340 which shows that (on this x86_64 box) the compiler has unrolled the loop
9341 and is using MMX instructions to perform several multiplications
9342 simultaneously:
9344 @example
9345         .file   "fake.c"
9346         .text
9347 .Ltext0:
9348         .p2align 4,,15
9349         .globl  factorial
9350         .type   factorial, @@function
9351 factorial:
9352 .LFB0:
9353         .file 1 "factorial.toy"
9354         .loc 1 14 0
9355         .cfi_startproc
9356 .LVL0:
9357 .L2:
9358         .loc 1 26 0
9359         cmpl    $1, %edi
9360         jle     .L13
9361         leal    -1(%rdi), %edx
9362         movl    %edx, %ecx
9363         shrl    $2, %ecx
9364         leal    0(,%rcx,4), %esi
9365         testl   %esi, %esi
9366         je      .L14
9367         cmpl    $9, %edx
9368         jbe     .L14
9369         leal    -2(%rdi), %eax
9370         movl    %eax, -16(%rsp)
9371         leal    -3(%rdi), %eax
9372         movd    -16(%rsp), %xmm0
9373         movl    %edi, -16(%rsp)
9374         movl    %eax, -12(%rsp)
9375         movd    -16(%rsp), %xmm1
9376         xorl    %eax, %eax
9377         movl    %edx, -16(%rsp)
9378         movd    -12(%rsp), %xmm4
9379         movd    -16(%rsp), %xmm6
9380         punpckldq       %xmm4, %xmm0
9381         movdqa  .LC1(%rip), %xmm4
9382         punpckldq       %xmm6, %xmm1
9383         punpcklqdq      %xmm0, %xmm1
9384         movdqa  .LC0(%rip), %xmm0
9385         jmp     .L5
9386         # etc - edited for brevity
9387 @end example
9389 @noindent
9391 This is clearly overkill for a function that will likely overflow the
9392 @code{int} type before the vectorization is worthwhile - but then again, this
9393 is a toy example.
9395 Turning down the optimization level to 2:
9397 @example
9398 ctxt.set_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL, 2);
9399 @end example
9401 @noindent
9403 yields this code, which is simple enough to quote in its entirety:
9405 @example
9406         .file   "fake.c"
9407         .text
9408         .p2align 4,,15
9409         .globl  factorial
9410         .type   factorial, @@function
9411 factorial:
9412 .LFB0:
9413         .cfi_startproc
9414 .L2:
9415         cmpl    $1, %edi
9416         jle     .L8
9417         movl    $1, %edx
9418         jmp     .L4
9419         .p2align 4,,10
9420         .p2align 3
9421 .L6:
9422         movl    %eax, %edi
9423 .L4:
9424 .L5:
9425         leal    -1(%rdi), %eax
9426         imull   %edi, %edx
9427         cmpl    $1, %eax
9428         jne     .L6
9429 .L3:
9430 .L7:
9431         imull   %edx, %eax
9432         ret
9433 .L8:
9434         movl    %edi, %eax
9435         movl    $1, %edx
9436         jmp     .L7
9437         .cfi_endproc
9438 .LFE0:
9439         .size   factorial, .-factorial
9440         .ident  "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-%@{gcc_release@})"
9441         .section        .note.GNU-stack,"",@@progbits
9442 @end example
9444 @noindent
9446 Note that the stack pushing and popping have been eliminated, as has the
9447 recursive call (in favor of an iteration).
9449 @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>
9450 @anchor{cp/intro/tutorial04 putting-it-all-together}@anchor{f2}
9451 @subsubsection Putting it all together
9454 The complete example can be seen in the source tree at
9455 @code{gcc/jit/docs/examples/tut04-toyvm/toyvm.cc}
9457 along with a Makefile and a couple of sample .toy scripts:
9459 @example
9460 $ ls -al
9461 drwxrwxr-x. 2 david david   4096 Sep 19 17:46 .
9462 drwxrwxr-x. 3 david david   4096 Sep 19 15:26 ..
9463 -rw-rw-r--. 1 david david    615 Sep 19 12:43 factorial.toy
9464 -rw-rw-r--. 1 david david    834 Sep 19 13:08 fibonacci.toy
9465 -rw-rw-r--. 1 david david    238 Sep 19 14:22 Makefile
9466 -rw-rw-r--. 1 david david  16457 Sep 19 17:07 toyvm.cc
9468 $ make toyvm
9469 g++ -Wall -g -o toyvm toyvm.cc -lgccjit
9471 $ ./toyvm factorial.toy 10
9472 interpreter result: 3628800
9473 compiler result: 3628800
9475 $ ./toyvm fibonacci.toy 10
9476 interpreter result: 55
9477 compiler result: 55
9478 @end example
9480 @noindent
9482 @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>
9483 @anchor{cp/intro/tutorial04 behind-the-curtain-how-does-our-code-get-optimized}@anchor{f3}
9484 @subsubsection Behind the curtain: How does our code get optimized?
9487 Our example is done, but you may be wondering about exactly how the
9488 compiler turned what we gave it into the machine code seen above.
9490 We can examine what the compiler is doing in detail by setting:
9492 @example
9493 state.ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING, 1);
9494 state.ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES, 1);
9495 @end example
9497 @noindent
9499 This will dump detailed information about the compiler's state to a
9500 directory under @code{/tmp}, and keep it from being cleaned up.
9502 The precise names and their formats of these files is subject to change.
9503 Higher optimization levels lead to more files.
9504 Here's what I saw (edited for brevity; there were almost 200 files):
9506 @example
9507 intermediate files written to /tmp/libgccjit-KPQbGw
9508 $ ls /tmp/libgccjit-KPQbGw/
9509 fake.c.000i.cgraph
9510 fake.c.000i.type-inheritance
9511 fake.c.004t.gimple
9512 fake.c.007t.omplower
9513 fake.c.008t.lower
9514 fake.c.011t.eh
9515 fake.c.012t.cfg
9516 fake.c.014i.visibility
9517 fake.c.015i.early_local_cleanups
9518 fake.c.016t.ssa
9519 # etc
9520 @end example
9522 @noindent
9524 The gimple code is converted into Static Single Assignment form,
9525 with annotations for use when generating the debuginfo:
9527 @example
9528 $ less /tmp/libgccjit-KPQbGw/fake.c.016t.ssa
9529 @end example
9531 @noindent
9533 @example
9534 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9536 factorial (signed int arg)
9538   signed int stack[8];
9539   signed int stack_depth;
9540   signed int x;
9541   signed int y;
9542   <unnamed type> _20;
9543   signed int _21;
9544   signed int _38;
9545   signed int _44;
9546   signed int _51;
9547   signed int _56;
9549 initial:
9550   stack_depth_3 = 0;
9551   # DEBUG stack_depth => stack_depth_3
9552   stack[stack_depth_3] = arg_5(D);
9553   stack_depth_7 = stack_depth_3 + 1;
9554   # DEBUG stack_depth => stack_depth_7
9555   # DEBUG instr0 => NULL
9556   # DEBUG /* DUP */ => NULL
9557   stack_depth_8 = stack_depth_7 + -1;
9558   # DEBUG stack_depth => stack_depth_8
9559   x_9 = stack[stack_depth_8];
9560   # DEBUG x => x_9
9561   stack[stack_depth_8] = x_9;
9562   stack_depth_11 = stack_depth_8 + 1;
9563   # DEBUG stack_depth => stack_depth_11
9564   stack[stack_depth_11] = x_9;
9565   stack_depth_13 = stack_depth_11 + 1;
9566   # DEBUG stack_depth => stack_depth_13
9567   # DEBUG instr1 => NULL
9568   # DEBUG /* PUSH_CONST */ => NULL
9569   stack[stack_depth_13] = 2;
9571   /* etc; edited for brevity */
9572 @end example
9574 @noindent
9576 We can perhaps better see the code by turning off
9577 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} to suppress all those @code{DEBUG}
9578 statements, giving:
9580 @example
9581 $ less /tmp/libgccjit-1Hywc0/fake.c.016t.ssa
9582 @end example
9584 @noindent
9586 @example
9587 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9589 factorial (signed int arg)
9591   signed int stack[8];
9592   signed int stack_depth;
9593   signed int x;
9594   signed int y;
9595   <unnamed type> _20;
9596   signed int _21;
9597   signed int _38;
9598   signed int _44;
9599   signed int _51;
9600   signed int _56;
9602 initial:
9603   stack_depth_3 = 0;
9604   stack[stack_depth_3] = arg_5(D);
9605   stack_depth_7 = stack_depth_3 + 1;
9606   stack_depth_8 = stack_depth_7 + -1;
9607   x_9 = stack[stack_depth_8];
9608   stack[stack_depth_8] = x_9;
9609   stack_depth_11 = stack_depth_8 + 1;
9610   stack[stack_depth_11] = x_9;
9611   stack_depth_13 = stack_depth_11 + 1;
9612   stack[stack_depth_13] = 2;
9613   stack_depth_15 = stack_depth_13 + 1;
9614   stack_depth_16 = stack_depth_15 + -1;
9615   y_17 = stack[stack_depth_16];
9616   stack_depth_18 = stack_depth_16 + -1;
9617   x_19 = stack[stack_depth_18];
9618   _20 = x_19 < y_17;
9619   _21 = (signed int) _20;
9620   stack[stack_depth_18] = _21;
9621   stack_depth_23 = stack_depth_18 + 1;
9622   stack_depth_24 = stack_depth_23 + -1;
9623   x_25 = stack[stack_depth_24];
9624   if (x_25 != 0)
9625     goto <bb 4> (instr9);
9626   else
9627     goto <bb 3> (instr4);
9629 instr4:
9630 /* DUP */:
9631   stack_depth_26 = stack_depth_24 + -1;
9632   x_27 = stack[stack_depth_26];
9633   stack[stack_depth_26] = x_27;
9634   stack_depth_29 = stack_depth_26 + 1;
9635   stack[stack_depth_29] = x_27;
9636   stack_depth_31 = stack_depth_29 + 1;
9637   stack[stack_depth_31] = 1;
9638   stack_depth_33 = stack_depth_31 + 1;
9639   stack_depth_34 = stack_depth_33 + -1;
9640   y_35 = stack[stack_depth_34];
9641   stack_depth_36 = stack_depth_34 + -1;
9642   x_37 = stack[stack_depth_36];
9643   _38 = x_37 - y_35;
9644   stack[stack_depth_36] = _38;
9645   stack_depth_40 = stack_depth_36 + 1;
9646   stack_depth_41 = stack_depth_40 + -1;
9647   x_42 = stack[stack_depth_41];
9648   _44 = factorial (x_42);
9649   stack[stack_depth_41] = _44;
9650   stack_depth_46 = stack_depth_41 + 1;
9651   stack_depth_47 = stack_depth_46 + -1;
9652   y_48 = stack[stack_depth_47];
9653   stack_depth_49 = stack_depth_47 + -1;
9654   x_50 = stack[stack_depth_49];
9655   _51 = x_50 * y_48;
9656   stack[stack_depth_49] = _51;
9657   stack_depth_53 = stack_depth_49 + 1;
9659   # stack_depth_1 = PHI <stack_depth_24(2), stack_depth_53(3)>
9660 instr9:
9661 /* RETURN */:
9662   stack_depth_54 = stack_depth_1 + -1;
9663   x_55 = stack[stack_depth_54];
9664   _56 = x_55;
9665   stack =@{v@} @{CLOBBER@};
9666   return _56;
9669 @end example
9671 @noindent
9673 Note in the above how all the @code{gccjit::block} instances we
9674 created have been consolidated into just 3 blocks in GCC's internal
9675 representation: @code{initial}, @code{instr4} and @code{instr9}.
9677 @menu
9678 * Optimizing away stack manipulation: Optimizing away stack manipulation<2>. 
9679 * Elimination of tail recursion: Elimination of tail recursion<2>. 
9681 @end menu
9683 @node Optimizing away stack manipulation<2>,Elimination of tail recursion<2>,,Behind the curtain How does our code get optimized?<2>
9684 @anchor{cp/intro/tutorial04 optimizing-away-stack-manipulation}@anchor{f4}
9685 @subsubsection Optimizing away stack manipulation
9688 Recall our simple implementation of stack operations.  Let's examine
9689 how the stack operations are optimized away.
9691 After a pass of constant-propagation, the depth of the stack at each
9692 opcode can be determined at compile-time:
9694 @example
9695 $ less /tmp/libgccjit-1Hywc0/fake.c.021t.ccp1
9696 @end example
9698 @noindent
9700 @example
9701 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9703 factorial (signed int arg)
9705   signed int stack[8];
9706   signed int stack_depth;
9707   signed int x;
9708   signed int y;
9709   <unnamed type> _20;
9710   signed int _21;
9711   signed int _38;
9712   signed int _44;
9713   signed int _51;
9715 initial:
9716   stack[0] = arg_5(D);
9717   x_9 = stack[0];
9718   stack[0] = x_9;
9719   stack[1] = x_9;
9720   stack[2] = 2;
9721   y_17 = stack[2];
9722   x_19 = stack[1];
9723   _20 = x_19 < y_17;
9724   _21 = (signed int) _20;
9725   stack[1] = _21;
9726   x_25 = stack[1];
9727   if (x_25 != 0)
9728     goto <bb 4> (instr9);
9729   else
9730     goto <bb 3> (instr4);
9732 instr4:
9733 /* DUP */:
9734   x_27 = stack[0];
9735   stack[0] = x_27;
9736   stack[1] = x_27;
9737   stack[2] = 1;
9738   y_35 = stack[2];
9739   x_37 = stack[1];
9740   _38 = x_37 - y_35;
9741   stack[1] = _38;
9742   x_42 = stack[1];
9743   _44 = factorial (x_42);
9744   stack[1] = _44;
9745   y_48 = stack[1];
9746   x_50 = stack[0];
9747   _51 = x_50 * y_48;
9748   stack[0] = _51;
9750 instr9:
9751 /* RETURN */:
9752   x_55 = stack[0];
9753   x_56 = x_55;
9754   stack =@{v@} @{CLOBBER@};
9755   return x_56;
9758 @end example
9760 @noindent
9762 Note how, in the above, all those @code{stack_depth} values are now just
9763 constants: we're accessing specific stack locations at each opcode.
9765 The "esra" pass ("Early Scalar Replacement of Aggregates") breaks
9766 out our "stack" array into individual elements:
9768 @example
9769 $ less /tmp/libgccjit-1Hywc0/fake.c.024t.esra
9770 @end example
9772 @noindent
9774 @example
9775 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9777 Created a replacement for stack offset: 0, size: 32: stack$0
9778 Created a replacement for stack offset: 32, size: 32: stack$1
9779 Created a replacement for stack offset: 64, size: 32: stack$2
9781 Symbols to be put in SSA form
9782 @{ D.89 D.90 D.91 @}
9783 Incremental SSA update started at block: 0
9784 Number of blocks in CFG: 5
9785 Number of blocks to update: 4 ( 80%)
9788 factorial (signed int arg)
9790   signed int stack$2;
9791   signed int stack$1;
9792   signed int stack$0;
9793   signed int stack[8];
9794   signed int stack_depth;
9795   signed int x;
9796   signed int y;
9797   <unnamed type> _20;
9798   signed int _21;
9799   signed int _38;
9800   signed int _44;
9801   signed int _51;
9803 initial:
9804   stack$0_45 = arg_5(D);
9805   x_9 = stack$0_45;
9806   stack$0_39 = x_9;
9807   stack$1_32 = x_9;
9808   stack$2_30 = 2;
9809   y_17 = stack$2_30;
9810   x_19 = stack$1_32;
9811   _20 = x_19 < y_17;
9812   _21 = (signed int) _20;
9813   stack$1_28 = _21;
9814   x_25 = stack$1_28;
9815   if (x_25 != 0)
9816     goto <bb 4> (instr9);
9817   else
9818     goto <bb 3> (instr4);
9820 instr4:
9821 /* DUP */:
9822   x_27 = stack$0_39;
9823   stack$0_22 = x_27;
9824   stack$1_14 = x_27;
9825   stack$2_12 = 1;
9826   y_35 = stack$2_12;
9827   x_37 = stack$1_14;
9828   _38 = x_37 - y_35;
9829   stack$1_10 = _38;
9830   x_42 = stack$1_10;
9831   _44 = factorial (x_42);
9832   stack$1_6 = _44;
9833   y_48 = stack$1_6;
9834   x_50 = stack$0_22;
9835   _51 = x_50 * y_48;
9836   stack$0_1 = _51;
9838   # stack$0_52 = PHI <stack$0_39(2), stack$0_1(3)>
9839 instr9:
9840 /* RETURN */:
9841   x_55 = stack$0_52;
9842   x_56 = x_55;
9843   stack =@{v@} @{CLOBBER@};
9844   return x_56;
9847 @end example
9849 @noindent
9851 Hence at this point, all those pushes and pops of the stack are now
9852 simply assignments to specific temporary variables.
9854 After some copy propagation, the stack manipulation has been completely
9855 optimized away:
9857 @example
9858 $ less /tmp/libgccjit-1Hywc0/fake.c.026t.copyprop1
9859 @end example
9861 @noindent
9863 @example
9864 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9866 factorial (signed int arg)
9868   signed int stack$2;
9869   signed int stack$1;
9870   signed int stack$0;
9871   signed int stack[8];
9872   signed int stack_depth;
9873   signed int x;
9874   signed int y;
9875   <unnamed type> _20;
9876   signed int _21;
9877   signed int _38;
9878   signed int _44;
9879   signed int _51;
9881 initial:
9882   stack$0_39 = arg_5(D);
9883   _20 = arg_5(D) <= 1;
9884   _21 = (signed int) _20;
9885   if (_21 != 0)
9886     goto <bb 4> (instr9);
9887   else
9888     goto <bb 3> (instr4);
9890 instr4:
9891 /* DUP */:
9892   _38 = arg_5(D) + -1;
9893   _44 = factorial (_38);
9894   _51 = arg_5(D) * _44;
9895   stack$0_1 = _51;
9897   # stack$0_52 = PHI <arg_5(D)(2), _51(3)>
9898 instr9:
9899 /* RETURN */:
9900   stack =@{v@} @{CLOBBER@};
9901   return stack$0_52;
9904 @end example
9906 @noindent
9908 Later on, another pass finally eliminated @code{stack_depth} local and the
9909 unused parts of the @cite{stack`} array altogether:
9911 @example
9912 $ less /tmp/libgccjit-1Hywc0/fake.c.036t.release_ssa
9913 @end example
9915 @noindent
9917 @example
9918 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9920 Released 44 names, 314.29%, removed 44 holes
9921 factorial (signed int arg)
9923   signed int stack$0;
9924   signed int mult_acc_1;
9925   <unnamed type> _5;
9926   signed int _6;
9927   signed int _7;
9928   signed int mul_tmp_10;
9929   signed int mult_acc_11;
9930   signed int mult_acc_13;
9932   # arg_9 = PHI <arg_8(D)(0)>
9933   # mult_acc_13 = PHI <1(0)>
9934 initial:
9936   <bb 5>:
9937   # arg_4 = PHI <arg_9(2), _7(3)>
9938   # mult_acc_1 = PHI <mult_acc_13(2), mult_acc_11(3)>
9939   _5 = arg_4 <= 1;
9940   _6 = (signed int) _5;
9941   if (_6 != 0)
9942     goto <bb 4> (instr9);
9943   else
9944     goto <bb 3> (instr4);
9946 instr4:
9947 /* DUP */:
9948   _7 = arg_4 + -1;
9949   mult_acc_11 = mult_acc_1 * arg_4;
9950   goto <bb 5>;
9952   # stack$0_12 = PHI <arg_4(5)>
9953 instr9:
9954 /* RETURN */:
9955   mul_tmp_10 = mult_acc_1 * stack$0_12;
9956   return mul_tmp_10;
9959 @end example
9961 @noindent
9963 @node Elimination of tail recursion<2>,,Optimizing away stack manipulation<2>,Behind the curtain How does our code get optimized?<2>
9964 @anchor{cp/intro/tutorial04 elimination-of-tail-recursion}@anchor{f5}
9965 @subsubsection Elimination of tail recursion
9968 Another significant optimization is the detection that the call to
9969 @code{factorial} is tail recursion, which can be eliminated in favor of
9970 an iteration:
9972 @example
9973 $ less /tmp/libgccjit-1Hywc0/fake.c.030t.tailr1
9974 @end example
9976 @noindent
9978 @example
9979 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9982 Symbols to be put in SSA form
9983 @{ D.88 @}
9984 Incremental SSA update started at block: 0
9985 Number of blocks in CFG: 5
9986 Number of blocks to update: 4 ( 80%)
9989 factorial (signed int arg)
9991   signed int stack$2;
9992   signed int stack$1;
9993   signed int stack$0;
9994   signed int stack[8];
9995   signed int stack_depth;
9996   signed int x;
9997   signed int y;
9998   signed int mult_acc_1;
9999   <unnamed type> _20;
10000   signed int _21;
10001   signed int _38;
10002   signed int mul_tmp_44;
10003   signed int mult_acc_51;
10005   # arg_5 = PHI <arg_39(D)(0), _38(3)>
10006   # mult_acc_1 = PHI <1(0), mult_acc_51(3)>
10007 initial:
10008   _20 = arg_5 <= 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 + -1;
10018   mult_acc_51 = mult_acc_1 * arg_5;
10019   goto <bb 2> (initial);
10021   # stack$0_52 = PHI <arg_5(2)>
10022 instr9:
10023 /* RETURN */:
10024   stack =@{v@} @{CLOBBER@};
10025   mul_tmp_44 = mult_acc_1 * stack$0_52;
10026   return mul_tmp_44;
10029 @end example
10031 @noindent
10033 @c Copyright (C) 2014 Free Software Foundation, Inc.
10034 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
10035 @c 
10036 @c This is free software: you can redistribute it and/or modify it
10037 @c under the terms of the GNU General Public License as published by
10038 @c the Free Software Foundation, either version 3 of the License, or
10039 @c (at your option) any later version.
10040 @c 
10041 @c This program is distributed in the hope that it will be useful, but
10042 @c WITHOUT ANY WARRANTY; without even the implied warranty of
10043 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10044 @c General Public License for more details.
10045 @c 
10046 @c You should have received a copy of the GNU General Public License
10047 @c along with this program.  If not, see
10048 @c <http://www.gnu.org/licenses/>.
10050 @node Topic Reference<2>,,Tutorial<2>,C++ bindings for libgccjit
10051 @anchor{cp/topics/index doc}@anchor{f6}@anchor{cp/topics/index topic-reference}@anchor{f7}
10052 @section Topic Reference
10055 @c Copyright (C) 2014 Free Software Foundation, Inc.
10056 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
10057 @c 
10058 @c This is free software: you can redistribute it and/or modify it
10059 @c under the terms of the GNU General Public License as published by
10060 @c the Free Software Foundation, either version 3 of the License, or
10061 @c (at your option) any later version.
10062 @c 
10063 @c This program is distributed in the hope that it will be useful, but
10064 @c WITHOUT ANY WARRANTY; without even the implied warranty of
10065 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10066 @c General Public License for more details.
10067 @c 
10068 @c You should have received a copy of the GNU General Public License
10069 @c along with this program.  If not, see
10070 @c <http://www.gnu.org/licenses/>.
10072 @menu
10073 * Compilation contexts: Compilation contexts<2>. 
10074 * Objects: Objects<2>. 
10075 * Types: Types<2>. 
10076 * Expressions: Expressions<2>. 
10077 * Creating and using functions: Creating and using functions<2>. 
10078 * Source Locations: Source Locations<2>. 
10079 * Compilation results: Compilation results<2>. 
10081 Compilation contexts
10083 * Lifetime-management: Lifetime-management<2>. 
10084 * Thread-safety: Thread-safety<2>. 
10085 * Error-handling: Error-handling<3>. 
10086 * Debugging: Debugging<2>. 
10087 * Options: Options<4>. 
10089 Options
10091 * String Options: String Options<2>. 
10092 * Boolean options: Boolean options<2>. 
10093 * Integer options: Integer options<2>. 
10095 Types
10097 * Standard types: Standard types<2>. 
10098 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile<2>. 
10099 * Structures and unions: Structures and unions<2>. 
10101 Expressions
10103 * Rvalues: Rvalues<2>. 
10104 * Lvalues: Lvalues<2>. 
10105 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions<2>. 
10107 Rvalues
10109 * Simple expressions: Simple expressions<2>. 
10110 * Unary Operations: Unary Operations<2>. 
10111 * Binary Operations: Binary Operations<2>. 
10112 * Comparisons: Comparisons<2>. 
10113 * Function calls: Function calls<2>. 
10114 * Type-coercion: Type-coercion<2>. 
10116 Lvalues
10118 * Global variables: Global variables<2>. 
10120 Creating and using functions
10122 * Params: Params<2>. 
10123 * Functions: Functions<2>. 
10124 * Blocks: Blocks<2>. 
10125 * Statements: Statements<2>. 
10127 Source Locations
10129 * Faking it: Faking it<2>. 
10131 @end menu
10134 @node Compilation contexts<2>,Objects<2>,,Topic Reference<2>
10135 @anchor{cp/topics/contexts compilation-contexts}@anchor{f8}@anchor{cp/topics/contexts doc}@anchor{f9}
10136 @subsection Compilation contexts
10139 @geindex gccjit;;context (C++ class)
10140 @anchor{cp/topics/contexts gccjit context}@anchor{fa}
10141 @deffn {C++ Class} gccjit::context
10142 @end deffn
10144 The top-level of the C++ API is the @pxref{fa,,gccjit;;context} type.
10146 A @pxref{fa,,gccjit;;context} instance encapsulates the state of a
10147 compilation.
10149 You can set up options on it, and add types, functions and code.
10150 Invoking @pxref{d3,,gccjit;;context;;compile()} on it gives you a
10151 @pxref{16,,gcc_jit_result *}.
10153 It is a thin wrapper around the C API's @pxref{8,,gcc_jit_context *}.
10155 @menu
10156 * Lifetime-management: Lifetime-management<2>. 
10157 * Thread-safety: Thread-safety<2>. 
10158 * Error-handling: Error-handling<3>. 
10159 * Debugging: Debugging<2>. 
10160 * Options: Options<4>. 
10162 @end menu
10164 @node Lifetime-management<2>,Thread-safety<2>,,Compilation contexts<2>
10165 @anchor{cp/topics/contexts lifetime-management}@anchor{fb}
10166 @subsubsection Lifetime-management
10169 Contexts are the unit of lifetime-management within the API: objects
10170 have their lifetime bounded by the context they are created within, and
10171 cleanup of such objects is done for you when the context is released.
10173 @geindex gccjit;;context;;acquire (C++ function)
10174 @anchor{cp/topics/contexts gccjit context acquire}@anchor{cd}
10175 @deffn {C++ Function} gccjit::context gccjit::context::acquire ()
10177 This function acquires a new @pxref{fa,,gccjit;;context} instance,
10178 which is independent of any others that may be present within this
10179 process.
10180 @end deffn
10182 @geindex gccjit;;context;;release (C++ function)
10183 @anchor{cp/topics/contexts gccjit context release}@anchor{cf}
10184 @deffn {C++ Function} void gccjit::context::release ()
10186 This function releases all resources associated with the given context.
10187 Both the context itself and all of its @code{gccjit::object *}
10188 instances are cleaned up.  It should be called exactly once on a given
10189 context.
10191 It is invalid to use the context or any of its "contextual" objects
10192 after calling this.
10194 @example
10195 ctxt.release ();
10196 @end example
10198 @noindent
10199 @end deffn
10201 @geindex gccjit;;context;;new_child_context (C++ function)
10202 @anchor{cp/topics/contexts gccjit context new_child_context}@anchor{fc}
10203 @deffn {C++ Function} gccjit::context gccjit::context::new_child_context ()
10205 Given an existing JIT context, create a child context.
10207 The child inherits a copy of all option-settings from the parent.
10209 The child can reference objects created within the parent, but not
10210 vice-versa.
10212 The lifetime of the child context must be bounded by that of the
10213 parent: you should release a child context before releasing the parent
10214 context.
10216 If you use a function from a parent context within a child context,
10217 you have to compile the parent context before you can compile the
10218 child context, and the gccjit::result of the parent context must
10219 outlive the gccjit::result of the child context.
10221 This allows caching of shared initializations.  For example, you could
10222 create types and declarations of global functions in a parent context
10223 once within a process, and then create child contexts whenever a
10224 function or loop becomes hot. Each such child context can be used for
10225 JIT-compiling just one function or loop, but can reference types
10226 and helper functions created within the parent context.
10228 Contexts can be arbitrarily nested, provided the above rules are
10229 followed, but it's probably not worth going above 2 or 3 levels, and
10230 there will likely be a performance hit for such nesting.
10231 @end deffn
10233 @node Thread-safety<2>,Error-handling<3>,Lifetime-management<2>,Compilation contexts<2>
10234 @anchor{cp/topics/contexts thread-safety}@anchor{fd}
10235 @subsubsection Thread-safety
10238 Instances of @pxref{fa,,gccjit;;context} created via
10239 @pxref{cd,,gccjit;;context;;acquire()} are independent from each other:
10240 only one thread may use a given context at once, but multiple threads
10241 could each have their own contexts without needing locks.
10243 Contexts created via @pxref{fc,,gccjit;;context;;new_child_context()} are
10244 related to their parent context.  They can be partitioned by their
10245 ultimate ancestor into independent "family trees".   Only one thread
10246 within a process may use a given "family tree" of such contexts at once,
10247 and if you're using multiple threads you should provide your own locking
10248 around entire such context partitions.
10250 @node Error-handling<3>,Debugging<2>,Thread-safety<2>,Compilation contexts<2>
10251 @anchor{cp/topics/contexts error-handling}@anchor{fe}
10252 @subsubsection Error-handling
10255 @c FIXME: How does error-handling work for C++ API?
10257 You can only compile and get code from a context if no errors occur.
10259 In general, if an error occurs when using an API entrypoint, it returns
10260 NULL.  You don't have to check everywhere for NULL results, since the
10261 API gracefully handles a NULL being passed in for any argument.
10263 Errors are printed on stderr and can be queried using
10264 @pxref{ff,,gccjit;;context;;get_first_error()}.
10266 @geindex gccjit;;context;;get_first_error (C++ function)
10267 @anchor{cp/topics/contexts gccjit context get_first_error__gccjit contextP}@anchor{ff}
10268 @deffn {C++ Function} const char* gccjit::context::get_first_error (gccjit::context* ctxt)
10270 Returns the first error message that occurred on the context.
10272 The returned string is valid for the rest of the lifetime of the
10273 context.
10275 If no errors occurred, this will be NULL.
10276 @end deffn
10278 @node Debugging<2>,Options<4>,Error-handling<3>,Compilation contexts<2>
10279 @anchor{cp/topics/contexts debugging}@anchor{100}
10280 @subsubsection Debugging
10283 @geindex gccjit;;context;;dump_to_file (C++ function)
10284 @anchor{cp/topics/contexts gccjit context dump_to_file__ssCR i}@anchor{101}
10285 @deffn {C++ Function} void gccjit::context::dump_to_file (const std::string& path, int update_locations)
10287 To help with debugging: dump a C-like representation to the given path,
10288 describing what's been set up on the context.
10290 If "update_locations" is true, then also set up @pxref{102,,gccjit;;location}
10291 information throughout the context, pointing at the dump file as if it
10292 were a source file.  This may be of use in conjunction with
10293 @code{GCCJIT::BOOL_OPTION_DEBUGINFO} to allow stepping through the
10294 code in a debugger.
10295 @end deffn
10297 @node Options<4>,,Debugging<2>,Compilation contexts<2>
10298 @anchor{cp/topics/contexts options}@anchor{103}
10299 @subsubsection Options
10302 @menu
10303 * String Options: String Options<2>. 
10304 * Boolean options: Boolean options<2>. 
10305 * Integer options: Integer options<2>. 
10307 @end menu
10309 @node String Options<2>,Boolean options<2>,,Options<4>
10310 @anchor{cp/topics/contexts string-options}@anchor{104}
10311 @subsubsection String Options
10314 @geindex gccjit;;context;;set_str_option (C++ function)
10315 @anchor{cp/topics/contexts gccjit context set_str_option__enum cCP}@anchor{105}
10316 @deffn {C++ Function} void gccjit::context::set_str_option (enum gcc_jit_str_option, const char* value)
10318 Set a string option of the context.
10320 This is a thin wrapper around the C API
10321 @pxref{59,,gcc_jit_context_set_str_option()}; the options have the same
10322 meaning.
10323 @end deffn
10325 @node Boolean options<2>,Integer options<2>,String Options<2>,Options<4>
10326 @anchor{cp/topics/contexts boolean-options}@anchor{106}
10327 @subsubsection Boolean options
10330 @geindex gccjit;;context;;set_bool_option (C++ function)
10331 @anchor{cp/topics/contexts gccjit context set_bool_option__enum i}@anchor{d5}
10332 @deffn {C++ Function} void gccjit::context::set_bool_option (enum gcc_jit_bool_option, int value)
10334 Set a boolean option of the context.
10336 This is a thin wrapper around the C API
10337 @pxref{1b,,gcc_jit_context_set_bool_option()}; the options have the same
10338 meaning.
10339 @end deffn
10341 @node Integer options<2>,,Boolean options<2>,Options<4>
10342 @anchor{cp/topics/contexts integer-options}@anchor{107}
10343 @subsubsection Integer options
10346 @geindex gccjit;;context;;set_int_option (C++ function)
10347 @anchor{cp/topics/contexts gccjit context set_int_option__enum i}@anchor{d6}
10348 @deffn {C++ Function} void gccjit::context::set_int_option (enum gcc_jit_int_option, int value)
10350 Set an integer option of the context.
10352 This is a thin wrapper around the C API
10353 @pxref{1e,,gcc_jit_context_set_int_option()}; the options have the same
10354 meaning.
10355 @end deffn
10357 @c Copyright (C) 2014 Free Software Foundation, Inc.
10358 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
10359 @c 
10360 @c This is free software: you can redistribute it and/or modify it
10361 @c under the terms of the GNU General Public License as published by
10362 @c the Free Software Foundation, either version 3 of the License, or
10363 @c (at your option) any later version.
10364 @c 
10365 @c This program is distributed in the hope that it will be useful, but
10366 @c WITHOUT ANY WARRANTY; without even the implied warranty of
10367 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10368 @c General Public License for more details.
10369 @c 
10370 @c You should have received a copy of the GNU General Public License
10371 @c along with this program.  If not, see
10372 @c <http://www.gnu.org/licenses/>.
10374 @node Objects<2>,Types<2>,Compilation contexts<2>,Topic Reference<2>
10375 @anchor{cp/topics/objects objects}@anchor{108}@anchor{cp/topics/objects doc}@anchor{109}
10376 @subsection Objects
10379 @geindex gccjit;;object (C++ class)
10380 @anchor{cp/topics/objects gccjit object}@anchor{10a}
10381 @deffn {C++ Class} gccjit::object
10382 @end deffn
10384 Almost every entity in the API (with the exception of
10385 @pxref{fa,,gccjit;;context} and @pxref{16,,gcc_jit_result *}) is a
10386 "contextual" object, a @pxref{10a,,gccjit;;object}.
10388 A JIT object:
10390 @quotation
10393 @itemize *
10395 @item 
10396 is associated with a @pxref{fa,,gccjit;;context}.
10398 @item 
10399 is automatically cleaned up for you when its context is released so
10400 you don't need to manually track and cleanup all objects, just the
10401 contexts.
10402 @end itemize
10403 @end quotation
10405 The C++ class hierarchy within the @code{gccjit} namespace looks like this:
10407 @example
10408 +- object
10409     +- location
10410     +- type
10411        +- struct
10412     +- field
10413     +- function
10414     +- block
10415     +- rvalue
10416         +- lvalue
10417            +- param
10418 @end example
10420 @noindent
10422 The @pxref{10a,,gccjit;;object} base class has the following operations:
10424 @geindex gccjit;;object;;get_context (C++ function)
10425 @anchor{cp/topics/objects gccjit object get_contextC}@anchor{10b}
10426 @deffn {C++ Function} gccjit::context gccjit::object::get_context () const
10428 Which context is the obj within?
10429 @end deffn
10431 @geindex gccjit;;object;;get_debug_string (C++ function)
10432 @anchor{cp/topics/objects gccjit object get_debug_stringC}@anchor{d0}
10433 @deffn {C++ Function} std::string gccjit::object::get_debug_string () const
10435 Generate a human-readable description for the given object.
10437 For example,
10439 @example
10440 printf ("obj: %s\n", obj.get_debug_string ().c_str ());
10441 @end example
10443 @noindent
10445 might give this text on stdout:
10447 @example
10448 obj: 4.0 * (float)i
10449 @end example
10451 @noindent
10452 @end deffn
10454 @c Copyright (C) 2014 Free Software Foundation, Inc.
10455 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
10456 @c 
10457 @c This is free software: you can redistribute it and/or modify it
10458 @c under the terms of the GNU General Public License as published by
10459 @c the Free Software Foundation, either version 3 of the License, or
10460 @c (at your option) any later version.
10461 @c 
10462 @c This program is distributed in the hope that it will be useful, but
10463 @c WITHOUT ANY WARRANTY; without even the implied warranty of
10464 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10465 @c General Public License for more details.
10466 @c 
10467 @c You should have received a copy of the GNU General Public License
10468 @c along with this program.  If not, see
10469 @c <http://www.gnu.org/licenses/>.
10471 @node Types<2>,Expressions<2>,Objects<2>,Topic Reference<2>
10472 @anchor{cp/topics/types doc}@anchor{10c}@anchor{cp/topics/types types}@anchor{10d}
10473 @subsection Types
10476 @geindex gccjit;;type (C++ class)
10477 @anchor{cp/topics/types gccjit type}@anchor{10e}
10478 @deffn {C++ Class} gccjit::type
10480 gccjit::type represents a type within the library.  It is a subclass
10481 of @pxref{10a,,gccjit;;object}.
10482 @end deffn
10484 Types can be created in several ways:
10487 @itemize *
10489 @item 
10490 fundamental types can be accessed using
10491 @pxref{ce,,gccjit;;context;;get_type()}:
10493 @example
10494 gccjit::type int_type = ctxt.get_type (GCC_JIT_TYPE_INT);
10495 @end example
10497 @noindent
10499 or using the @code{gccjit::context::get_int_type} template:
10501 @example
10502 gccjit::type t = ctxt.get_int_type <unsigned short> ();
10503 @end example
10505 @noindent
10507 See @pxref{b,,gcc_jit_context_get_type()} for the available types.
10509 @item 
10510 derived types can be accessed by using functions such as
10511 @pxref{10f,,gccjit;;type;;get_pointer()} and @pxref{110,,gccjit;;type;;get_const()}:
10513 @example
10514 gccjit::type const_int_star = int_type.get_const ().get_pointer ();
10515 gccjit::type int_const_star = int_type.get_pointer ().get_const ();
10516 @end example
10518 @noindent
10520 @item 
10521 by creating structures (see below).
10522 @end itemize
10524 @menu
10525 * Standard types: Standard types<2>. 
10526 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile<2>. 
10527 * Structures and unions: Structures and unions<2>. 
10529 @end menu
10531 @node Standard types<2>,Pointers const and volatile<2>,,Types<2>
10532 @anchor{cp/topics/types standard-types}@anchor{111}
10533 @subsubsection Standard types
10536 @geindex gccjit;;context;;get_type (C++ function)
10537 @anchor{cp/topics/types gccjit context get_type__enum}@anchor{ce}
10538 @deffn {C++ Function} gccjit::type gccjit::context::get_type (enum gcc_jit_types)
10540 Access a specific type.  This is a thin wrapper around
10541 @pxref{b,,gcc_jit_context_get_type()}; the parameter has the same meaning.
10542 @end deffn
10544 @geindex gccjit;;context;;get_int_type (C++ function)
10545 @anchor{cp/topics/types gccjit context get_int_type__s i}@anchor{112}
10546 @deffn {C++ Function} gccjit::type gccjit::context::get_int_type (size_t num_bytes, int is_signed)
10548 Access the integer type of the given size.
10549 @end deffn
10551 @geindex gccjit;;context;;get_int_type<T> (C++ function)
10552 @anchor{cp/topics/types gccjit context get_int_type T}@anchor{113}
10553 @deffn {C++ Function} gccjit::type gccjit::context::get_int_type<T> ()
10555 Access the given integer type.  For example, you could map the
10556 @code{unsigned short} type into a gccjit::type via:
10558 @example
10559 gccjit::type t = ctxt.get_int_type <unsigned short> ();
10560 @end example
10562 @noindent
10563 @end deffn
10565 @node Pointers const and volatile<2>,Structures and unions<2>,Standard types<2>,Types<2>
10566 @anchor{cp/topics/types pointers-const-and-volatile}@anchor{114}
10567 @subsubsection Pointers, @cite{const}, and @cite{volatile}
10570 @geindex gccjit;;type;;get_pointer (C++ function)
10571 @anchor{cp/topics/types gccjit type get_pointer}@anchor{10f}
10572 @deffn {C++ Function} gccjit::type gccjit::type::get_pointer ()
10574 Given type "T", get type "T*".
10575 @end deffn
10577 @c FIXME: get_const doesn't seem to exist
10579 @geindex gccjit;;type;;get_const (C++ function)
10580 @anchor{cp/topics/types gccjit type get_const}@anchor{110}
10581 @deffn {C++ Function} gccjit::type gccjit::type::get_const ()
10583 Given type "T", get type "const T".
10584 @end deffn
10586 @geindex gccjit;;type;;get_volatile (C++ function)
10587 @anchor{cp/topics/types gccjit type get_volatile}@anchor{115}
10588 @deffn {C++ Function} gccjit::type gccjit::type::get_volatile ()
10590 Given type "T", get type "volatile T".
10591 @end deffn
10593 @geindex gccjit;;context;;new_array_type (C++ function)
10594 @anchor{cp/topics/types gccjit context new_array_type__gccjit type i gccjit location}@anchor{116}
10595 @deffn {C++ Function} gccjit::type gccjit::context::new_array_type (gccjit::type element_type, int num_elements, gccjit::location loc)
10597 Given type "T", get type "T[N]" (for a constant N).
10598 Param "loc" is optional.
10599 @end deffn
10601 @node Structures and unions<2>,,Pointers const and volatile<2>,Types<2>
10602 @anchor{cp/topics/types structures-and-unions}@anchor{117}
10603 @subsubsection Structures and unions
10606 @geindex gccjit;;struct_ (C++ class)
10607 @anchor{cp/topics/types gccjit struct_}@anchor{118}
10608 @deffn {C++ Class} gccjit::struct_
10609 @end deffn
10611 A compound type analagous to a C @cite{struct}.
10613 @pxref{118,,gccjit;;struct_} is a subclass of @pxref{10e,,gccjit;;type} (and thus
10614 of @pxref{10a,,gccjit;;object} in turn).
10616 @geindex gccjit;;field (C++ class)
10617 @anchor{cp/topics/types gccjit field}@anchor{119}
10618 @deffn {C++ Class} gccjit::field
10619 @end deffn
10621 A field within a @pxref{118,,gccjit;;struct_}.
10623 @pxref{119,,gccjit;;field} is a subclass of @pxref{10a,,gccjit;;object}.
10625 You can model C @cite{struct} types by creating @pxref{118,,gccjit;;struct_} and
10626 @pxref{119,,gccjit;;field} instances, in either order:
10629 @itemize *
10631 @item 
10632 by creating the fields, then the structure.  For example, to model:
10634 @example
10635 struct coord @{double x; double y; @};
10636 @end example
10638 @noindent
10640 you could call:
10642 @example
10643 gccjit::field field_x = ctxt.new_field (double_type, "x");
10644 gccjit::field field_y = ctxt.new_field (double_type, "y");
10645 std::vector fields;
10646 fields.push_back (field_x);
10647 fields.push_back (field_y);
10648 gccjit::struct_ coord = ctxt.new_struct_type ("coord", fields);
10649 @end example
10651 @noindent
10653 @item 
10654 by creating the structure, then populating it with fields, typically
10655 to allow modelling self-referential structs such as:
10657 @example
10658 struct node @{ int m_hash; struct node *m_next; @};
10659 @end example
10661 @noindent
10663 like this:
10665 @example
10666 gccjit::struct_ node = ctxt.new_opaque_struct_type ("node");
10667 gccjit::type node_ptr = node.get_pointer ();
10668 gccjit::field field_hash = ctxt.new_field (int_type, "m_hash");
10669 gccjit::field field_next = ctxt.new_field (node_ptr, "m_next");
10670 std::vector fields;
10671 fields.push_back (field_hash);
10672 fields.push_back (field_next);
10673 node.set_fields (fields);
10674 @end example
10676 @noindent
10677 @end itemize
10679 @c FIXME: the above API doesn't seem to exist yet
10681 @geindex gccjit;;context;;new_field (C++ function)
10682 @anchor{cp/topics/types gccjit context new_field__gccjit type cCP gccjit location}@anchor{11a}
10683 @deffn {C++ Function} gccjit::field gccjit::context::new_field (gccjit::type type, const char* name, gccjit::location loc)
10685 Construct a new field, with the given type and name.
10686 @end deffn
10688 @geindex gccjit;;context;;new_struct_type (C++ function)
10689 @anchor{cp/topics/types gccjit context new_struct_type__ssCR std vector field R gccjit location}@anchor{11b}
10690 @deffn {C++ Function} gccjit::struct_ gccjit::context::new_struct_type (const std::string& name, std::vector<field>& fields, gccjit::location loc)
10692 @quotation
10694 Construct a new struct type, with the given name and fields.
10695 @end quotation
10696 @end deffn
10698 @geindex gccjit;;context;;new_opaque_struct (C++ function)
10699 @anchor{cp/topics/types gccjit context new_opaque_struct__ssCR gccjit location}@anchor{11c}
10700 @deffn {C++ Function} gccjit::struct_ gccjit::context::new_opaque_struct (const std::string& name, gccjit::location loc)
10702 Construct a new struct type, with the given name, but without
10703 specifying the fields.   The fields can be omitted (in which case the
10704 size of the struct is not known), or later specified using
10705 @pxref{78,,gcc_jit_struct_set_fields()}.
10706 @end deffn
10708 @c Copyright (C) 2014 Free Software Foundation, Inc.
10709 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
10710 @c 
10711 @c This is free software: you can redistribute it and/or modify it
10712 @c under the terms of the GNU General Public License as published by
10713 @c the Free Software Foundation, either version 3 of the License, or
10714 @c (at your option) any later version.
10715 @c 
10716 @c This program is distributed in the hope that it will be useful, but
10717 @c WITHOUT ANY WARRANTY; without even the implied warranty of
10718 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
10719 @c General Public License for more details.
10720 @c 
10721 @c You should have received a copy of the GNU General Public License
10722 @c along with this program.  If not, see
10723 @c <http://www.gnu.org/licenses/>.
10725 @node Expressions<2>,Creating and using functions<2>,Types<2>,Topic Reference<2>
10726 @anchor{cp/topics/expressions expressions}@anchor{11d}@anchor{cp/topics/expressions doc}@anchor{11e}
10727 @subsection Expressions
10730 @menu
10731 * Rvalues: Rvalues<2>. 
10732 * Lvalues: Lvalues<2>. 
10733 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions<2>. 
10735 Rvalues
10737 * Simple expressions: Simple expressions<2>. 
10738 * Unary Operations: Unary Operations<2>. 
10739 * Binary Operations: Binary Operations<2>. 
10740 * Comparisons: Comparisons<2>. 
10741 * Function calls: Function calls<2>. 
10742 * Type-coercion: Type-coercion<2>. 
10744 Lvalues
10746 * Global variables: Global variables<2>. 
10748 @end menu
10751 @node Rvalues<2>,Lvalues<2>,,Expressions<2>
10752 @anchor{cp/topics/expressions rvalues}@anchor{11f}
10753 @subsubsection Rvalues
10756 @geindex gccjit;;rvalue (C++ class)
10757 @anchor{cp/topics/expressions gccjit rvalue}@anchor{120}
10758 @deffn {C++ Class} gccjit::rvalue
10759 @end deffn
10761 A @pxref{120,,gccjit;;rvalue} is an expression that can be computed.  It is a
10762 subclass of @pxref{10a,,gccjit;;object}, and is a thin wrapper around
10763 @pxref{13,,gcc_jit_rvalue *} from the C API.
10765 It can be simple, e.g.:
10767 @quotation
10770 @itemize *
10772 @item 
10773 an integer value e.g. @cite{0} or @cite{42}
10775 @item 
10776 a string literal e.g. @cite{"Hello world"}
10778 @item 
10779 a variable e.g. @cite{i}.  These are also lvalues (see below).
10780 @end itemize
10781 @end quotation
10783 or compound e.g.:
10785 @quotation
10788 @itemize *
10790 @item 
10791 a unary expression e.g. @cite{!cond}
10793 @item 
10794 a binary expression e.g. @cite{(a + b)}
10796 @item 
10797 a function call e.g. @cite{get_distance (&player_ship@comma{} &target)}
10799 @item 
10800 etc.
10801 @end itemize
10802 @end quotation
10804 Every rvalue has an associated type, and the API will check to ensure
10805 that types match up correctly (otherwise the context will emit an error).
10807 @geindex gccjit;;rvalue;;get_type (C++ function)
10808 @anchor{cp/topics/expressions gccjit rvalue get_type}@anchor{121}
10809 @deffn {C++ Function} gccjit::type gccjit::rvalue::get_type ()
10811 Get the type of this rvalue.
10812 @end deffn
10814 @menu
10815 * Simple expressions: Simple expressions<2>. 
10816 * Unary Operations: Unary Operations<2>. 
10817 * Binary Operations: Binary Operations<2>. 
10818 * Comparisons: Comparisons<2>. 
10819 * Function calls: Function calls<2>. 
10820 * Type-coercion: Type-coercion<2>. 
10822 @end menu
10824 @node Simple expressions<2>,Unary Operations<2>,,Rvalues<2>
10825 @anchor{cp/topics/expressions simple-expressions}@anchor{122}
10826 @subsubsection Simple expressions
10829 @geindex gccjit;;context;;new_rvalue (C++ function)
10830 @anchor{cp/topics/expressions gccjit context new_rvalue__gccjit type iC}@anchor{e2}
10831 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (gccjit::type numeric_type, int value) const
10833 Given a numeric type (integer or floating point), build an rvalue for
10834 the given constant @code{int} value.
10835 @end deffn
10837 @geindex gccjit;;context;;zero (C++ function)
10838 @anchor{cp/topics/expressions gccjit context zero__gccjit typeC}@anchor{de}
10839 @deffn {C++ Function} gccjit::rvalue gccjit::context::zero (gccjit::type numeric_type) const
10841 Given a numeric type (integer or floating point), get the rvalue for
10842 zero.  Essentially this is just a shortcut for:
10844 @example
10845 ctxt.new_rvalue (numeric_type, 0)
10846 @end example
10848 @noindent
10849 @end deffn
10851 @geindex gccjit;;context;;one (C++ function)
10852 @anchor{cp/topics/expressions gccjit context one__gccjit typeC}@anchor{123}
10853 @deffn {C++ Function} gccjit::rvalue gccjit::context::one (gccjit::type numeric_type) const
10855 Given a numeric type (integer or floating point), get the rvalue for
10856 zero.  Essentially this is just a shortcut for:
10858 @example
10859 ctxt.new_rvalue (numeric_type, 1)
10860 @end example
10862 @noindent
10863 @end deffn
10865 @geindex gccjit;;context;;new_rvalue (C++ function)
10866 @anchor{cp/topics/expressions gccjit context new_rvalue__gccjit type doubleC}@anchor{124}
10867 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (gccjit::type numeric_type, double value) const
10869 Given a numeric type (integer or floating point), build an rvalue for
10870 the given constant value.
10871 @end deffn
10873 @geindex gccjit;;context;;new_rvalue (C++ function)
10874 @anchor{cp/topics/expressions gccjit context new_rvalue__gccjit type voidPC}@anchor{125}
10875 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (gccjit::type pointer_type, void* value) const
10877 Given a pointer type, build an rvalue for the given address.
10878 @end deffn
10880 @geindex gccjit;;context;;new_rvalue (C++ function)
10881 @anchor{cp/topics/expressions gccjit context new_rvalue__ssCRC}@anchor{126}
10882 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (const std::string& value) const
10884 Generate an rvalue of type @code{GCC_JIT_TYPE_CONST_CHAR_PTR} for
10885 the given string.  This is akin to a string literal.
10886 @end deffn
10888 @node Unary Operations<2>,Binary Operations<2>,Simple expressions<2>,Rvalues<2>
10889 @anchor{cp/topics/expressions unary-operations}@anchor{127}
10890 @subsubsection Unary Operations
10893 @geindex gccjit;;context;;new_unary_op (C++ function)
10894 @anchor{cp/topics/expressions gccjit context new_unary_op__enum gccjit type gccjit rvalue gccjit location}@anchor{128}
10895 @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)
10897 Build a unary operation out of an input rvalue.
10899 Parameter @code{loc} is optional.
10901 This is a thin wrapper around the C API's
10902 @pxref{83,,gcc_jit_context_new_unary_op()} and the available unary
10903 operations are documented there.
10904 @end deffn
10906 There are shorter ways to spell the various specific kinds of unary
10907 operation:
10909 @geindex gccjit;;context;;new_minus (C++ function)
10910 @anchor{cp/topics/expressions gccjit context new_minus__gccjit type gccjit rvalue gccjit location}@anchor{129}
10911 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_minus (gccjit::type result_type, gccjit::rvalue a, gccjit::location loc)
10913 Negate an arithmetic value; for example:
10915 @example
10916 gccjit::rvalue negpi = ctxt.new_minus (t_double, pi);
10917 @end example
10919 @noindent
10921 builds the equivalent of this C expression:
10923 @example
10925 @end example
10927 @noindent
10928 @end deffn
10930 @geindex new_bitwise_negate (C++ function)
10931 @anchor{cp/topics/expressions new_bitwise_negate__gccjit type gccjit rvalue gccjit location}@anchor{12a}
10932 @deffn {C++ Function} gccjit::rvalue new_bitwise_negate (gccjit::type result_type, gccjit::rvalue a, gccjit::location loc)
10934 Bitwise negation of an integer value (one's complement); for example:
10936 @example
10937 gccjit::rvalue mask = ctxt.new_bitwise_negate (t_int, a);
10938 @end example
10940 @noindent
10942 builds the equivalent of this C expression:
10944 @example
10946 @end example
10948 @noindent
10949 @end deffn
10951 @geindex new_logical_negate (C++ function)
10952 @anchor{cp/topics/expressions new_logical_negate__gccjit type gccjit rvalue gccjit location}@anchor{12b}
10953 @deffn {C++ Function} gccjit::rvalue new_logical_negate (gccjit::type result_type, gccjit::rvalue a, gccjit::location loc)
10955 Logical negation of an arithmetic or pointer value; for example:
10957 @example
10958 gccjit::rvalue guard = ctxt.new_logical_negate (t_bool, cond);
10959 @end example
10961 @noindent
10963 builds the equivalent of this C expression:
10965 @example
10966 !cond
10967 @end example
10969 @noindent
10970 @end deffn
10972 The most concise way to spell them is with overloaded operators:
10974 @geindex operator- (C++ function)
10975 @anchor{cp/topics/expressions sub-operator__gccjit rvalue}@anchor{12c}
10976 @deffn {C++ Function} gccjit::rvalue operator- (gccjit::rvalue a)
10978 @example
10979 gccjit::rvalue negpi = -pi;
10980 @end example
10982 @noindent
10983 @end deffn
10985 @geindex operator~ (C++ function)
10986 @anchor{cp/topics/expressions inv-operator__gccjit rvalue}@anchor{12d}
10987 @deffn {C++ Function} gccjit::rvalue operator~ (gccjit::rvalue a)
10989 @example
10990 gccjit::rvalue mask = ~a;
10991 @end example
10993 @noindent
10994 @end deffn
10996 @geindex operator! (C++ function)
10997 @anchor{cp/topics/expressions not-operator__gccjit rvalue}@anchor{12e}
10998 @deffn {C++ Function} gccjit::rvalue operator! (gccjit::rvalue a)
11000 @example
11001 gccjit::rvalue guard = !cond;
11002 @end example
11004 @noindent
11005 @end deffn
11007 @node Binary Operations<2>,Comparisons<2>,Unary Operations<2>,Rvalues<2>
11008 @anchor{cp/topics/expressions binary-operations}@anchor{12f}
11009 @subsubsection Binary Operations
11012 @geindex gccjit;;context;;new_binary_op (C++ function)
11013 @anchor{cp/topics/expressions gccjit context new_binary_op__enum gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{d2}
11014 @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)
11016 Build a binary operation out of two constituent rvalues.
11018 Parameter @code{loc} is optional.
11020 This is a thin wrapper around the C API's
11021 @pxref{12,,gcc_jit_context_new_binary_op()} and the available binary
11022 operations are documented there.
11023 @end deffn
11025 There are shorter ways to spell the various specific kinds of binary
11026 operation:
11028 @geindex gccjit;;context;;new_plus (C++ function)
11029 @anchor{cp/topics/expressions gccjit context new_plus__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{130}
11030 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_plus (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11031 @end deffn
11033 @geindex gccjit;;context;;new_minus (C++ function)
11034 @anchor{cp/topics/expressions gccjit context new_minus__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{131}
11035 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_minus (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11036 @end deffn
11038 @geindex gccjit;;context;;new_mult (C++ function)
11039 @anchor{cp/topics/expressions gccjit context new_mult__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{132}
11040 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_mult (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11041 @end deffn
11043 @geindex gccjit;;context;;new_divide (C++ function)
11044 @anchor{cp/topics/expressions gccjit context new_divide__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{133}
11045 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_divide (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11046 @end deffn
11048 @geindex gccjit;;context;;new_modulo (C++ function)
11049 @anchor{cp/topics/expressions gccjit context new_modulo__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{134}
11050 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_modulo (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11051 @end deffn
11053 @geindex gccjit;;context;;new_bitwise_and (C++ function)
11054 @anchor{cp/topics/expressions gccjit context new_bitwise_and__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{135}
11055 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_bitwise_and (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11056 @end deffn
11058 @geindex gccjit;;context;;new_bitwise_xor (C++ function)
11059 @anchor{cp/topics/expressions gccjit context new_bitwise_xor__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{136}
11060 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_bitwise_xor (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11061 @end deffn
11063 @geindex gccjit;;context;;new_bitwise_or (C++ function)
11064 @anchor{cp/topics/expressions gccjit context new_bitwise_or__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{137}
11065 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_bitwise_or (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11066 @end deffn
11068 @geindex gccjit;;context;;new_logical_and (C++ function)
11069 @anchor{cp/topics/expressions gccjit context new_logical_and__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{138}
11070 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_logical_and (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11071 @end deffn
11073 @geindex gccjit;;context;;new_logical_or (C++ function)
11074 @anchor{cp/topics/expressions gccjit context new_logical_or__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{139}
11075 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_logical_or (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11076 @end deffn
11078 The most concise way to spell them is with overloaded operators:
11080 @geindex operator+ (C++ function)
11081 @anchor{cp/topics/expressions add-operator__gccjit rvalue gccjit rvalue}@anchor{13a}
11082 @deffn {C++ Function} gccjit::rvalue operator+ (gccjit::rvalue a, gccjit::rvalue b)
11084 @example
11085 gccjit::rvalue sum = a + b;
11086 @end example
11088 @noindent
11089 @end deffn
11091 @geindex operator- (C++ function)
11092 @anchor{cp/topics/expressions sub-operator__gccjit rvalue gccjit rvalue}@anchor{13b}
11093 @deffn {C++ Function} gccjit::rvalue operator- (gccjit::rvalue a, gccjit::rvalue b)
11095 @example
11096 gccjit::rvalue diff = a - b;
11097 @end example
11099 @noindent
11100 @end deffn
11102 @geindex operator* (C++ function)
11103 @anchor{cp/topics/expressions mul-operator__gccjit rvalue gccjit rvalue}@anchor{13c}
11104 @deffn {C++ Function} gccjit::rvalue operator* (gccjit::rvalue a, gccjit::rvalue b)
11106 @example
11107 gccjit::rvalue prod = a * b;
11108 @end example
11110 @noindent
11111 @end deffn
11113 @geindex operator/ (C++ function)
11114 @anchor{cp/topics/expressions div-operator__gccjit rvalue gccjit rvalue}@anchor{13d}
11115 @deffn {C++ Function} gccjit::rvalue operator/ (gccjit::rvalue a, gccjit::rvalue b)
11117 @example
11118 gccjit::rvalue result = a / b;
11119 @end example
11121 @noindent
11122 @end deffn
11124 @geindex operator% (C++ function)
11125 @anchor{cp/topics/expressions mod-operator__gccjit rvalue gccjit rvalue}@anchor{13e}
11126 @deffn {C++ Function} gccjit::rvalue operator% (gccjit::rvalue a, gccjit::rvalue b)
11128 @example
11129 gccjit::rvalue mod = a % b;
11130 @end example
11132 @noindent
11133 @end deffn
11135 @geindex operator& (C++ function)
11136 @anchor{cp/topics/expressions and-operator__gccjit rvalue gccjit rvalue}@anchor{13f}
11137 @deffn {C++ Function} gccjit::rvalue operator& (gccjit::rvalue a, gccjit::rvalue b)
11139 @example
11140 gccjit::rvalue x = a & b;
11141 @end example
11143 @noindent
11144 @end deffn
11146 @geindex operator^ (C++ function)
11147 @anchor{cp/topics/expressions xor-operator__gccjit rvalue gccjit rvalue}@anchor{140}
11148 @deffn {C++ Function} gccjit::rvalue operator^ (gccjit::rvalue a, gccjit::rvalue b)
11150 @example
11151 gccjit::rvalue x = a ^ b;
11152 @end example
11154 @noindent
11155 @end deffn
11157 @geindex operator| (C++ function)
11158 @anchor{cp/topics/expressions or-operator__gccjit rvalue gccjit rvalue}@anchor{141}
11159 @deffn {C++ Function} gccjit::rvalue operator| (gccjit::rvalue a, gccjit::rvalue b)
11161 @example
11162 gccjit::rvalue x = a | b;
11163 @end example
11165 @noindent
11166 @end deffn
11168 @geindex operator&& (C++ function)
11169 @anchor{cp/topics/expressions sand-operator__gccjit rvalue gccjit rvalue}@anchor{142}
11170 @deffn {C++ Function} gccjit::rvalue operator&& (gccjit::rvalue a, gccjit::rvalue b)
11172 @example
11173 gccjit::rvalue cond = a && b;
11174 @end example
11176 @noindent
11177 @end deffn
11179 @geindex operator|| (C++ function)
11180 @anchor{cp/topics/expressions sor-operator__gccjit rvalue gccjit rvalue}@anchor{143}
11181 @deffn {C++ Function} gccjit::rvalue operator|| (gccjit::rvalue a, gccjit::rvalue b)
11183 @example
11184 gccjit::rvalue cond = a || b;
11185 @end example
11187 @noindent
11188 @end deffn
11190 These can of course be combined, giving a terse way to build compound
11191 expressions:
11193 @quotation
11195 @example
11196 gccjit::rvalue discriminant = (b * b) - (four * a * c);
11197 @end example
11199 @noindent
11200 @end quotation
11202 @node Comparisons<2>,Function calls<2>,Binary Operations<2>,Rvalues<2>
11203 @anchor{cp/topics/expressions comparisons}@anchor{144}
11204 @subsubsection Comparisons
11207 @geindex gccjit;;context;;new_comparison (C++ function)
11208 @anchor{cp/topics/expressions gccjit context new_comparison__enum gccjit rvalue gccjit rvalue gccjit location}@anchor{df}
11209 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_comparison (enum gcc_jit_comparison, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11211 Build a boolean rvalue out of the comparison of two other rvalues.
11213 Parameter @code{loc} is optional.
11215 This is a thin wrapper around the C API's
11216 @pxref{2c,,gcc_jit_context_new_comparison()} and the available kinds
11217 of comparison are documented there.
11218 @end deffn
11220 There are shorter ways to spell the various specific kinds of binary
11221 operation:
11223 @geindex gccjit;;context;;new_eq (C++ function)
11224 @anchor{cp/topics/expressions gccjit context new_eq__gccjit rvalue gccjit rvalue gccjit location}@anchor{145}
11225 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_eq (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11226 @end deffn
11228 @geindex gccjit;;context;;new_ne (C++ function)
11229 @anchor{cp/topics/expressions gccjit context new_ne__gccjit rvalue gccjit rvalue gccjit location}@anchor{146}
11230 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_ne (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11231 @end deffn
11233 @geindex gccjit;;context;;new_lt (C++ function)
11234 @anchor{cp/topics/expressions gccjit context new_lt__gccjit rvalue gccjit rvalue gccjit location}@anchor{147}
11235 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_lt (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11236 @end deffn
11238 @geindex gccjit;;context;;new_le (C++ function)
11239 @anchor{cp/topics/expressions gccjit context new_le__gccjit rvalue gccjit rvalue gccjit location}@anchor{148}
11240 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_le (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11241 @end deffn
11243 @geindex gccjit;;context;;new_gt (C++ function)
11244 @anchor{cp/topics/expressions gccjit context new_gt__gccjit rvalue gccjit rvalue gccjit location}@anchor{149}
11245 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_gt (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11246 @end deffn
11248 @geindex gccjit;;context;;new_ge (C++ function)
11249 @anchor{cp/topics/expressions gccjit context new_ge__gccjit rvalue gccjit rvalue gccjit location}@anchor{14a}
11250 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_ge (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11251 @end deffn
11253 The most concise way to spell them is with overloaded operators:
11255 @geindex operator== (C++ function)
11256 @anchor{cp/topics/expressions eq-operator__gccjit rvalue gccjit rvalue}@anchor{14b}
11257 @deffn {C++ Function} gccjit::rvalue operator== (gccjit::rvalue a, gccjit::rvalue b)
11259 @example
11260 gccjit::rvalue cond = (a == ctxt.zero (t_int));
11261 @end example
11263 @noindent
11264 @end deffn
11266 @geindex operator!= (C++ function)
11267 @anchor{cp/topics/expressions neq-operator__gccjit rvalue gccjit rvalue}@anchor{14c}
11268 @deffn {C++ Function} gccjit::rvalue operator!= (gccjit::rvalue a, gccjit::rvalue b)
11270 @example
11271 gccjit::rvalue cond = (i != j);
11272 @end example
11274 @noindent
11275 @end deffn
11277 @geindex operator< (C++ function)
11278 @anchor{cp/topics/expressions lt-operator__gccjit rvalue gccjit rvalue}@anchor{14d}
11279 @deffn {C++ Function} gccjit::rvalue operator< (gccjit::rvalue a, gccjit::rvalue b)
11281 @example
11282 gccjit::rvalue cond = i < n;
11283 @end example
11285 @noindent
11286 @end deffn
11288 @geindex operator<= (C++ function)
11289 @anchor{cp/topics/expressions lte-operator__gccjit rvalue gccjit rvalue}@anchor{14e}
11290 @deffn {C++ Function} gccjit::rvalue operator<= (gccjit::rvalue a, gccjit::rvalue b)
11292 @example
11293 gccjit::rvalue cond = i <= n;
11294 @end example
11296 @noindent
11297 @end deffn
11299 @geindex operator> (C++ function)
11300 @anchor{cp/topics/expressions gt-operator__gccjit rvalue gccjit rvalue}@anchor{14f}
11301 @deffn {C++ Function} gccjit::rvalue operator> (gccjit::rvalue a, gccjit::rvalue b)
11303 @example
11304 gccjit::rvalue cond = (ch > limit);
11305 @end example
11307 @noindent
11308 @end deffn
11310 @geindex operator>= (C++ function)
11311 @anchor{cp/topics/expressions gte-operator__gccjit rvalue gccjit rvalue}@anchor{150}
11312 @deffn {C++ Function} gccjit::rvalue operator>= (gccjit::rvalue a, gccjit::rvalue b)
11314 @example
11315 gccjit::rvalue cond = (score >= ctxt.new_rvalue (t_int, 100));
11316 @end example
11318 @noindent
11319 @end deffn
11321 @c TODO: beyond this point
11323 @node Function calls<2>,Type-coercion<2>,Comparisons<2>,Rvalues<2>
11324 @anchor{cp/topics/expressions function-calls}@anchor{151}
11325 @subsubsection Function calls
11328 @geindex gcc_jit_context_new_call (C++ function)
11329 @anchor{cp/topics/expressions gcc_jit_context_new_call__gcc_jit_contextP gcc_jit_locationP gcc_jit_functionP i gcc_jit_rvaluePP}@anchor{152}
11330 @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)
11332 Given a function and the given table of argument rvalues, construct a
11333 call to the function, with the result as an rvalue.
11335 @cartouche
11336 @quotation Note 
11337 @code{gccjit::context::new_call()} merely builds a
11338 @pxref{120,,gccjit;;rvalue} i.e. an expression that can be evaluated,
11339 perhaps as part of a more complicated expression.
11340 The call @emph{won't} happen unless you add a statement to a function
11341 that evaluates the expression.
11343 For example, if you want to call a function and discard the result
11344 (or to call a function with @code{void} return type), use
11345 @pxref{153,,gccjit;;block;;add_eval()}:
11347 @example
11348 /* Add "(void)printf (arg0, arg1);".  */
11349 block.add_eval (ctxt.new_call (printf_func, arg0, arg1));
11350 @end example
11352 @noindent
11353 @end quotation
11354 @end cartouche
11355 @end deffn
11357 @node Type-coercion<2>,,Function calls<2>,Rvalues<2>
11358 @anchor{cp/topics/expressions type-coercion}@anchor{154}
11359 @subsubsection Type-coercion
11362 @geindex gccjit;;context;;new_cast (C++ function)
11363 @anchor{cp/topics/expressions gccjit context new_cast__gccjit rvalue gccjit type gccjit location}@anchor{155}
11364 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_cast (gccjit::rvalue rvalue, gccjit::type type, gccjit::location loc)
11366 Given an rvalue of T, construct another rvalue of another type.
11368 Currently only a limited set of conversions are possible:
11370 @quotation
11373 @itemize *
11375 @item 
11376 int <-> float
11378 @item 
11379 int <-> bool
11381 @item 
11382 P*  <-> Q*, for pointer types P and Q
11383 @end itemize
11384 @end quotation
11385 @end deffn
11387 @node Lvalues<2>,Working with pointers structs and unions<2>,Rvalues<2>,Expressions<2>
11388 @anchor{cp/topics/expressions lvalues}@anchor{156}
11389 @subsubsection Lvalues
11392 @geindex gccjit;;lvalue (C++ class)
11393 @anchor{cp/topics/expressions gccjit lvalue}@anchor{157}
11394 @deffn {C++ Class} gccjit::lvalue
11395 @end deffn
11397 An lvalue is something that can of the @emph{left}-hand side of an assignment:
11398 a storage area (such as a variable).  It is a subclass of
11399 @pxref{120,,gccjit;;rvalue}, where the rvalue is computed by reading from the
11400 storage area.
11402 It iss a thin wrapper around @pxref{24,,gcc_jit_lvalue *} from the C API.
11404 @geindex gccjit;;lvalue;;get_address (C++ function)
11405 @anchor{cp/topics/expressions gccjit lvalue get_address__gccjit location}@anchor{158}
11406 @deffn {C++ Function} gccjit::rvalue gccjit::lvalue::get_address (gccjit::location loc)
11408 Take the address of an lvalue; analogous to:
11410 @example
11411 &(EXPR)
11412 @end example
11414 @noindent
11416 in C.
11418 Parameter "loc" is optional.
11419 @end deffn
11421 @menu
11422 * Global variables: Global variables<2>. 
11424 @end menu
11426 @node Global variables<2>,,,Lvalues<2>
11427 @anchor{cp/topics/expressions global-variables}@anchor{159}
11428 @subsubsection Global variables
11431 @geindex gccjit;;context;;new_global (C++ function)
11432 @anchor{cp/topics/expressions gccjit context new_global__gccjit type cCP gccjit location}@anchor{15a}
11433 @deffn {C++ Function} gccjit::lvalue gccjit::context::new_global (gccjit::type type, const char* name, gccjit::location loc)
11435 Add a new global variable of the given type and name to the context.
11436 @end deffn
11438 @node Working with pointers structs and unions<2>,,Lvalues<2>,Expressions<2>
11439 @anchor{cp/topics/expressions working-with-pointers-structs-and-unions}@anchor{15b}
11440 @subsubsection Working with pointers, structs and unions
11443 @geindex gccjit;;rvalue;;dereference (C++ function)
11444 @anchor{cp/topics/expressions gccjit rvalue dereference__gccjit location}@anchor{15c}
11445 @deffn {C++ Function} gccjit::lvalue gccjit::rvalue::dereference (gccjit::location loc)
11447 Given an rvalue of pointer type @code{T *}, dereferencing the pointer,
11448 getting an lvalue of type @code{T}.  Analogous to:
11450 @example
11451 *(EXPR)
11452 @end example
11454 @noindent
11456 in C.
11458 Parameter "loc" is optional.
11459 @end deffn
11461 If you don't need to specify the location, this can also be expressed using
11462 an overloaded operator:
11465 @deffn {C++ Function} gccjit::lvalue            gccjit::rvalue::operator* ();
11467 @example
11468 gccjit::lvalue content = *ptr;
11469 @end example
11471 @noindent
11472 @end deffn
11474 Field access is provided separately for both lvalues and rvalues:
11476 @geindex gccjit;;lvalue;;access_field (C++ function)
11477 @anchor{cp/topics/expressions gccjit lvalue access_field__gccjit field gccjit location}@anchor{15d}
11478 @deffn {C++ Function} gccjit::lvalue gccjit::lvalue::access_field (gccjit::field field, gccjit::location loc)
11480 Given an lvalue of struct or union type, access the given field,
11481 getting an lvalue of the field's type.  Analogous to:
11483 @example
11484 (EXPR).field = ...;
11485 @end example
11487 @noindent
11489 in C.
11490 @end deffn
11492 @geindex gccjit;;rvalue;;access_field (C++ function)
11493 @anchor{cp/topics/expressions gccjit rvalue access_field__gccjit field gccjit location}@anchor{15e}
11494 @deffn {C++ Function} gccjit::rvalue gccjit::rvalue::access_field (gccjit::field field, gccjit::location loc)
11496 Given an rvalue of struct or union type, access the given field
11497 as an rvalue.  Analogous to:
11499 @example
11500 (EXPR).field
11501 @end example
11503 @noindent
11505 in C.
11506 @end deffn
11508 @geindex gccjit;;rvalue;;dereference_field (C++ function)
11509 @anchor{cp/topics/expressions gccjit rvalue dereference_field__gccjit field gccjit location}@anchor{15f}
11510 @deffn {C++ Function} gccjit::lvalue gccjit::rvalue::dereference_field (gccjit::field field, gccjit::location loc)
11512 Given an rvalue of pointer type @code{T *} where T is of struct or union
11513 type, access the given field as an lvalue.  Analogous to:
11515 @example
11516 (EXPR)->field
11517 @end example
11519 @noindent
11521 in C, itself equivalent to @code{(*EXPR).FIELD}.
11522 @end deffn
11524 @geindex gccjit;;context;;new_array_access (C++ function)
11525 @anchor{cp/topics/expressions gccjit context new_array_access__gccjit rvalue gccjit rvalue gccjit location}@anchor{160}
11526 @deffn {C++ Function} gccjit::lvalue gccjit::context::new_array_access (gccjit::rvalue ptr, gccjit::rvalue index, gccjit::location loc)
11528 Given an rvalue of pointer type @code{T *}, get at the element @cite{T} at
11529 the given index, using standard C array indexing rules i.e. each
11530 increment of @code{index} corresponds to @code{sizeof(T)} bytes.
11531 Analogous to:
11533 @example
11534 PTR[INDEX]
11535 @end example
11537 @noindent
11539 in C (or, indeed, to @code{PTR + INDEX}).
11541 Parameter "loc" is optional.
11542 @end deffn
11544 For array accesses where you don't need to specify a @pxref{102,,gccjit;;location},
11545 two overloaded operators are available:
11547 @quotation
11549 gccjit::lvalue gccjit::rvalue::operator[] (gccjit::rvalue index)
11551 @example
11552 gccjit::lvalue element = array[idx];
11553 @end example
11555 @noindent
11557 gccjit::lvalue gccjit::rvalue::operator[] (int index)
11559 @example
11560 gccjit::lvalue element = array[0];
11561 @end example
11563 @noindent
11564 @end quotation
11566 @c Copyright (C) 2014 Free Software Foundation, Inc.
11567 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
11568 @c 
11569 @c This is free software: you can redistribute it and/or modify it
11570 @c under the terms of the GNU General Public License as published by
11571 @c the Free Software Foundation, either version 3 of the License, or
11572 @c (at your option) any later version.
11573 @c 
11574 @c This program is distributed in the hope that it will be useful, but
11575 @c WITHOUT ANY WARRANTY; without even the implied warranty of
11576 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11577 @c General Public License for more details.
11578 @c 
11579 @c You should have received a copy of the GNU General Public License
11580 @c along with this program.  If not, see
11581 @c <http://www.gnu.org/licenses/>.
11583 @node Creating and using functions<2>,Source Locations<2>,Expressions<2>,Topic Reference<2>
11584 @anchor{cp/topics/functions doc}@anchor{161}@anchor{cp/topics/functions creating-and-using-functions}@anchor{162}
11585 @subsection Creating and using functions
11588 @menu
11589 * Params: Params<2>. 
11590 * Functions: Functions<2>. 
11591 * Blocks: Blocks<2>. 
11592 * Statements: Statements<2>. 
11594 @end menu
11596 @node Params<2>,Functions<2>,,Creating and using functions<2>
11597 @anchor{cp/topics/functions params}@anchor{163}
11598 @subsubsection Params
11601 @geindex gccjit;;param (C++ class)
11602 @anchor{cp/topics/functions gccjit param}@anchor{164}
11603 @deffn {C++ Class} gccjit::param
11605 A @cite{gccjit::param} represents a parameter to a function.
11606 @end deffn
11608 @geindex gccjit;;context;;new_param (C++ function)
11609 @anchor{cp/topics/functions gccjit context new_param__gccjit type cCP gccjit location}@anchor{d1}
11610 @deffn {C++ Function} gccjit::param gccjit::context::new_param (gccjit::type type, const char* name, gccjit::location loc)
11612 In preparation for creating a function, create a new parameter of the
11613 given type and name.
11614 @end deffn
11616 @pxref{164,,gccjit;;param} is a subclass of @pxref{157,,gccjit;;lvalue} (and thus
11617 of @pxref{120,,gccjit;;rvalue} and @pxref{10a,,gccjit;;object}).  It is a thin
11618 wrapper around the C API's @pxref{25,,gcc_jit_param *}.
11620 @node Functions<2>,Blocks<2>,Params<2>,Creating and using functions<2>
11621 @anchor{cp/topics/functions functions}@anchor{165}
11622 @subsubsection Functions
11625 @geindex gccjit;;function (C++ class)
11626 @anchor{cp/topics/functions gccjit function}@anchor{166}
11627 @deffn {C++ Class} gccjit::function
11629 A @cite{gccjit::function} represents a function - either one that we're
11630 creating ourselves, or one that we're referencing.
11631 @end deffn
11634 @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) \
11636 Create a gcc_jit_function with the given name and parameters.
11638 Parameters "is_variadic" and "loc" are optional.
11640 This is a wrapper around the C API's @pxref{11,,gcc_jit_context_new_function()}.
11641 @end deffn
11643 @geindex gccjit;;context;;get_builtin_function (C++ function)
11644 @anchor{cp/topics/functions gccjit context get_builtin_function__cCP}@anchor{167}
11645 @deffn {C++ Function} gccjit::function gccjit::context::get_builtin_function (const char* name)
11647 This is a wrapper around the C API's
11648 @pxref{b5,,gcc_jit_context_get_builtin_function()}.
11649 @end deffn
11651 @geindex gccjit;;function;;get_param (C++ function)
11652 @anchor{cp/topics/functions gccjit function get_param__iC}@anchor{168}
11653 @deffn {C++ Function} gccjit::param gccjit::function::get_param (int index) const
11655 Get the param of the given index (0-based).
11656 @end deffn
11658 @geindex gccjit;;function;;dump_to_dot (C++ function)
11659 @anchor{cp/topics/functions gccjit function dump_to_dot__cCP}@anchor{e4}
11660 @deffn {C++ Function} void gccjit::function::dump_to_dot (const char* path)
11662 Emit the function in graphviz format to the given path.
11663 @end deffn
11665 @geindex gccjit;;function;;new_local (C++ function)
11666 @anchor{cp/topics/functions gccjit function new_local__gccjit type cCP gccjit location}@anchor{db}
11667 @deffn {C++ Function} gccjit::lvalue gccjit::function::new_local (gccjit::type type, const char* name, gccjit::location loc)
11669 Create a new local variable within the function, of the given type and
11670 name.
11671 @end deffn
11673 @node Blocks<2>,Statements<2>,Functions<2>,Creating and using functions<2>
11674 @anchor{cp/topics/functions blocks}@anchor{169}
11675 @subsubsection Blocks
11678 @geindex gccjit;;block (C++ class)
11679 @anchor{cp/topics/functions gccjit block}@anchor{16a}
11680 @deffn {C++ Class} gccjit::block
11682 A @cite{gccjit::block} represents a basic block within a function  i.e. a
11683 sequence of statements with a single entry point and a single exit
11684 point.
11686 @pxref{16a,,gccjit;;block} is a subclass of @pxref{10a,,gccjit;;object}.
11688 The first basic block that you create within a function will
11689 be the entrypoint.
11691 Each basic block that you create within a function must be
11692 terminated, either with a conditional, a jump, or a return.
11694 It's legal to have multiple basic blocks that return within
11695 one function.
11696 @end deffn
11698 @geindex gccjit;;function;;new_block (C++ function)
11699 @anchor{cp/topics/functions gccjit function new_block__cCP}@anchor{16b}
11700 @deffn {C++ Function} gccjit::block gccjit::function::new_block (const char* name)
11702 Create a basic block of the given name.  The name may be NULL, but
11703 providing meaningful names is often helpful when debugging: it may
11704 show up in dumps of the internal representation, and in error
11705 messages.
11706 @end deffn
11708 @node Statements<2>,,Blocks<2>,Creating and using functions<2>
11709 @anchor{cp/topics/functions statements}@anchor{16c}
11710 @subsubsection Statements
11713 @geindex gccjit;;block;;add_eval (C++ function)
11714 @anchor{cp/topics/functions gccjit block add_eval__gccjit rvalue gccjit location}@anchor{153}
11715 @deffn {C++ Function} void gccjit::block::add_eval (gccjit::rvalue rvalue, gccjit::location loc)
11717 Add evaluation of an rvalue, discarding the result
11718 (e.g. a function call that "returns" void).
11720 This is equivalent to this C code:
11722 @example
11723 (void)expression;
11724 @end example
11726 @noindent
11727 @end deffn
11729 @geindex gccjit;;block;;add_assignment (C++ function)
11730 @anchor{cp/topics/functions gccjit block add_assignment__gccjit lvalue gccjit rvalue gccjit location}@anchor{dd}
11731 @deffn {C++ Function} void gccjit::block::add_assignment (gccjit::lvalue lvalue, gccjit::rvalue rvalue, gccjit::location loc)
11733 Add evaluation of an rvalue, assigning the result to the given
11734 lvalue.
11736 This is roughly equivalent to this C code:
11738 @example
11739 lvalue = rvalue;
11740 @end example
11742 @noindent
11743 @end deffn
11745 @geindex gccjit;;block;;add_assignment_op (C++ function)
11746 @anchor{cp/topics/functions gccjit block add_assignment_op__gccjit lvalue enum gccjit rvalue gccjit location}@anchor{e1}
11747 @deffn {C++ Function} void gccjit::block::add_assignment_op (gccjit::lvalue lvalue, enum gcc_jit_binary_op, gccjit::rvalue rvalue, gccjit::location loc)
11749 Add evaluation of an rvalue, using the result to modify an
11750 lvalue.
11752 This is analogous to "+=" and friends:
11754 @example
11755 lvalue += rvalue;
11756 lvalue *= rvalue;
11757 lvalue /= rvalue;
11758 @end example
11760 @noindent
11762 etc.  For example:
11764 @example
11765 /* "i++" */
11766 loop_body.add_assignment_op (
11767   i,
11768   GCC_JIT_BINARY_OP_PLUS,
11769   ctxt.one (int_type));
11770 @end example
11772 @noindent
11773 @end deffn
11775 @geindex gccjit;;block;;add_comment (C++ function)
11776 @anchor{cp/topics/functions gccjit block add_comment__cCP gccjit location}@anchor{ec}
11777 @deffn {C++ Function} void gccjit::block::add_comment (const char* text, gccjit::location loc)
11779 Add a no-op textual comment to the internal representation of the
11780 code.  It will be optimized away, but will be visible in the dumps
11781 seen via @pxref{5e,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE}
11782 and @pxref{1c,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE},
11783 and thus may be of use when debugging how your project's internal
11784 representation gets converted to the libgccjit IR.
11786 Parameter "loc" is optional.
11787 @end deffn
11789 @geindex gccjit;;block;;end_with_conditional (C++ function)
11790 @anchor{cp/topics/functions gccjit block end_with_conditional__gccjit rvalue gccjit block gccjit block gccjit location}@anchor{e0}
11791 @deffn {C++ Function} void gccjit::block::end_with_conditional (gccjit::rvalue boolval, gccjit::block on_true, gccjit::block on_false, gccjit::location loc)
11793 Terminate a block by adding evaluation of an rvalue, branching on the
11794 result to the appropriate successor block.
11796 This is roughly equivalent to this C code:
11798 @example
11799 if (boolval)
11800   goto on_true;
11801 else
11802   goto on_false;
11803 @end example
11805 @noindent
11807 block, boolval, on_true, and on_false must be non-NULL.
11808 @end deffn
11810 @geindex gccjit;;block;;end_with_jump (C++ function)
11811 @anchor{cp/topics/functions gccjit block end_with_jump__gccjit block gccjit location}@anchor{16d}
11812 @deffn {C++ Function} void gccjit::block::end_with_jump (gccjit::block target, gccjit::location loc)
11814 Terminate a block by adding a jump to the given target block.
11816 This is roughly equivalent to this C code:
11818 @example
11819 goto target;
11820 @end example
11822 @noindent
11823 @end deffn
11825 @geindex gccjit;;block;;end_with_return (C++ function)
11826 @anchor{cp/topics/functions gccjit block end_with_return__gccjit rvalue gccjit location}@anchor{16e}
11827 @deffn {C++ Function} void gccjit::block::end_with_return (gccjit::rvalue rvalue, gccjit::location loc)
11829 Terminate a block.
11831 Both params are optional.
11833 An rvalue must be provided for a function returning non-void, and
11834 must not be provided by a function "returning" @cite{void}.
11836 If an rvalue is provided, the block is terminated by evaluating the
11837 rvalue and returning the value.
11839 This is roughly equivalent to this C code:
11841 @example
11842 return expression;
11843 @end example
11845 @noindent
11847 If an rvalue is not provided, the block is terminated by adding a
11848 valueless return, for use within a function with "void" return type.
11850 This is equivalent to this C code:
11852 @example
11853 return;
11854 @end example
11856 @noindent
11857 @end deffn
11859 @c Copyright (C) 2014 Free Software Foundation, Inc.
11860 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
11861 @c 
11862 @c This is free software: you can redistribute it and/or modify it
11863 @c under the terms of the GNU General Public License as published by
11864 @c the Free Software Foundation, either version 3 of the License, or
11865 @c (at your option) any later version.
11866 @c 
11867 @c This program is distributed in the hope that it will be useful, but
11868 @c WITHOUT ANY WARRANTY; without even the implied warranty of
11869 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11870 @c General Public License for more details.
11871 @c 
11872 @c You should have received a copy of the GNU General Public License
11873 @c along with this program.  If not, see
11874 @c <http://www.gnu.org/licenses/>.
11876 @node Source Locations<2>,Compilation results<2>,Creating and using functions<2>,Topic Reference<2>
11877 @anchor{cp/topics/locations source-locations}@anchor{16f}@anchor{cp/topics/locations doc}@anchor{170}
11878 @subsection Source Locations
11881 @geindex gccjit;;location (C++ class)
11882 @anchor{cp/topics/locations gccjit location}@anchor{102}
11883 @deffn {C++ Class} gccjit::location
11885 A @cite{gccjit::location} encapsulates a source code location, so that
11886 you can (optionally) associate locations in your language with
11887 statements in the JIT-compiled code, allowing the debugger to
11888 single-step through your language.
11890 @cite{gccjit::location} instances are optional: you can always omit them
11891 from any C++ API entrypoint accepting one.
11893 You can construct them using @pxref{f0,,gccjit;;context;;new_location()}.
11895 You need to enable @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} on the
11896 @pxref{fa,,gccjit;;context} for these locations to actually be usable by
11897 the debugger:
11899 @example
11900 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DEBUGINFO, 1);
11901 @end example
11903 @noindent
11904 @end deffn
11906 @geindex gccjit;;context;;new_location (C++ function)
11907 @anchor{cp/topics/locations gccjit context new_location__cCP i i}@anchor{f0}
11908 @deffn {C++ Function} gccjit::location gccjit::context::new_location (const char* filename, int line, int column)
11910 Create a @cite{gccjit::location} instance representing the given source
11911 location.
11912 @end deffn
11914 @menu
11915 * Faking it: Faking it<2>. 
11917 @end menu
11919 @node Faking it<2>,,,Source Locations<2>
11920 @anchor{cp/topics/locations faking-it}@anchor{171}
11921 @subsubsection Faking it
11924 If you don't have source code for your internal representation, but need
11925 to debug, you can generate a C-like representation of the functions in
11926 your context using @pxref{101,,gccjit;;context;;dump_to_file()}:
11928 @example
11929 ctxt.dump_to_file ("/tmp/something.c",
11930                    1 /* update_locations */);
11931 @end example
11933 @noindent
11935 This will dump C-like code to the given path.  If the @cite{update_locations}
11936 argument is true, this will also set up @cite{gccjit::location} information
11937 throughout the context, pointing at the dump file as if it were a source
11938 file, giving you @emph{something} you can step through in the debugger.
11940 @c Copyright (C) 2014 Free Software Foundation, Inc.
11941 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
11942 @c 
11943 @c This is free software: you can redistribute it and/or modify it
11944 @c under the terms of the GNU General Public License as published by
11945 @c the Free Software Foundation, either version 3 of the License, or
11946 @c (at your option) any later version.
11947 @c 
11948 @c This program is distributed in the hope that it will be useful, but
11949 @c WITHOUT ANY WARRANTY; without even the implied warranty of
11950 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11951 @c General Public License for more details.
11952 @c 
11953 @c You should have received a copy of the GNU General Public License
11954 @c along with this program.  If not, see
11955 @c <http://www.gnu.org/licenses/>.
11957 @node Compilation results<2>,,Source Locations<2>,Topic Reference<2>
11958 @anchor{cp/topics/results compilation-results}@anchor{172}@anchor{cp/topics/results doc}@anchor{173}
11959 @subsection Compilation results
11962 @geindex gcc_jit_result (C++ type)
11963 @anchor{cp/topics/results gcc_jit_result}@anchor{174}
11964 @deffn {C++ Type} gcc_jit_result
11966 A @cite{gcc_jit_result} encapsulates the result of compiling a context.
11967 @end deffn
11969 @geindex gccjit;;context;;compile (C++ function)
11970 @anchor{cp/topics/results gccjit context compile}@anchor{d3}
11971 @deffn {C++ Function} @pxref{174,,gcc_jit_result*} gccjit::context::compile ()
11973 This calls into GCC and builds the code, returning a
11974 @cite{gcc_jit_result *}.
11975 @end deffn
11977 @geindex gcc_jit_result_get_code (C++ function)
11978 @anchor{cp/topics/results gcc_jit_result_get_code__gcc_jit_resultP cCP}@anchor{175}
11979 @deffn {C++ Function} void* gcc_jit_result_get_code (gcc_jit_result* result, const char* funcname)
11981 Locate a given function within the built machine code.
11982 This will need to be cast to a function pointer of the
11983 correct type before it can be called.
11984 @end deffn
11986 @geindex gcc_jit_result_release (C++ function)
11987 @anchor{cp/topics/results gcc_jit_result_release__gcc_jit_resultP}@anchor{176}
11988 @deffn {C++ Function} void gcc_jit_result_release (gcc_jit_result* result)
11990 Once we're done with the code, this unloads the built .so file.
11991 This cleans up the result; after calling this, it's no longer
11992 valid to use the result.
11993 @end deffn
11995 @c Copyright (C) 2014 Free Software Foundation, Inc.
11996 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
11997 @c 
11998 @c This is free software: you can redistribute it and/or modify it
11999 @c under the terms of the GNU General Public License as published by
12000 @c the Free Software Foundation, either version 3 of the License, or
12001 @c (at your option) any later version.
12002 @c 
12003 @c This program is distributed in the hope that it will be useful, but
12004 @c WITHOUT ANY WARRANTY; without even the implied warranty of
12005 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12006 @c General Public License for more details.
12007 @c 
12008 @c You should have received a copy of the GNU General Public License
12009 @c along with this program.  If not, see
12010 @c <http://www.gnu.org/licenses/>.
12012 @node Internals,Indices and tables,C++ bindings for libgccjit,Top
12013 @anchor{internals/index internals}@anchor{177}@anchor{internals/index doc}@anchor{178}
12014 @chapter Internals
12017 @menu
12018 * Working on the JIT library:: 
12019 * Running the test suite:: 
12020 * Environment variables:: 
12021 * Overview of code structure:: 
12023 @end menu
12025 @node Working on the JIT library,Running the test suite,,Internals
12026 @anchor{internals/index working-on-the-jit-library}@anchor{179}
12027 @section Working on the JIT library
12030 Having checked out the source code (to "src"), you can configure and build
12031 the JIT library like this:
12033 @example
12034 mkdir build
12035 mkdir install
12036 PREFIX=$(pwd)/install
12037 cd build
12038 ../src/configure \
12039    --enable-host-shared \
12040    --enable-languages=jit,c++ \
12041    --disable-bootstrap \
12042    --enable-checking=release \
12043    --prefix=$PREFIX
12044 nice make -j4 # altering the "4" to however many cores you have
12045 @end example
12047 @noindent
12049 This should build a libgccjit.so within jit/build/gcc:
12051 @example
12052 [build] $ file gcc/libgccjit.so*
12053 gcc/libgccjit.so:       symbolic link to `libgccjit.so.0'
12054 gcc/libgccjit.so.0:     symbolic link to `libgccjit.so.0.0.1'
12055 gcc/libgccjit.so.0.0.1: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, not stripped
12056 @end example
12058 @noindent
12060 Here's what those configuration options mean:
12062 @geindex command line option; --enable-host-shared
12063 @anchor{internals/index cmdoption--enable-host-shared}@anchor{17a}
12064 @deffn {Option} --enable-host-shared
12066 Configuring with this option means that the compiler is built as
12067 position-independent code, which incurs a slight performance hit,
12068 but it necessary for a shared library.
12069 @end deffn
12071 @geindex command line option; --enable-languages=jit@comma{}c++
12072 @anchor{internals/index cmdoption--enable-languages}@anchor{17b}
12073 @deffn {Option} --enable-languages=jit,c++
12075 This specifies which frontends to build.  The JIT library looks like
12076 a frontend to the rest of the code.
12078 The C++ portion of the JIT test suite requires the C++ frontend to be
12079 enabled at configure-time, or you may see errors like this when
12080 running the test suite:
12082 @example
12083 xgcc: error: /home/david/jit/src/gcc/testsuite/jit.dg/test-quadratic.cc: C++ compiler not installed on this system
12084 c++: error trying to exec 'cc1plus': execvp: No such file or directory
12085 @end example
12087 @noindent
12088 @end deffn
12090 @geindex command line option; --disable-bootstrap
12091 @anchor{internals/index cmdoption--disable-bootstrap}@anchor{17c}
12092 @deffn {Option} --disable-bootstrap
12094 For hacking on the "jit" subdirectory, performing a full
12095 bootstrap can be overkill, since it's unused by a bootstrap.  However,
12096 when submitting patches, you should remove this option, to ensure that
12097 the compiler can still bootstrap itself.
12098 @end deffn
12100 @geindex command line option; --enable-checking=release
12101 @anchor{internals/index cmdoption--enable-checking}@anchor{17d}
12102 @deffn {Option} --enable-checking=release
12104 The compile can perform extensive self-checking as it runs, useful when
12105 debugging, but slowing things down.
12107 For maximum speed, configure with @code{--enable-checking=release} to
12108 disable this self-checking.
12109 @end deffn
12111 @node Running the test suite,Environment variables,Working on the JIT library,Internals
12112 @anchor{internals/index running-the-test-suite}@anchor{17e}
12113 @section Running the test suite
12116 @example
12117 [build] $ cd gcc
12118 [gcc] $ make check-jit RUNTESTFLAGS="-v -v -v"
12119 @end example
12121 @noindent
12123 A summary of the tests can then be seen in:
12125 @example
12126 jit/build/gcc/testsuite/jit/jit.sum
12127 @end example
12129 @noindent
12131 and detailed logs in:
12133 @example
12134 jit/build/gcc/testsuite/jit/jit.log
12135 @end example
12137 @noindent
12139 The test executables can be seen as:
12141 @example
12142 jit/build/gcc/testsuite/jit/*.exe
12143 @end example
12145 @noindent
12147 which can be run independently.
12149 You can compile and run individual tests by passing "jit.exp=TESTNAME" to RUNTESTFLAGS e.g.:
12151 @example
12152 [gcc] $ make check-jit RUNTESTFLAGS="-v -v -v jit.exp=test-factorial.c"
12153 @end example
12155 @noindent
12157 and once a test has been compiled, you can debug it directly:
12159 @example
12160 [gcc] $ PATH=.:$PATH \
12161         LD_LIBRARY_PATH=. \
12162         LIBRARY_PATH=. \
12163           gdb --args \
12164             testsuite/jit/test-factorial.c.exe
12165 @end example
12167 @noindent
12169 @menu
12170 * Running under valgrind:: 
12172 @end menu
12174 @node Running under valgrind,,,Running the test suite
12175 @anchor{internals/index running-under-valgrind}@anchor{17f}
12176 @subsection Running under valgrind
12179 The jit testsuite detects if RUN_UNDER_VALGRIND is present in the
12180 environment (with any value).  If it is present, it runs the test client
12181 code under valgrind@footnote{http://valgrind.org},
12182 specifcally, the default
12183 memcheck@footnote{http://valgrind.org/docs/manual/mc-manual.html}
12184 tool with
12185 --leak-check=full@footnote{http://valgrind.org/docs/manual/mc-manual.html#opt.leak-check}.
12187 It automatically parses the output from valgrind, injecting XFAIL results if
12188 any issues are found, or PASS results if the output is clean.  The output
12189 is saved to @code{TESTNAME.exe.valgrind.txt}.
12191 For example, the following invocation verbosely runs the testcase
12192 @code{test-sum-of-squares.c} under valgrind, showing an issue:
12194 @example
12195 $ RUN_UNDER_VALGRIND= \
12196     make check-jit \
12197       RUNTESTFLAGS="-v -v -v jit.exp=test-sum-of-squares.c"
12199 (...verbose log contains detailed valgrind errors, if any...)
12201                 === jit Summary ===
12203 # of expected passes            28
12204 # of expected failures          2
12206 $ less testsuite/jit/jit.sum
12207 (...other results...)
12208 XFAIL: jit.dg/test-sum-of-squares.c: test-sum-of-squares.c.exe.valgrind.txt: definitely lost: 8 bytes in 1 blocks
12209 XFAIL: jit.dg/test-sum-of-squares.c: test-sum-of-squares.c.exe.valgrind.txt: unsuppressed errors: 1
12210 (...other results...)
12212 $ less testsuite/jit/test-sum-of-squares.c.exe.valgrind.txt
12213 (...shows full valgrind report for this test case...)
12214 @end example
12216 @noindent
12218 When running under valgrind, it's best to have configured gcc with
12219 @code{--enable-valgrind-annotations}, which automatically suppresses
12220 various known false positives.
12222 @node Environment variables,Overview of code structure,Running the test suite,Internals
12223 @anchor{internals/index environment-variables}@anchor{180}
12224 @section Environment variables
12227 When running client code against a locally-built libgccjit, three
12228 environment variables need to be set up:
12230 @geindex environment variable; LD_LIBRARY_PATH
12231 @anchor{internals/index envvar-LD_LIBRARY_PATH}@anchor{181}
12232 @deffn {Environment Variable} LD_LIBRARY_PATH
12234 @quotation
12236 @cite{libgccjit.so} is dynamically linked into client code, so if running
12237 against a locally-built library, @code{LD_LIBRARY_PATH} needs to be set
12238 up appropriately.  The library can be found within the "gcc"
12239 subdirectory of the build tree:
12240 @end quotation
12242 @example
12243 $ file libgccjit.so*
12244 libgccjit.so:       symbolic link to `libgccjit.so.0'
12245 libgccjit.so.0:     symbolic link to `libgccjit.so.0.0.1'
12246 libgccjit.so.0.0.1: ELF 64-bit LSB shared object, x86-64, version 1 (GNU/Linux), dynamically linked, not stripped
12247 @end example
12249 @noindent
12250 @end deffn
12252 @geindex environment variable; PATH
12253 @anchor{internals/index envvar-PATH}@anchor{182}
12254 @deffn {Environment Variable} PATH
12256 The library uses a driver executable for converting from .s assembler
12257 files to .so shared libraries.  Specifically, it looks for a name
12258 expanded from
12259 @code{$@{target_noncanonical@}-gcc-$@{gcc_BASEVER@}$@{exeext@}}
12260 such as @code{x86_64-unknown-linux-gnu-gcc-5.0.0}.
12262 Hence @code{PATH} needs to include a directory where the library can
12263 locate this executable.
12265 The executable is normally installed to the installation bindir
12266 (e.g. /usr/bin), but a copy is also created within the "gcc"
12267 subdirectory of the build tree for running the testsuite, and for ease
12268 of development.
12269 @end deffn
12271 @geindex environment variable; LIBRARY_PATH
12272 @anchor{internals/index envvar-LIBRARY_PATH}@anchor{183}
12273 @deffn {Environment Variable} LIBRARY_PATH
12275 The driver executable invokes the linker, and the latter needs to locate
12276 support libraries needed by the generated code, or you will see errors
12277 like:
12279 @example
12280 ld: cannot find crtbeginS.o: No such file or directory
12281 ld: cannot find -lgcc
12282 ld: cannot find -lgcc_s
12283 @end example
12285 @noindent
12287 Hence if running directly from a locally-built copy (without installing),
12288 @code{LIBRARY_PATH} needs to contain the "gcc" subdirectory of the build
12289 tree.
12290 @end deffn
12292 For example, to run a binary that uses the library against a non-installed
12293 build of the library in LIBGCCJIT_BUILD_DIR you need an invocation of the
12294 client code like this, to preprend the dir to each of the environment
12295 variables:
12297 @example
12298 $ LD_LIBRARY_PATH=$(LIBGCCJIT_BUILD_DIR):$(LD_LIBRARY_PATH) \
12299   PATH=$(LIBGCCJIT_BUILD_DIR):$(PATH) \
12300   LIBRARY_PATH=$(LIBGCCJIT_BUILD_DIR):$(LIBRARY_PATH) \
12301     ./jit-hello-world
12302 hello world
12303 @end example
12305 @noindent
12307 @node Overview of code structure,,Environment variables,Internals
12308 @anchor{internals/index overview-of-code-structure}@anchor{184}
12309 @section Overview of code structure
12313 @itemize *
12315 @item 
12316 @code{libgccjit.c} implements the API entrypoints.  It performs error
12317 checking, then calls into classes of the gcc::jit::recording namespace
12318 within @code{jit-recording.c} and @code{jit-recording.h}.
12320 @item 
12321 The gcc::jit::recording classes (within @code{jit-recording.c} and
12322 @code{jit-recording.h}) record the API calls that are made:
12324 @quotation
12326 @example
12328   /* Indentation indicates inheritance: */
12329   class context;
12330   class memento;
12331     class string;
12332     class location;
12333     class type;
12334       class function_type;
12335       class compound_type;
12336         class struct_;
12337         class union_;
12338     class field;
12339     class fields;
12340     class function;
12341     class block;
12342     class rvalue;
12343       class lvalue;
12344         class local;
12345         class global;
12346         class param;
12347     class statement;
12350 @end example
12352 @noindent
12353 @end quotation
12355 @item 
12356 When the context is compiled, the gcc::jit::playback classes (within
12357 @code{jit-playback.c} and @code{jit-playback.h}) replay the API calls
12358 within langhook:parse_file:
12360 @quotation
12362 @example
12364   /* Indentation indicates inheritance: */
12365   class context;
12366   class wrapper;
12367     class type;
12368       class compound_type;
12369     class field;
12370     class function;
12371     class block;
12372     class rvalue;
12373       class lvalue;
12374         class param;
12375     class source_file;
12376     class source_line;
12377     class location;
12380 @end example
12382 @noindent
12384 @example
12385 Client Code   . Generated .            libgccjit.so
12386               . code      .
12387               .           . JIT API  . JIT "Frontend". (libbackend.a)
12388 ....................................................................................
12389    │          .           .          .               .
12390     ──────────────────────────>      .               .
12391               .           .    │     .               .
12392               .           .    V     .               .
12393               .           .    ──> libgccjit.c       .
12394               .           .        │ (error-checking).
12395               .           .        │                 .
12396               .           .        ──> jit-recording.c
12397               .           .              (record API calls)
12398               .           .    <───────              .
12399               .           .    │     .               .
12400    <───────────────────────────      .               .
12401    │          .           .          .               .
12402    │          .           .          .               .
12403    V          .           .  gcc_jit_context_compile .
12404     ──────────────────────────>      .               .
12405               .           .    │ start of recording::context::compile ()
12406               .           .    │     .               .
12407               .           .    │ start of playback::context::compile ()
12408               .           .    │   (create tempdir)  .
12409               .           .    │     .               .
12410               .           .    │ ACQUIRE MUTEX       .
12411               .           .    │     .               .
12412               .           .    V───────────────────────> toplev::main (for now)
12413               .           .          .               .       │
12414               .           .          .               .   (various code)
12415               .           .          .               .       │
12416               .           .          .               .       V
12417               .           .          .    <───────────────── langhook:parse_file
12418               .           .          .    │          .
12419               .           .          .    │ (jit_langhook_parse_file)
12420               .           .          .    │          .
12421 ..........................................│..................VVVVVVVVVVVVV...
12422               .           .          .    │          .       No GC in here
12423               .           .          .    │ jit-playback.c
12424               .           .          .    │   (playback of API calls)
12425               .           .          .    ───────────────> creation of functions,
12426               .           .          .               .     types, expression trees
12427               .           .          .    <──────────────── etc
12428               .           .          .    │(handle_locations: add locations to
12429               .           .          .    │ linemap and associate them with trees)
12430               .           .          .    │          .
12431               .           .          .    │          .       No GC in here
12432 ..........................................│..................AAAAAAAAAAAAA...
12433               .           .          .    │ for each function
12434               .           .          .    ──> postprocess
12435               .           .          .        │      .
12436               .           .          .        ────────────> cgraph_finalize_function
12437               .           .          .        <────────────
12438               .           .          .     <──       .
12439               .           .          .    │          .
12440               .           .          .    ──────────────────> (end of
12441               .           .          .               .       │ langhook_parse_file)
12442               .           .          .               .       │
12443               .           .          .               .   (various code)
12444               .           .          .               .       │
12445               .           .          .               .       ↓
12446               .           .          .    <───────────────── langhook:write_globals
12447               .           .          .    │          .
12448               .           .          .    │ (jit_langhook_write_globals)
12449               .           .          .    │          .
12450               .           .          .    │          .
12451               .           .          .    ──────────────────> finalize_compilation_unit
12452               .           .          .               .       │
12453               .           .          .               .   (the middle─end and backend)
12454               .           .          .               .       ↓
12455               .           .    <───────────────────────────── end of toplev::main
12456               .           .    │     .               .
12457               .           .    V───────────────────────> toplev::finalize
12458               .           .          .               . │   (purge internal state)
12459               .           .    <──────────────────────── end of toplev::finalize
12460               .           .    │     .               .
12461               .           .    │ Convert assembler to DSO ("fake.so")
12462               .           .    │     .               .
12463               .           .    │ Load DSO (dlopen "fake.so")
12464               .           .    │     .               .
12465               .           .    │ RELEASE MUTEX       .
12466               .           .    │     .               .
12467               .           .    │ end of playback::context::compile ()
12468               .           .    │     .               .
12469               .           .    │ playback::context dtor
12470               .           .     ──>  .               .
12471               .           .       │ Cleanup tempdir  .
12472               .           .       │   ("fake.so" is unlinked from the
12473               .           .       │    filesystem at this point)
12474               .           .    <──   .               .
12475               .           .    │     .               .
12476               .           .    │ end of recording::context::compile ()
12477    <───────────────────────────      .               .
12478    │          .           .          .               .
12479    V          .           .  gcc_jit_result_get_code .
12480     ──────────────────────────>      .               .
12481               .           .    │ dlsym () within loaded DSO
12482    <───────────────────────────      .               .
12483    Get (void*).           .          .               .
12484    │          .           .          .               .
12485    │ Call it  .           .          .               .
12486    ───────────────>       .          .               .
12487               .    │      .          .               .
12488               .    │      .          .               .
12489    <───────────────       .          .               .
12490    │          .           .          .               .
12491 etc│          .           .          .               .
12492    │          .           .          .               .
12493    V          .           .  gcc_jit_result_release  .
12494     ──────────────────────────>      .               .
12495               .           .    │ dlclose () the loaded DSO
12496               .           .    │    (code becomes uncallable)
12497    <───────────────────────────      .               .
12498    │          .           .          .               .
12500 @end example
12502 @noindent
12503 @end quotation
12504 @end itemize
12506 Here is a high-level summary from @code{jit-common.h}:
12508 @quotation
12510 In order to allow jit objects to be usable outside of a compile
12511 whilst working with the existing structure of GCC's code the
12512 C API is implemented in terms of a gcc::jit::recording::context,
12513 which records the calls made to it.
12515 When a gcc_jit_context is compiled, the recording context creates a
12516 playback context.  The playback context invokes the bulk of the GCC
12517 code, and within the "frontend" parsing hook, plays back the recorded
12518 API calls, creating GCC tree objects.
12520 So there are two parallel families of classes: those relating to
12521 recording, and those relating to playback:
12524 @itemize *
12526 @item 
12527 Visibility: recording objects are exposed back to client code,
12528 whereas playback objects are internal to the library.
12530 @item 
12531 Lifetime: recording objects have a lifetime equal to that of the
12532 recording context that created them, whereas playback objects only
12533 exist within the frontend hook.
12535 @item 
12536 Memory allocation: recording objects are allocated by the recording
12537 context, and automatically freed by it when the context is released,
12538 whereas playback objects are allocated within the GC heap, and
12539 garbage-collected; they can own GC-references.
12541 @item 
12542 Integration with rest of GCC: recording objects are unrelated to the
12543 rest of GCC, whereas playback objects are wrappers around "tree"
12544 instances.  Hence you can't ask a recording rvalue or lvalue what its
12545 type is, whereas you can for a playback rvalue of lvalue (since it
12546 can work with the underlying GCC tree nodes).
12548 @item 
12549 Instancing: There can be multiple recording contexts "alive" at once
12550 (albeit it only one compiling at once), whereas there can only be one
12551 playback context alive at one time (since it interacts with the GC).
12552 @end itemize
12554 Ultimately if GCC could support multiple GC heaps and contexts, and
12555 finer-grained initialization, then this recording vs playback
12556 distinction could be eliminated.
12558 During a playback, we associate objects from the recording with
12559 their counterparts during this playback.  For simplicity, we store this
12560 within the recording objects, as @code{void *m_playback_obj}, casting it to
12561 the appropriate playback object subclass.  For these casts to make
12562 sense, the two class hierarchies need to have the same structure.
12564 Note that the playback objects that @code{m_playback_obj} points to are
12565 GC-allocated, but the recording objects don't own references:
12566 these associations only exist within a part of the code where
12567 the GC doesn't collect, and are set back to NULL before the GC can
12568 run.
12569 @end quotation
12570 @anchor{internals/index example-of-log-file}@anchor{55}
12571 Another way to understand the structure of the code is to enable logging,
12572 via @pxref{54,,gcc_jit_context_set_logfile()}.  Here is an example of a log
12573 generated via this call:
12575 @example
12576 JIT: entering: gcc_jit_context_set_str_option
12577 JIT: exiting: gcc_jit_context_set_str_option
12578 JIT: entering: gcc_jit_context_set_int_option
12579 JIT: exiting: gcc_jit_context_set_int_option
12580 JIT: entering: gcc_jit_context_set_bool_option
12581 JIT: exiting: gcc_jit_context_set_bool_option
12582 JIT: entering: gcc_jit_context_set_bool_option
12583 JIT: exiting: gcc_jit_context_set_bool_option
12584 JIT: entering: gcc_jit_context_set_bool_option
12585 JIT: exiting: gcc_jit_context_set_bool_option
12586 JIT: entering: gcc_jit_context_set_bool_option
12587 JIT: exiting: gcc_jit_context_set_bool_option
12588 JIT: entering: gcc_jit_context_set_bool_option
12589 JIT: exiting: gcc_jit_context_set_bool_option
12590 JIT: entering: gcc_jit_context_get_type
12591 JIT: exiting: gcc_jit_context_get_type
12592 JIT: entering: gcc_jit_context_get_type
12593 JIT: exiting: gcc_jit_context_get_type
12594 JIT: entering: gcc_jit_context_new_param
12595 JIT: exiting: gcc_jit_context_new_param
12596 JIT: entering: gcc_jit_context_new_function
12597 JIT: exiting: gcc_jit_context_new_function
12598 JIT: entering: gcc_jit_context_new_param
12599 JIT: exiting: gcc_jit_context_new_param
12600 JIT: entering: gcc_jit_context_get_type
12601 JIT: exiting: gcc_jit_context_get_type
12602 JIT: entering: gcc_jit_context_new_function
12603 JIT: exiting: gcc_jit_context_new_function
12604 JIT: entering: gcc_jit_context_new_string_literal
12605 JIT: exiting: gcc_jit_context_new_string_literal
12606 JIT: entering: gcc_jit_function_new_block
12607 JIT: exiting: gcc_jit_function_new_block
12608 JIT: entering: gcc_jit_block_add_comment
12609 JIT: exiting: gcc_jit_block_add_comment
12610 JIT: entering: gcc_jit_context_new_call
12611 JIT: exiting: gcc_jit_context_new_call
12612 JIT: entering: gcc_jit_block_add_eval
12613 JIT: exiting: gcc_jit_block_add_eval
12614 JIT: entering: gcc_jit_block_end_with_void_return
12615 JIT: exiting: gcc_jit_block_end_with_void_return
12616 JIT: entering: gcc_jit_context_compile
12617 JIT:  compiling ctxt: 0x1283e20
12618 JIT:  entering: gcc::jit::result* gcc::jit::recording::context::compile()
12619 JIT:   entering: void gcc::jit::recording::context::validate()
12620 JIT:   exiting: void gcc::jit::recording::context::validate()
12621 JIT:   entering: gcc::jit::playback::context::context(gcc::jit::recording::context*)
12622 JIT:   exiting: gcc::jit::playback::context::context(gcc::jit::recording::context*)
12623 JIT:   entering: gcc::jit::result* gcc::jit::playback::context::compile()
12624 JIT:    entering: void gcc::jit::playback::context::make_fake_args(vec<char*>*, const char*, vec<gcc::jit::recording::requested_dump>*)
12625 JIT:    exiting: void gcc::jit::playback::context::make_fake_args(vec<char*>*, const char*, vec<gcc::jit::recording::requested_dump>*)
12626 JIT:    entering: void gcc::jit::playback::context::acquire_mutex()
12627 JIT:    exiting: void gcc::jit::playback::context::acquire_mutex()
12628 JIT:    entering: toplev::main
12629 JIT:     argv[0]: ./test-hello-world.c.exe
12630 JIT:     argv[1]: /tmp/libgccjit-CKq1M9/fake.c
12631 JIT:     argv[2]: -fPIC
12632 JIT:     argv[3]: -O3
12633 JIT:     argv[4]: -g
12634 JIT:     argv[5]: -quiet
12635 JIT:     argv[6]: --param
12636 JIT:     argv[7]: ggc-min-expand=0
12637 JIT:     argv[8]: --param
12638 JIT:     argv[9]: ggc-min-heapsize=0
12639 JIT:     entering: bool jit_langhook_init()
12640 JIT:     exiting: bool jit_langhook_init()
12641 JIT:     entering: void gcc::jit::playback::context::replay()
12642 JIT:      entering: void gcc::jit::recording::context::replay_into(gcc::jit::replayer*)
12643 JIT:      exiting: void gcc::jit::recording::context::replay_into(gcc::jit::replayer*)
12644 JIT:      entering: void gcc::jit::recording::context::disassociate_from_playback()
12645 JIT:      exiting: void gcc::jit::recording::context::disassociate_from_playback()
12646 JIT:      entering: void gcc::jit::playback::context::handle_locations()
12647 JIT:      exiting: void gcc::jit::playback::context::handle_locations()
12648 JIT:      entering: void gcc::jit::playback::function::build_stmt_list()
12649 JIT:      exiting: void gcc::jit::playback::function::build_stmt_list()
12650 JIT:      entering: void gcc::jit::playback::function::build_stmt_list()
12651 JIT:      exiting: void gcc::jit::playback::function::build_stmt_list()
12652 JIT:      entering: void gcc::jit::playback::function::postprocess()
12653 JIT:      exiting: void gcc::jit::playback::function::postprocess()
12654 JIT:      entering: void gcc::jit::playback::function::postprocess()
12655 JIT:      exiting: void gcc::jit::playback::function::postprocess()
12656 JIT:     exiting: void gcc::jit::playback::context::replay()
12657 JIT:     entering: void jit_langhook_write_globals()
12658 JIT:     exiting: void jit_langhook_write_globals()
12659 JIT:    exiting: toplev::main
12660 JIT:    entering: void gcc::jit::playback::context::extract_any_requested_dumps(vec<gcc::jit::recording::requested_dump>*)
12661 JIT:    exiting: void gcc::jit::playback::context::extract_any_requested_dumps(vec<gcc::jit::recording::requested_dump>*)
12662 JIT:    entering: toplev::finalize
12663 JIT:    exiting: toplev::finalize
12664 JIT:    entering: void gcc::jit::playback::context::convert_to_dso(const char*)
12665 JIT:     argv[0]: x86_64-unknown-linux-gnu-gcc-5.0.0
12666 JIT:     argv[1]: -shared
12667 JIT:     argv[2]: /tmp/libgccjit-CKq1M9/fake.s
12668 JIT:     argv[3]: -o
12669 JIT:     argv[4]: /tmp/libgccjit-CKq1M9/fake.so
12670 JIT:     argv[5]: -fno-use-linker-plugin
12671 JIT:     argv[6]: (null)
12672 JIT:    exiting: void gcc::jit::playback::context::convert_to_dso(const char*)
12673 JIT:    entering: gcc::jit::result* gcc::jit::playback::context::dlopen_built_dso()
12674 JIT:     entering: gcc::jit::result::result(gcc::jit::logger*, void*)
12675 JIT:     exiting: gcc::jit::result::result(gcc::jit::logger*, void*)
12676 JIT:    exiting: gcc::jit::result* gcc::jit::playback::context::dlopen_built_dso()
12677 JIT:    entering: void gcc::jit::playback::context::release_mutex()
12678 JIT:    exiting: void gcc::jit::playback::context::release_mutex()
12679 JIT:   exiting: gcc::jit::result* gcc::jit::playback::context::compile()
12680 JIT:   entering: gcc::jit::playback::context::~context()
12681 JIT:   exiting: gcc::jit::playback::context::~context()
12682 JIT:  exiting: gcc::jit::result* gcc::jit::recording::context::compile()
12683 JIT:  gcc_jit_context_compile: returning (gcc_jit_result *)0x12f75d0
12684 JIT: exiting: gcc_jit_context_compile
12685 JIT: entering: gcc_jit_result_get_code
12686 JIT:  locating fnname: hello_world
12687 JIT:  entering: void* gcc::jit::result::get_code(const char*)
12688 JIT:  exiting: void* gcc::jit::result::get_code(const char*)
12689 JIT:  gcc_jit_result_get_code: returning (void *)0x7ff6b8cd87f0
12690 JIT: exiting: gcc_jit_result_get_code
12691 JIT: entering: gcc_jit_context_release
12692 JIT:  deleting ctxt: 0x1283e20
12693 JIT:  entering: gcc::jit::recording::context::~context()
12694 JIT:  exiting: gcc::jit::recording::context::~context()
12695 JIT: exiting: gcc_jit_context_release
12696 JIT: entering: gcc_jit_result_release
12697 JIT:  deleting result: 0x12f75d0
12698 JIT:  entering: virtual gcc::jit::result::~result()
12699 JIT:  exiting: virtual gcc::jit::result::~result()
12700 JIT: exiting: gcc_jit_result_release
12701 JIT: gcc::jit::logger::~logger()
12703 @end example
12705 @noindent
12707 @node Indices and tables,Index,Internals,Top
12708 @anchor{index indices-and-tables}@anchor{185}
12709 @unnumbered Indices and tables
12713 @itemize *
12715 @item 
12716 @emph{genindex}
12718 @item 
12719 @emph{modindex}
12721 @item 
12722 @emph{search}
12723 @end itemize
12725 @c Some notes:
12726 @c 
12727 @c The Sphinx C domain appears to lack explicit support for enum values,
12728 @c so I've been using :c:macro: for them.
12729 @c 
12730 @c See http://sphinx-doc.org/domains.html#the-c-domain
12732 @node Index,,Indices and tables,Top
12733 @unnumbered Index
12736 @printindex ge
12738 @c %**end of body
12739 @bye