1 \input texinfo @c -*-texinfo-*-
3 @setfilename libgccjit.info
4 @documentencoding UTF-8
6 @*Generated by Sphinx 1.1.3.@*
8 @settitle libgccjit Documentation
13 @dircategory Miscellaneous
15 * libgccjit: (libgccjit.info). One line description of project.
22 libgccjit 8.0.0 (experimental 20171031), October 31, 2017
26 Copyright @copyright{} 2014-2019 Free Software Foundation, Inc.
32 @title libgccjit Documentation
37 @c %** start of user preamble
39 @c %** end of user preamble
43 @top libgccjit Documentation
48 @anchor{index doc}@anchor{0}
49 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
50 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
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.
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.
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
73 There are actually two APIs for the library:
79 a pure C API: @code{libgccjit.h}
82 a C++ wrapper API: @code{libgccjit++.h}. This is a collection of "thin"
83 wrapper classes around the C API, to save typing.
88 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
89 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
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.
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.
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/>.
108 * C++ bindings for libgccjit::
110 * Indices and tables::
114 --- The Detailed Node Listing ---
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.
122 * Tutorial part 5; Implementing an Ahead-of-Time compiler: Tutorial part 5 Implementing an Ahead-of-Time compiler.
124 Tutorial part 2: Creating a trivial machine code function
130 Tutorial part 3: Loops and variables
132 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues.
134 * Visualizing the control flow graph::
135 * Full example: Full example<2>.
137 Tutorial part 4: Adding JIT-compilation to a toy interpreter
139 * Our toy interpreter::
140 * Compiling to machine code::
141 * Setting things up::
142 * Populating the function::
143 * Verifying the control flow graph::
144 * Compiling the context::
145 * Single-stepping through the generated code::
146 * Examining the generated code::
147 * Putting it all together::
148 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?.
150 Behind the curtain: How does our code get optimized?
152 * Optimizing away stack manipulation::
153 * Elimination of tail recursion::
155 Tutorial part 5: Implementing an Ahead-of-Time compiler
157 * The "brainf" language::
158 * Converting a brainf script to libgccjit IR::
159 * Compiling a context to a file::
160 * Other forms of ahead-of-time-compilation::
164 * Compilation contexts::
168 * Creating and using functions::
169 * Function pointers: Function pointers<2>.
171 * Compiling a context::
172 * ABI and API compatibility::
177 * Lifetime-management::
179 * Error-handling: Error-handling<2>.
181 * Options: Options<2>.
188 * Additional command-line options::
193 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile.
195 * Structures and unions::
196 * Function pointer types::
202 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions.
206 * Simple expressions::
207 * Vector expressions::
209 * Binary Operations::
212 * Function pointers::
219 Creating and using functions
232 * In-memory compilation::
233 * Ahead-of-time compilation::
235 ABI and API compatibility
257 C++ bindings for libgccjit
259 * Tutorial: Tutorial<2>.
260 * Topic Reference: Topic Reference<2>.
264 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world"<2>.
265 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function<2>.
266 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables<2>.
267 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>.
269 Tutorial part 2: Creating a trivial machine code function
271 * Options: Options<3>.
272 * Full example: Full example<3>.
274 Tutorial part 3: Loops and variables
276 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues<2>.
277 * Control flow: Control flow<2>.
278 * Visualizing the control flow graph: Visualizing the control flow graph<2>.
279 * Full example: Full example<4>.
281 Tutorial part 4: Adding JIT-compilation to a toy interpreter
283 * Our toy interpreter: Our toy interpreter<2>.
284 * Compiling to machine code: Compiling to machine code<2>.
285 * Setting things up: Setting things up<2>.
286 * Populating the function: Populating the function<2>.
287 * Verifying the control flow graph: Verifying the control flow graph<2>.
288 * Compiling the context: Compiling the context<2>.
289 * Single-stepping through the generated code: Single-stepping through the generated code<2>.
290 * Examining the generated code: Examining the generated code<2>.
291 * Putting it all together: Putting it all together<2>.
292 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?<2>.
294 Behind the curtain: How does our code get optimized?
296 * Optimizing away stack manipulation: Optimizing away stack manipulation<2>.
297 * Elimination of tail recursion: Elimination of tail recursion<2>.
301 * Compilation contexts: Compilation contexts<2>.
302 * Objects: Objects<2>.
304 * Expressions: Expressions<2>.
305 * Creating and using functions: Creating and using functions<2>.
306 * Source Locations: Source Locations<2>.
307 * Compiling a context: Compiling a context<2>.
311 * Lifetime-management: Lifetime-management<2>.
312 * Thread-safety: Thread-safety<2>.
313 * Error-handling: Error-handling<3>.
314 * Debugging: Debugging<2>.
315 * Options: Options<4>.
319 * String Options: String Options<2>.
320 * Boolean options: Boolean options<2>.
321 * Integer options: Integer options<2>.
322 * Additional command-line options: Additional command-line options<2>.
326 * Standard types: Standard types<2>.
327 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile<2>.
328 * Vector types: Vector types<2>.
329 * Structures and unions: Structures and unions<2>.
333 * Rvalues: Rvalues<2>.
334 * Lvalues: Lvalues<2>.
335 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions<2>.
339 * Simple expressions: Simple expressions<2>.
340 * Vector expressions: Vector expressions<2>.
341 * Unary Operations: Unary Operations<2>.
342 * Binary Operations: Binary Operations<2>.
343 * Comparisons: Comparisons<2>.
344 * Function calls: Function calls<2>.
345 * Function pointers: Function pointers<3>.
346 * Type-coercion: Type-coercion<2>.
350 * Global variables: Global variables<2>.
352 Creating and using functions
355 * Functions: Functions<2>.
357 * Statements: Statements<2>.
361 * Faking it: Faking it<2>.
365 * In-memory compilation: In-memory compilation<2>.
366 * Ahead-of-time compilation: Ahead-of-time compilation<2>.
370 * Working on the JIT library::
371 * Running the test suite::
372 * Environment variables::
374 * Overview of code structure::
376 * Submitting patches::
378 Running the test suite
380 * Running under valgrind::
386 @node Tutorial,Topic Reference,Top,Top
387 @anchor{intro/index libgccjit}@anchor{1}@anchor{intro/index doc}@anchor{2}@anchor{intro/index tutorial}@anchor{3}
391 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
392 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
394 @c This is free software: you can redistribute it and/or modify it
395 @c under the terms of the GNU General Public License as published by
396 @c the Free Software Foundation, either version 3 of the License, or
397 @c (at your option) any later version.
399 @c This program is distributed in the hope that it will be useful, but
400 @c WITHOUT ANY WARRANTY; without even the implied warranty of
401 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
402 @c General Public License for more details.
404 @c You should have received a copy of the GNU General Public License
405 @c along with this program. If not, see
406 @c <http://www.gnu.org/licenses/>.
409 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world".
410 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function.
411 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables.
412 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter.
413 * Tutorial part 5; Implementing an Ahead-of-Time compiler: Tutorial part 5 Implementing an Ahead-of-Time compiler.
417 @node Tutorial part 1 "Hello world",Tutorial part 2 Creating a trivial machine code function,,Tutorial
418 @anchor{intro/tutorial01 doc}@anchor{4}@anchor{intro/tutorial01 tutorial-part-1-hello-world}@anchor{5}
419 @section Tutorial part 1: "Hello world"
422 Before we look at the details of the API, let's look at building and
423 running programs that use the library.
425 Here's a toy "hello world" program that uses the library to synthesize
426 a call to @cite{printf} and uses it to write a message to stdout.
428 Don't worry about the content of the program for now; we'll cover
429 the details in later parts of this tutorial.
434 /* Smoketest example for libgccjit.so
435 Copyright (C) 2014-2019 Free Software Foundation, Inc.
437 This file is part of GCC.
439 GCC is free software; you can redistribute it and/or modify it
440 under the terms of the GNU General Public License as published by
441 the Free Software Foundation; either version 3, or (at your option)
444 GCC is distributed in the hope that it will be useful, but
445 WITHOUT ANY WARRANTY; without even the implied warranty of
446 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
447 General Public License for more details.
449 You should have received a copy of the GNU General Public License
450 along with GCC; see the file COPYING3. If not see
451 <http://www.gnu.org/licenses/>. */
453 #include <libgccjit.h>
459 create_code (gcc_jit_context *ctxt)
461 /* Let's try to inject the equivalent of:
463 greet (const char *name)
465 printf ("hello %s\n", name);
468 gcc_jit_type *void_type =
469 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_VOID);
470 gcc_jit_type *const_char_ptr_type =
471 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_CONST_CHAR_PTR);
472 gcc_jit_param *param_name =
473 gcc_jit_context_new_param (ctxt, NULL, const_char_ptr_type, "name");
474 gcc_jit_function *func =
475 gcc_jit_context_new_function (ctxt, NULL,
476 GCC_JIT_FUNCTION_EXPORTED,
482 gcc_jit_param *param_format =
483 gcc_jit_context_new_param (ctxt, NULL, const_char_ptr_type, "format");
484 gcc_jit_function *printf_func =
485 gcc_jit_context_new_function (ctxt, NULL,
486 GCC_JIT_FUNCTION_IMPORTED,
487 gcc_jit_context_get_type (
488 ctxt, GCC_JIT_TYPE_INT),
492 gcc_jit_rvalue *args[2];
493 args[0] = gcc_jit_context_new_string_literal (ctxt, "hello %s\n");
494 args[1] = gcc_jit_param_as_rvalue (param_name);
496 gcc_jit_block *block = gcc_jit_function_new_block (func, NULL);
498 gcc_jit_block_add_eval (
500 gcc_jit_context_new_call (ctxt,
504 gcc_jit_block_end_with_void_return (block, NULL);
508 main (int argc, char **argv)
510 gcc_jit_context *ctxt;
511 gcc_jit_result *result;
513 /* Get a "context" object for working with the library. */
514 ctxt = gcc_jit_context_acquire ();
517 fprintf (stderr, "NULL ctxt");
521 /* Set some options on the context.
522 Let's see the code being generated, in assembler form. */
523 gcc_jit_context_set_bool_option (
525 GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
528 /* Populate the context. */
531 /* Compile the code. */
532 result = gcc_jit_context_compile (ctxt);
535 fprintf (stderr, "NULL result");
539 /* Extract the generated code from "result". */
540 typedef void (*fn_type) (const char *);
542 (fn_type)gcc_jit_result_get_code (result, "greet");
545 fprintf (stderr, "NULL greet");
549 /* Now call the generated function: */
553 gcc_jit_context_release (ctxt);
554 gcc_jit_result_release (result);
563 Copy the above to @cite{tut01-hello-world.c}.
565 Assuming you have the jit library installed, build the test program
570 tut01-hello-world.c \
571 -o tut01-hello-world \
577 You should then be able to run the built program:
580 $ ./tut01-hello-world
586 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
587 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
589 @c This is free software: you can redistribute it and/or modify it
590 @c under the terms of the GNU General Public License as published by
591 @c the Free Software Foundation, either version 3 of the License, or
592 @c (at your option) any later version.
594 @c This program is distributed in the hope that it will be useful, but
595 @c WITHOUT ANY WARRANTY; without even the implied warranty of
596 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
597 @c General Public License for more details.
599 @c You should have received a copy of the GNU General Public License
600 @c along with this program. If not, see
601 @c <http://www.gnu.org/licenses/>.
603 @node Tutorial part 2 Creating a trivial machine code function,Tutorial part 3 Loops and variables,Tutorial part 1 "Hello world",Tutorial
604 @anchor{intro/tutorial02 doc}@anchor{6}@anchor{intro/tutorial02 tutorial-part-2-creating-a-trivial-machine-code-function}@anchor{7}
605 @section Tutorial part 2: Creating a trivial machine code function
608 Consider this C function:
619 How can we construct this at run-time using libgccjit?
621 First we need to include the relevant header:
624 #include <libgccjit.h>
629 All state associated with compilation is associated with a
630 @pxref{8,,gcc_jit_context *}.
632 Create one using @pxref{9,,gcc_jit_context_acquire()}:
635 gcc_jit_context *ctxt;
636 ctxt = gcc_jit_context_acquire ();
641 The JIT library has a system of types. It is statically-typed: every
642 expression is of a specific type, fixed at compile-time. In our example,
643 all of the expressions are of the C @cite{int} type, so let's obtain this from
644 the context, as a @pxref{a,,gcc_jit_type *}, using
645 @pxref{b,,gcc_jit_context_get_type()}:
648 gcc_jit_type *int_type =
649 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
654 @pxref{a,,gcc_jit_type *} is an example of a "contextual" object: every
655 entity in the API is associated with a @pxref{8,,gcc_jit_context *}.
657 Memory management is easy: all such "contextual" objects are automatically
658 cleaned up for you when the context is released, using
659 @pxref{c,,gcc_jit_context_release()}:
662 gcc_jit_context_release (ctxt);
667 so you don't need to manually track and cleanup all objects, just the
670 Although the API is C-based, there is a form of class hierarchy, which
688 There are casting methods for upcasting from subclasses to parent classes.
689 For example, @pxref{d,,gcc_jit_type_as_object()}:
692 gcc_jit_object *obj = gcc_jit_type_as_object (int_type);
697 One thing you can do with a @pxref{e,,gcc_jit_object *} is
698 to ask it for a human-readable description, using
699 @pxref{f,,gcc_jit_object_get_debug_string()}:
702 printf ("obj: %s\n", gcc_jit_object_get_debug_string (obj));
707 giving this text on stdout:
715 This is invaluable when debugging.
717 Let's create the function. To do so, we first need to construct
718 its single parameter, specifying its type and giving it a name,
719 using @pxref{10,,gcc_jit_context_new_param()}:
722 gcc_jit_param *param_i =
723 gcc_jit_context_new_param (ctxt, NULL, int_type, "i");
728 Now we can create the function, using
729 @pxref{11,,gcc_jit_context_new_function()}:
732 gcc_jit_function *func =
733 gcc_jit_context_new_function (ctxt, NULL,
734 GCC_JIT_FUNCTION_EXPORTED,
743 To define the code within the function, we must create basic blocks
744 containing statements.
746 Every basic block contains a list of statements, eventually terminated
747 by a statement that either returns, or jumps to another basic block.
749 Our function has no control-flow, so we just need one basic block:
752 gcc_jit_block *block = gcc_jit_function_new_block (func, NULL);
757 Our basic block is relatively simple: it immediately terminates by
758 returning the value of an expression.
760 We can build the expression using @pxref{12,,gcc_jit_context_new_binary_op()}:
763 gcc_jit_rvalue *expr =
764 gcc_jit_context_new_binary_op (
766 GCC_JIT_BINARY_OP_MULT, int_type,
767 gcc_jit_param_as_rvalue (param_i),
768 gcc_jit_param_as_rvalue (param_i));
773 A @pxref{13,,gcc_jit_rvalue *} is another example of a
774 @pxref{e,,gcc_jit_object *} subclass. We can upcast it using
775 @pxref{14,,gcc_jit_rvalue_as_object()} and as before print it with
776 @pxref{f,,gcc_jit_object_get_debug_string()}.
779 printf ("expr: %s\n",
780 gcc_jit_object_get_debug_string (
781 gcc_jit_rvalue_as_object (expr)));
794 Creating the expression in itself doesn't do anything; we have to add
795 this expression to a statement within the block. In this case, we use it
796 to build a return statement, which terminates the basic block:
799 gcc_jit_block_end_with_return (block, NULL, expr);
804 OK, we've populated the context. We can now compile it using
805 @pxref{15,,gcc_jit_context_compile()}:
808 gcc_jit_result *result;
809 result = gcc_jit_context_compile (ctxt);
814 and get a @pxref{16,,gcc_jit_result *}.
816 At this point we're done with the context; we can release it:
819 gcc_jit_context_release (ctxt);
824 We can now use @pxref{17,,gcc_jit_result_get_code()} to look up a specific
825 machine code routine within the result, in this case, the function we
829 void *fn_ptr = gcc_jit_result_get_code (result, "square");
832 fprintf (stderr, "NULL fn_ptr");
839 We can now cast the pointer to an appropriate function pointer type, and
843 typedef int (*fn_type) (int);
844 fn_type square = (fn_type)fn_ptr;
845 printf ("result: %d", square (5));
856 Once we're done with the code, we can release the result:
859 gcc_jit_result_release (result);
864 We can't call @code{square} anymore once we've released @code{result}.
873 @node Error-handling,Options,,Tutorial part 2 Creating a trivial machine code function
874 @anchor{intro/tutorial02 error-handling}@anchor{18}
875 @subsection Error-handling
878 Various kinds of errors are possible when using the API, such as
879 mismatched types in an assignment. You can only compile and get code
880 from a context if no errors occur.
882 Errors are printed on stderr; they typically contain the name of the API
883 entrypoint where the error occurred, and pertinent information on the
887 ./buggy-program: error: gcc_jit_block_add_assignment: mismatching types: assignment to i (type: int) from "hello world" (type: const char *)
892 The API is designed to cope with errors without crashing, so you can get
893 away with having a single error-handling check in your code:
896 void *fn_ptr = gcc_jit_result_get_code (result, "square");
899 fprintf (stderr, "NULL fn_ptr");
906 For more information, see the @pxref{19,,error-handling guide}
907 within the Topic eference.
909 @node Options,Full example,Error-handling,Tutorial part 2 Creating a trivial machine code function
910 @anchor{intro/tutorial02 options}@anchor{1a}
914 To get more information on what's going on, you can set debugging flags
915 on the context using @pxref{1b,,gcc_jit_context_set_bool_option()}.
917 @c (I'm deliberately not mentioning
918 @c :c:macro:`GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE` here since I think
919 @c it's probably more of use to implementors than to users)
921 Setting @pxref{1c,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE} will dump a
922 C-like representation to stderr when you compile (GCC's "GIMPLE"
926 gcc_jit_context_set_bool_option (
928 GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE,
930 result = gcc_jit_context_compile (ctxt);
936 square (signed int i)
948 We can see the generated machine code in assembler form (on stderr) by
949 setting @pxref{1d,,GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE} on the context
953 gcc_jit_context_set_bool_option (
955 GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
957 result = gcc_jit_context_compile (ctxt);
966 .type square, @@function
971 .cfi_def_cfa_offset 16
974 .cfi_def_cfa_register 6
984 .size square, .-square
985 .ident "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)"
986 .section .note.GNU-stack,"",@@progbits
991 By default, no optimizations are performed, the equivalent of GCC's
992 @cite{-O0} option. We can turn things up to e.g. @cite{-O3} by calling
993 @pxref{1e,,gcc_jit_context_set_int_option()} with
994 @pxref{1f,,GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}:
997 gcc_jit_context_set_int_option (
999 GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL,
1010 .type square, @@function
1020 .size square, .-square
1021 .ident "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)"
1022 .section .note.GNU-stack,"",@@progbits
1027 Naturally this has only a small effect on such a trivial function.
1029 @node Full example,,Options,Tutorial part 2 Creating a trivial machine code function
1030 @anchor{intro/tutorial02 full-example}@anchor{20}
1031 @subsection Full example
1034 Here's what the above looks like as a complete program:
1039 /* Usage example for libgccjit.so
1040 Copyright (C) 2014-2019 Free Software Foundation, Inc.
1042 This file is part of GCC.
1044 GCC is free software; you can redistribute it and/or modify it
1045 under the terms of the GNU General Public License as published by
1046 the Free Software Foundation; either version 3, or (at your option)
1049 GCC is distributed in the hope that it will be useful, but
1050 WITHOUT ANY WARRANTY; without even the implied warranty of
1051 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
1052 General Public License for more details.
1054 You should have received a copy of the GNU General Public License
1055 along with GCC; see the file COPYING3. If not see
1056 <http://www.gnu.org/licenses/>. */
1058 #include <libgccjit.h>
1064 create_code (gcc_jit_context *ctxt)
1066 /* Let's try to inject the equivalent of:
1073 gcc_jit_type *int_type =
1074 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
1075 gcc_jit_param *param_i =
1076 gcc_jit_context_new_param (ctxt, NULL, int_type, "i");
1077 gcc_jit_function *func =
1078 gcc_jit_context_new_function (ctxt, NULL,
1079 GCC_JIT_FUNCTION_EXPORTED,
1085 gcc_jit_block *block = gcc_jit_function_new_block (func, NULL);
1087 gcc_jit_rvalue *expr =
1088 gcc_jit_context_new_binary_op (
1090 GCC_JIT_BINARY_OP_MULT, int_type,
1091 gcc_jit_param_as_rvalue (param_i),
1092 gcc_jit_param_as_rvalue (param_i));
1094 gcc_jit_block_end_with_return (block, NULL, expr);
1098 main (int argc, char **argv)
1100 gcc_jit_context *ctxt = NULL;
1101 gcc_jit_result *result = NULL;
1103 /* Get a "context" object for working with the library. */
1104 ctxt = gcc_jit_context_acquire ();
1107 fprintf (stderr, "NULL ctxt");
1111 /* Set some options on the context.
1112 Let's see the code being generated, in assembler form. */
1113 gcc_jit_context_set_bool_option (
1115 GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
1118 /* Populate the context. */
1121 /* Compile the code. */
1122 result = gcc_jit_context_compile (ctxt);
1125 fprintf (stderr, "NULL result");
1129 /* We're done with the context; we can release it: */
1130 gcc_jit_context_release (ctxt);
1133 /* Extract the generated code from "result". */
1134 void *fn_ptr = gcc_jit_result_get_code (result, "square");
1137 fprintf (stderr, "NULL fn_ptr");
1141 typedef int (*fn_type) (int);
1142 fn_type square = (fn_type)fn_ptr;
1143 printf ("result: %d\n", square (5));
1147 gcc_jit_context_release (ctxt);
1149 gcc_jit_result_release (result);
1158 Building and running it:
1166 # Run the built program:
1173 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
1174 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
1176 @c This is free software: you can redistribute it and/or modify it
1177 @c under the terms of the GNU General Public License as published by
1178 @c the Free Software Foundation, either version 3 of the License, or
1179 @c (at your option) any later version.
1181 @c This program is distributed in the hope that it will be useful, but
1182 @c WITHOUT ANY WARRANTY; without even the implied warranty of
1183 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
1184 @c General Public License for more details.
1186 @c You should have received a copy of the GNU General Public License
1187 @c along with this program. If not, see
1188 @c <http://www.gnu.org/licenses/>.
1190 @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
1191 @anchor{intro/tutorial03 tutorial-part-3-loops-and-variables}@anchor{21}@anchor{intro/tutorial03 doc}@anchor{22}
1192 @section Tutorial part 3: Loops and variables
1195 Consider this C function:
1200 int loop_test (int n)
1203 for (int i = 0; i < n; i++)
1212 This example demonstrates some more features of libgccjit, with local
1213 variables and a loop.
1215 To break this down into libgccjit terms, it's usually easier to reword
1216 the @cite{for} loop as a @cite{while} loop, giving:
1221 int loop_test (int n)
1237 Here's what the final control flow graph will look like:
1244 @image{sum-of-squares1,,,image of a control flow graph,png}
1250 As before, we include the libgccjit header and make a
1251 @pxref{8,,gcc_jit_context *}.
1254 #include <libgccjit.h>
1258 gcc_jit_context *ctxt;
1259 ctxt = gcc_jit_context_acquire ();
1264 The function works with the C @cite{int} type:
1267 gcc_jit_type *the_type =
1268 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
1269 gcc_jit_type *return_type = the_type;
1274 though we could equally well make it work on, say, @cite{double}:
1277 gcc_jit_type *the_type =
1278 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_DOUBLE);
1283 Let's build the function:
1287 gcc_jit_context_new_param (ctxt, NULL, the_type, "n");
1288 gcc_jit_param *params[1] = @{n@};
1289 gcc_jit_function *func =
1290 gcc_jit_context_new_function (ctxt, NULL,
1291 GCC_JIT_FUNCTION_EXPORTED,
1300 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues.
1302 * Visualizing the control flow graph::
1303 * Full example: Full example<2>.
1307 @node Expressions lvalues and rvalues,Control flow,,Tutorial part 3 Loops and variables
1308 @anchor{intro/tutorial03 expressions-lvalues-and-rvalues}@anchor{23}
1309 @subsection Expressions: lvalues and rvalues
1312 The base class of expression is the @pxref{13,,gcc_jit_rvalue *},
1313 representing an expression that can be on the @emph{right}-hand side of
1314 an assignment: a value that can be computed somehow, and assigned
1315 @emph{to} a storage area (such as a variable). It has a specific
1316 @pxref{a,,gcc_jit_type *}.
1318 Anothe important class is @pxref{24,,gcc_jit_lvalue *}.
1319 A @pxref{24,,gcc_jit_lvalue *}. is something that can of the @emph{left}-hand
1320 side of an assignment: a storage area (such as a variable).
1322 In other words, every assignment can be thought of as:
1330 Note that @pxref{24,,gcc_jit_lvalue *} is a subclass of
1331 @pxref{13,,gcc_jit_rvalue *}, where in an assignment of the form:
1334 LVALUE_A = LVALUE_B;
1339 the @cite{LVALUE_B} implies reading the current value of that storage
1340 area, assigning it into the @cite{LVALUE_A}.
1342 So far the only expressions we've seen are @cite{i * i}:
1345 gcc_jit_rvalue *expr =
1346 gcc_jit_context_new_binary_op (
1348 GCC_JIT_BINARY_OP_MULT, int_type,
1349 gcc_jit_param_as_rvalue (param_i),
1350 gcc_jit_param_as_rvalue (param_i));
1355 which is a @pxref{13,,gcc_jit_rvalue *}, and the various function
1356 parameters: @cite{param_i} and @cite{param_n}, instances of
1357 @pxref{25,,gcc_jit_param *}, which is a subclass of
1358 @pxref{24,,gcc_jit_lvalue *} (and, in turn, of @pxref{13,,gcc_jit_rvalue *}):
1359 we can both read from and write to function parameters within the
1362 Our new example has a couple of local variables. We create them by
1363 calling @pxref{26,,gcc_jit_function_new_local()}, supplying a type and a
1369 gcc_jit_function_new_local (func, NULL, the_type, "i");
1370 gcc_jit_lvalue *sum =
1371 gcc_jit_function_new_local (func, NULL, the_type, "sum");
1376 These are instances of @pxref{24,,gcc_jit_lvalue *} - they can be read from
1379 Note that there is no precanned way to create @emph{and} initialize a variable
1388 Instead, having added the local to the function, we have to separately add
1389 an assignment of @cite{0} to @cite{local_i} at the beginning of the function.
1391 @node Control flow,Visualizing the control flow graph,Expressions lvalues and rvalues,Tutorial part 3 Loops and variables
1392 @anchor{intro/tutorial03 control-flow}@anchor{27}
1393 @subsection Control flow
1396 This function has a loop, so we need to build some basic blocks to
1397 handle the control flow. In this case, we need 4 blocks:
1403 before the loop (initializing the locals)
1406 the conditional at the top of the loop (comparing @cite{i < n})
1409 the body of the loop
1412 after the loop terminates (@cite{return sum})
1415 so we create these as @pxref{28,,gcc_jit_block *} instances within the
1416 @pxref{29,,gcc_jit_function *}:
1419 gcc_jit_block *b_initial =
1420 gcc_jit_function_new_block (func, "initial");
1421 gcc_jit_block *b_loop_cond =
1422 gcc_jit_function_new_block (func, "loop_cond");
1423 gcc_jit_block *b_loop_body =
1424 gcc_jit_function_new_block (func, "loop_body");
1425 gcc_jit_block *b_after_loop =
1426 gcc_jit_function_new_block (func, "after_loop");
1431 We now populate each block with statements.
1433 The entry block @cite{b_initial} consists of initializations followed by a jump
1434 to the conditional. We assign @cite{0} to @cite{i} and to @cite{sum}, using
1435 @pxref{2a,,gcc_jit_block_add_assignment()} to add
1436 an assignment statement, and using @pxref{2b,,gcc_jit_context_zero()} to get
1437 the constant value @cite{0} for the relevant type for the right-hand side of
1442 gcc_jit_block_add_assignment (
1445 gcc_jit_context_zero (ctxt, the_type));
1448 gcc_jit_block_add_assignment (
1451 gcc_jit_context_zero (ctxt, the_type));
1456 We can then terminate the entry block by jumping to the conditional:
1459 gcc_jit_block_end_with_jump (b_initial, NULL, b_loop_cond);
1464 The conditional block is equivalent to the line @cite{while (i < n)} from our
1465 C example. It contains a single statement: a conditional, which jumps to
1466 one of two destination blocks depending on a boolean
1467 @pxref{13,,gcc_jit_rvalue *}, in this case the comparison of @cite{i} and @cite{n}.
1468 We build the comparison using @pxref{2c,,gcc_jit_context_new_comparison()}:
1472 gcc_jit_rvalue *guard =
1473 gcc_jit_context_new_comparison (
1475 GCC_JIT_COMPARISON_GE,
1476 gcc_jit_lvalue_as_rvalue (i),
1477 gcc_jit_param_as_rvalue (n));
1482 and can then use this to add @cite{b_loop_cond}'s sole statement, via
1483 @pxref{2d,,gcc_jit_block_end_with_conditional()}:
1491 gcc_jit_block_end_with_conditional (
1494 b_after_loop, /* on_true */
1495 b_loop_body); /* on_false */
1500 Next, we populate the body of the loop.
1502 The C statement @cite{sum += i * i;} is an assignment operation, where an
1503 lvalue is modified "in-place". We use
1504 @pxref{2e,,gcc_jit_block_add_assignment_op()} to handle these operations:
1508 gcc_jit_block_add_assignment_op (
1511 GCC_JIT_BINARY_OP_PLUS,
1512 gcc_jit_context_new_binary_op (
1514 GCC_JIT_BINARY_OP_MULT, the_type,
1515 gcc_jit_lvalue_as_rvalue (i),
1516 gcc_jit_lvalue_as_rvalue (i)));
1521 The @cite{i++} can be thought of as @cite{i += 1}, and can thus be handled in
1522 a similar way. We use @pxref{2f,,gcc_jit_context_one()} to get the constant
1523 value @cite{1} (for the relevant type) for the right-hand side
1528 gcc_jit_block_add_assignment_op (
1531 GCC_JIT_BINARY_OP_PLUS,
1532 gcc_jit_context_one (ctxt, the_type));
1539 For numeric constants other than 0 or 1, we could use
1540 @pxref{30,,gcc_jit_context_new_rvalue_from_int()} and
1541 @pxref{31,,gcc_jit_context_new_rvalue_from_double()}.
1545 The loop body completes by jumping back to the conditional:
1548 gcc_jit_block_end_with_jump (b_loop_body, NULL, b_loop_cond);
1553 Finally, we populate the @cite{b_after_loop} block, reached when the loop
1554 conditional is false. We want to generate the equivalent of:
1562 so the block is just one statement:
1566 gcc_jit_block_end_with_return (
1569 gcc_jit_lvalue_as_rvalue (sum));
1576 You can intermingle block creation with statement creation,
1577 but given that the terminator statements generally include references
1578 to other blocks, I find it's clearer to create all the blocks,
1579 @emph{then} all the statements.
1583 We've finished populating the function. As before, we can now compile it
1587 gcc_jit_result *result;
1588 result = gcc_jit_context_compile (ctxt);
1590 typedef int (*loop_test_fn_type) (int);
1591 loop_test_fn_type loop_test =
1592 (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
1595 printf ("result: %d", loop_test (10));
1606 @node Visualizing the control flow graph,Full example<2>,Control flow,Tutorial part 3 Loops and variables
1607 @anchor{intro/tutorial03 visualizing-the-control-flow-graph}@anchor{32}
1608 @subsection Visualizing the control flow graph
1611 You can see the control flow graph of a function using
1612 @pxref{33,,gcc_jit_function_dump_to_dot()}:
1615 gcc_jit_function_dump_to_dot (func, "/tmp/sum-of-squares.dot");
1620 giving a .dot file in GraphViz format.
1622 You can convert this to an image using @cite{dot}:
1625 $ dot -Tpng /tmp/sum-of-squares.dot -o /tmp/sum-of-squares.png
1630 or use a viewer (my preferred one is xdot.py; see
1631 @indicateurl{https://github.com/jrfonseca/xdot.py}; on Fedora you can
1632 install it with @cite{yum install python-xdot}):
1639 @image{sum-of-squares1,,,image of a control flow graph,png}
1645 @node Full example<2>,,Visualizing the control flow graph,Tutorial part 3 Loops and variables
1646 @anchor{intro/tutorial03 full-example}@anchor{34}
1647 @subsection Full example
1653 /* Usage example for libgccjit.so
1654 Copyright (C) 2014-2019 Free Software Foundation, Inc.
1656 This file is part of GCC.
1658 GCC is free software; you can redistribute it and/or modify it
1659 under the terms of the GNU General Public License as published by
1660 the Free Software Foundation; either version 3, or (at your option)
1663 GCC is distributed in the hope that it will be useful, but
1664 WITHOUT ANY WARRANTY; without even the implied warranty of
1665 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
1666 General Public License for more details.
1668 You should have received a copy of the GNU General Public License
1669 along with GCC; see the file COPYING3. If not see
1670 <http://www.gnu.org/licenses/>. */
1672 #include <libgccjit.h>
1678 create_code (gcc_jit_context *ctxt)
1681 Simple sum-of-squares, to test conditionals and looping
1683 int loop_test (int n)
1687 for (i = 0; i < n ; i ++)
1693 gcc_jit_type *the_type =
1694 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
1695 gcc_jit_type *return_type = the_type;
1698 gcc_jit_context_new_param (ctxt, NULL, the_type, "n");
1699 gcc_jit_param *params[1] = @{n@};
1700 gcc_jit_function *func =
1701 gcc_jit_context_new_function (ctxt, NULL,
1702 GCC_JIT_FUNCTION_EXPORTED,
1709 gcc_jit_function_new_local (func, NULL, the_type, "i");
1710 gcc_jit_lvalue *sum =
1711 gcc_jit_function_new_local (func, NULL, the_type, "sum");
1713 gcc_jit_block *b_initial =
1714 gcc_jit_function_new_block (func, "initial");
1715 gcc_jit_block *b_loop_cond =
1716 gcc_jit_function_new_block (func, "loop_cond");
1717 gcc_jit_block *b_loop_body =
1718 gcc_jit_function_new_block (func, "loop_body");
1719 gcc_jit_block *b_after_loop =
1720 gcc_jit_function_new_block (func, "after_loop");
1723 gcc_jit_block_add_assignment (
1726 gcc_jit_context_zero (ctxt, the_type));
1729 gcc_jit_block_add_assignment (
1732 gcc_jit_context_zero (ctxt, the_type));
1734 gcc_jit_block_end_with_jump (b_initial, NULL, b_loop_cond);
1737 gcc_jit_block_end_with_conditional (
1739 gcc_jit_context_new_comparison (
1741 GCC_JIT_COMPARISON_GE,
1742 gcc_jit_lvalue_as_rvalue (i),
1743 gcc_jit_param_as_rvalue (n)),
1748 gcc_jit_block_add_assignment_op (
1751 GCC_JIT_BINARY_OP_PLUS,
1752 gcc_jit_context_new_binary_op (
1754 GCC_JIT_BINARY_OP_MULT, the_type,
1755 gcc_jit_lvalue_as_rvalue (i),
1756 gcc_jit_lvalue_as_rvalue (i)));
1759 gcc_jit_block_add_assignment_op (
1762 GCC_JIT_BINARY_OP_PLUS,
1763 gcc_jit_context_one (ctxt, the_type));
1765 gcc_jit_block_end_with_jump (b_loop_body, NULL, b_loop_cond);
1768 gcc_jit_block_end_with_return (
1771 gcc_jit_lvalue_as_rvalue (sum));
1775 main (int argc, char **argv)
1777 gcc_jit_context *ctxt = NULL;
1778 gcc_jit_result *result = NULL;
1780 /* Get a "context" object for working with the library. */
1781 ctxt = gcc_jit_context_acquire ();
1784 fprintf (stderr, "NULL ctxt");
1788 /* Set some options on the context.
1789 Let's see the code being generated, in assembler form. */
1790 gcc_jit_context_set_bool_option (
1792 GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
1795 /* Populate the context. */
1798 /* Compile the code. */
1799 result = gcc_jit_context_compile (ctxt);
1802 fprintf (stderr, "NULL result");
1806 /* Extract the generated code from "result". */
1807 typedef int (*loop_test_fn_type) (int);
1808 loop_test_fn_type loop_test =
1809 (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
1812 fprintf (stderr, "NULL loop_test");
1816 /* Run the generated code. */
1817 int val = loop_test (10);
1818 printf("loop_test returned: %d\n", val);
1821 gcc_jit_context_release (ctxt);
1822 gcc_jit_result_release (result);
1831 Building and running it:
1835 tut03-sum-of-squares.c \
1836 -o tut03-sum-of-squares \
1839 # Run the built program:
1840 $ ./tut03-sum-of-squares
1841 loop_test returned: 285
1846 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
1847 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
1849 @c This is free software: you can redistribute it and/or modify it
1850 @c under the terms of the GNU General Public License as published by
1851 @c the Free Software Foundation, either version 3 of the License, or
1852 @c (at your option) any later version.
1854 @c This program is distributed in the hope that it will be useful, but
1855 @c WITHOUT ANY WARRANTY; without even the implied warranty of
1856 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
1857 @c General Public License for more details.
1859 @c You should have received a copy of the GNU General Public License
1860 @c along with this program. If not, see
1861 @c <http://www.gnu.org/licenses/>.
1863 @node Tutorial part 4 Adding JIT-compilation to a toy interpreter,Tutorial part 5 Implementing an Ahead-of-Time compiler,Tutorial part 3 Loops and variables,Tutorial
1864 @anchor{intro/tutorial04 tutorial-part-4-adding-jit-compilation-to-a-toy-interpreter}@anchor{35}@anchor{intro/tutorial04 doc}@anchor{36}
1865 @section Tutorial part 4: Adding JIT-compilation to a toy interpreter
1868 In this example we construct a "toy" interpreter, and add JIT-compilation
1872 * Our toy interpreter::
1873 * Compiling to machine code::
1874 * Setting things up::
1875 * Populating the function::
1876 * Verifying the control flow graph::
1877 * Compiling the context::
1878 * Single-stepping through the generated code::
1879 * Examining the generated code::
1880 * Putting it all together::
1881 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?.
1885 @node Our toy interpreter,Compiling to machine code,,Tutorial part 4 Adding JIT-compilation to a toy interpreter
1886 @anchor{intro/tutorial04 our-toy-interpreter}@anchor{37}
1887 @subsection Our toy interpreter
1890 It's a stack-based interpreter, and is intended as a (very simple) example
1891 of the kind of bytecode interpreter seen in dynamic languages such as
1894 For the sake of simplicity, our toy virtual machine is very limited:
1902 The only data type is @cite{int}
1905 It can only work on one function at a time (so that the only
1906 function call that can be made is to recurse).
1909 Functions can only take one parameter.
1912 Functions have a stack of @cite{int} values.
1915 We'll implement function call within the interpreter by calling a
1916 function in our implementation, rather than implementing our own
1920 The parser is only good enough to get the examples to work.
1924 Naturally, a real interpreter would be much more complicated that this.
1926 The following operations are supported:
1929 @multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxx}
1952 Duplicate top of stack.
1968 Swap top two elements
1985 Add the top two elements
2002 Likewise, but subtract.
2018 Likewise, but multiply.
2035 elements on the stack
2036 and push a nonzero/zero
2053 Recurse, passing the top
2071 Return the top of the
2084 PUSH_CONST @cite{arg}
2100 JUMP_ABS_IF_TRUE @cite{arg}
2104 Pop; if top of stack was
2119 Programs can be interpreted, disassembled, and compiled to machine code.
2121 The interpreter reads @code{.toy} scripts. Here's what a simple recursive
2122 factorial program looks like, the script @code{factorial.toy}.
2123 The parser ignores lines beginning with a @cite{#}.
2128 # Simple recursive factorial implementation, roughly equivalent to:
2130 # int factorial (int arg)
2134 # return arg * factorial (arg - 1)
2146 # stack: [arg, arg, 2]
2150 # stack: [arg, (arg < 2)]
2162 # stack: [arg, arg, 1]
2166 # stack: [arg, (arg - 1)
2170 # stack: [arg, factorial(arg - 1)]
2174 # stack: [arg * factorial(arg - 1)]
2184 The interpreter is a simple infinite loop with a big @code{switch} statement
2185 based on what the next opcode is:
2192 toyvm_function_interpret (toyvm_function *fn, int arg, FILE *trace)
2195 #define PUSH(ARG) (toyvm_frame_push (&frame, (ARG)))
2196 #define POP(ARG) (toyvm_frame_pop (&frame))
2198 frame.frm_function = fn;
2200 frame.frm_cur_depth = 0;
2208 assert (frame.frm_pc < fn->fn_num_ops);
2209 op = &fn->fn_ops[frame.frm_pc++];
2213 toyvm_frame_dump_stack (&frame, trace);
2214 toyvm_function_disassemble_op (fn, op, frame.frm_pc, trace);
2217 switch (op->op_opcode)
2219 /* Ops taking no operand. */
2239 case BINARY_SUBTRACT:
2251 case BINARY_COMPARE_LT:
2259 x = toyvm_function_interpret (fn, x, trace);
2266 /* Ops taking an operand. */
2268 PUSH (op->op_operand);
2271 case JUMP_ABS_IF_TRUE:
2274 frame.frm_pc = op->op_operand;
2278 assert (0); /* unknown opcode */
2280 @} /* end of switch on opcode */
2281 @} /* end of while loop */
2293 @node Compiling to machine code,Setting things up,Our toy interpreter,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2294 @anchor{intro/tutorial04 compiling-to-machine-code}@anchor{38}
2295 @subsection Compiling to machine code
2298 We want to generate machine code that can be cast to this type and
2299 then directly executed in-process:
2304 typedef int (*toyvm_compiled_code) (int);
2312 The lifetime of the code is tied to that of a @pxref{16,,gcc_jit_result *}.
2313 We'll handle this by bundling them up in a structure, so that we can
2314 clean them up together by calling @pxref{39,,gcc_jit_result_release()}:
2320 struct toyvm_compiled_function
2322 gcc_jit_result *cf_jit_result;
2323 toyvm_compiled_code cf_code;
2332 Our compiler isn't very sophisticated; it takes the implementation of
2333 each opcode above, and maps it directly to the operations supported by
2336 How should we handle the stack? In theory we could calculate what the
2337 stack depth will be at each opcode, and optimize away the stack
2338 manipulation "by hand". We'll see below that libgccjit is able to do
2339 this for us, so we'll implement stack manipulation
2340 in a direct way, by creating a @code{stack} array and @code{stack_depth}
2341 variables, local within the generated function, equivalent to this C code:
2345 int stack[MAX_STACK_DEPTH];
2350 We'll also have local variables @code{x} and @code{y} for use when implementing
2351 the opcodes, equivalent to this:
2360 This means our compiler has the following state:
2366 struct compilation_state
2368 gcc_jit_context *ctxt;
2370 gcc_jit_type *int_type;
2371 gcc_jit_type *bool_type;
2372 gcc_jit_type *stack_type; /* int[MAX_STACK_DEPTH] */
2374 gcc_jit_rvalue *const_one;
2376 gcc_jit_function *fn;
2377 gcc_jit_param *param_arg;
2378 gcc_jit_lvalue *stack;
2379 gcc_jit_lvalue *stack_depth;
2383 gcc_jit_location *op_locs[MAX_OPS];
2384 gcc_jit_block *initial_block;
2385 gcc_jit_block *op_blocks[MAX_OPS];
2395 @node Setting things up,Populating the function,Compiling to machine code,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2396 @anchor{intro/tutorial04 setting-things-up}@anchor{3a}
2397 @subsection Setting things up
2400 First we create our types:
2406 gcc_jit_context_get_type (state.ctxt, GCC_JIT_TYPE_INT);
2408 gcc_jit_context_get_type (state.ctxt, GCC_JIT_TYPE_BOOL);
2410 gcc_jit_context_new_array_type (state.ctxt, NULL,
2411 state.int_type, MAX_STACK_DEPTH);
2419 along with extracting a useful @cite{int} constant:
2424 state.const_one = gcc_jit_context_one (state.ctxt, state.int_type);
2432 We'll implement push and pop in terms of the @code{stack} array and
2433 @code{stack_depth}. Here are helper functions for adding statements to
2434 a block, implementing pushing and popping values:
2441 add_push (compilation_state *state,
2442 gcc_jit_block *block,
2443 gcc_jit_rvalue *rvalue,
2444 gcc_jit_location *loc)
2446 /* stack[stack_depth] = RVALUE */
2447 gcc_jit_block_add_assignment (
2450 /* stack[stack_depth] */
2451 gcc_jit_context_new_array_access (
2454 gcc_jit_lvalue_as_rvalue (state->stack),
2455 gcc_jit_lvalue_as_rvalue (state->stack_depth)),
2458 /* "stack_depth++;". */
2459 gcc_jit_block_add_assignment_op (
2463 GCC_JIT_BINARY_OP_PLUS,
2468 add_pop (compilation_state *state,
2469 gcc_jit_block *block,
2470 gcc_jit_lvalue *lvalue,
2471 gcc_jit_location *loc)
2473 /* "--stack_depth;". */
2474 gcc_jit_block_add_assignment_op (
2478 GCC_JIT_BINARY_OP_MINUS,
2481 /* "LVALUE = stack[stack_depth];". */
2482 gcc_jit_block_add_assignment (
2486 /* stack[stack_depth] */
2487 gcc_jit_lvalue_as_rvalue (
2488 gcc_jit_context_new_array_access (
2491 gcc_jit_lvalue_as_rvalue (state->stack),
2492 gcc_jit_lvalue_as_rvalue (state->stack_depth))));
2501 We will support single-stepping through the generated code in the
2502 debugger, so we need to create @pxref{3b,,gcc_jit_location} instances, one
2503 per operation in the source code. These will reference the lines of
2504 e.g. @code{factorial.toy}.
2509 for (pc = 0; pc < fn->fn_num_ops; pc++)
2511 toyvm_op *op = &fn->fn_ops[pc];
2513 state.op_locs[pc] = gcc_jit_context_new_location (state.ctxt,
2525 Let's create the function itself. As usual, we create its parameter
2526 first, then use the parameter to create the function:
2532 gcc_jit_context_new_param (state.ctxt, state.op_locs[0],
2533 state.int_type, "arg");
2535 gcc_jit_context_new_function (state.ctxt,
2537 GCC_JIT_FUNCTION_EXPORTED,
2540 1, &state.param_arg, 0);
2548 We create the locals within the function.
2554 gcc_jit_function_new_local (state.fn, NULL,
2555 state.stack_type, "stack");
2557 gcc_jit_function_new_local (state.fn, NULL,
2558 state.int_type, "stack_depth");
2560 gcc_jit_function_new_local (state.fn, NULL,
2561 state.int_type, "x");
2563 gcc_jit_function_new_local (state.fn, NULL,
2564 state.int_type, "y");
2572 @node Populating the function,Verifying the control flow graph,Setting things up,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2573 @anchor{intro/tutorial04 populating-the-function}@anchor{3c}
2574 @subsection Populating the function
2577 There's some one-time initialization, and the API treats the first block
2578 you create as the entrypoint of the function, so we need to create that
2584 state.initial_block = gcc_jit_function_new_block (state.fn, "initial");
2592 We can now create blocks for each of the operations. Most of these will
2593 be consolidated into larger blocks when the optimizer runs.
2598 for (pc = 0; pc < fn->fn_num_ops; pc++)
2601 sprintf (buf, "instr%i", pc);
2602 state.op_blocks[pc] = gcc_jit_function_new_block (state.fn, buf);
2611 Now that we have a block it can jump to when it's done, we can populate
2618 /* "stack_depth = 0;". */
2619 gcc_jit_block_add_assignment (
2620 state.initial_block,
2623 gcc_jit_context_zero (state.ctxt, state.int_type));
2625 /* "PUSH (arg);". */
2627 state.initial_block,
2628 gcc_jit_param_as_rvalue (state.param_arg),
2631 /* ...and jump to insn 0. */
2632 gcc_jit_block_end_with_jump (state.initial_block,
2634 state.op_blocks[0]);
2642 We can now populate the blocks for the individual operations. We loop
2643 through them, adding instructions to their blocks:
2648 for (pc = 0; pc < fn->fn_num_ops; pc++)
2650 gcc_jit_location *loc = state.op_locs[pc];
2652 gcc_jit_block *block = state.op_blocks[pc];
2653 gcc_jit_block *next_block = (pc < fn->fn_num_ops
2654 ? state.op_blocks[pc + 1]
2658 op = &fn->fn_ops[pc];
2666 We're going to have another big @code{switch} statement for implementing
2667 the opcodes, this time for compiling them, rather than interpreting
2668 them. It's helpful to have macros for implementing push and pop, so that
2669 we can make the @code{switch} statement that's coming up look as much as
2670 possible like the one above within the interpreter:
2674 #define X_EQUALS_POP()\
2675 add_pop (&state, block, state.x, loc)
2676 #define Y_EQUALS_POP()\
2677 add_pop (&state, block, state.y, loc)
2678 #define PUSH_RVALUE(RVALUE)\
2679 add_push (&state, block, (RVALUE), loc)
2681 PUSH_RVALUE (gcc_jit_lvalue_as_rvalue (state.x))
2683 PUSH_RVALUE (gcc_jit_lvalue_as_rvalue (state.y))
2692 A particularly clever implementation would have an @emph{identical}
2693 @code{switch} statement shared by the interpreter and the compiler, with
2694 some preprocessor "magic". We're not doing that here, for the sake
2699 When I first implemented this compiler, I accidentally missed an edit
2700 when copying and pasting the @code{Y_EQUALS_POP} macro, so that popping the
2701 stack into @code{y} instead erroneously assigned it to @code{x}, leaving @code{y}
2704 To track this kind of thing down, we can use
2705 @pxref{3d,,gcc_jit_block_add_comment()} to add descriptive comments
2706 to the internal representation. This is invaluable when looking through
2707 the generated IR for, say @code{factorial}:
2713 gcc_jit_block_add_comment (block, loc, opcode_names[op->op_opcode]);
2721 We can now write the big @code{switch} statement that implements the
2722 individual opcodes, populating the relevant block with statements:
2728 switch (op->op_opcode)
2747 gcc_jit_context_new_binary_op (
2750 GCC_JIT_BINARY_OP_PLUS,
2752 gcc_jit_lvalue_as_rvalue (state.x),
2753 gcc_jit_lvalue_as_rvalue (state.y)));
2756 case BINARY_SUBTRACT:
2760 gcc_jit_context_new_binary_op (
2763 GCC_JIT_BINARY_OP_MINUS,
2765 gcc_jit_lvalue_as_rvalue (state.x),
2766 gcc_jit_lvalue_as_rvalue (state.y)));
2773 gcc_jit_context_new_binary_op (
2776 GCC_JIT_BINARY_OP_MULT,
2778 gcc_jit_lvalue_as_rvalue (state.x),
2779 gcc_jit_lvalue_as_rvalue (state.y)));
2782 case BINARY_COMPARE_LT:
2786 /* cast of bool to int */
2787 gcc_jit_context_new_cast (
2790 /* (x < y) as a bool */
2791 gcc_jit_context_new_comparison (
2794 GCC_JIT_COMPARISON_LT,
2795 gcc_jit_lvalue_as_rvalue (state.x),
2796 gcc_jit_lvalue_as_rvalue (state.y)),
2803 gcc_jit_rvalue *arg = gcc_jit_lvalue_as_rvalue (state.x);
2805 gcc_jit_context_new_call (
2815 gcc_jit_block_end_with_return (
2818 gcc_jit_lvalue_as_rvalue (state.x));
2821 /* Ops taking an operand. */
2824 gcc_jit_context_new_rvalue_from_int (
2830 case JUMP_ABS_IF_TRUE:
2832 gcc_jit_block_end_with_conditional (
2836 gcc_jit_context_new_cast (
2839 gcc_jit_lvalue_as_rvalue (state.x),
2841 state.op_blocks[op->op_operand], /* on_true */
2842 next_block); /* on_false */
2847 @} /* end of switch on opcode */
2855 Every block must be terminated, via a call to one of the
2856 @code{gcc_jit_block_end_with_} entrypoints. This has been done for two
2857 of the opcodes, but we need to do it for the other ones, by jumping
2863 if (op->op_opcode != JUMP_ABS_IF_TRUE
2864 && op->op_opcode != RETURN)
2865 gcc_jit_block_end_with_jump (
2876 This is analogous to simply incrementing the program counter.
2878 @node Verifying the control flow graph,Compiling the context,Populating the function,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2879 @anchor{intro/tutorial04 verifying-the-control-flow-graph}@anchor{3e}
2880 @subsection Verifying the control flow graph
2883 Having finished looping over the blocks, the context is complete.
2885 As before, we can verify that the control flow and statements are sane by
2886 using @pxref{33,,gcc_jit_function_dump_to_dot()}:
2889 gcc_jit_function_dump_to_dot (state.fn, "/tmp/factorial.dot");
2894 and viewing the result. Note how the label names, comments, and
2895 variable names show up in the dump, to make it easier to spot
2896 errors in our compiler.
2903 @image{factorial1,,,image of a control flow graph,png}
2909 @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
2910 @anchor{intro/tutorial04 compiling-the-context}@anchor{3f}
2911 @subsection Compiling the context
2914 Having finished looping over the blocks and populating them with
2915 statements, the context is complete.
2917 We can now compile it, and extract machine code from the result:
2922 gcc_jit_result *jit_result = gcc_jit_context_compile (state.ctxt);
2923 gcc_jit_context_release (state.ctxt);
2925 toyvm_compiled_function *toyvm_result =
2926 (toyvm_compiled_function *)calloc (1, sizeof (toyvm_compiled_function));
2929 fprintf (stderr, "out of memory allocating toyvm_compiled_function\n");
2930 gcc_jit_result_release (jit_result);
2934 toyvm_result->cf_jit_result = jit_result;
2935 toyvm_result->cf_code =
2936 (toyvm_compiled_code)gcc_jit_result_get_code (jit_result,
2941 return toyvm_result;
2946 #define CHECK_NON_NULL(PTR) \
2948 if ((PTR) != NULL) \
2950 pass ("%s: %s is non-null", test, #PTR); \
2954 fail ("%s: %s is NULL", test, #PTR); \
2959 #define CHECK_VALUE(ACTUAL, EXPECTED) \
2961 if ((ACTUAL) == (EXPECTED)) \
2963 pass ("%s: actual: %s == expected: %s", test, #ACTUAL, #EXPECTED); \
2967 fail ("%s: actual: %s != expected: %s", test, #ACTUAL, #EXPECTED); \
2968 fprintf (stderr, "incorrect value\n"); \
2974 test_script (const char *scripts_dir, const char *script_name, int input,
2975 int expected_result)
2979 int interpreted_result;
2980 toyvm_compiled_function *compiled_fn;
2981 toyvm_compiled_code code;
2982 int compiled_result;
2984 snprintf (test, sizeof (test), "toyvm.c: %s", script_name);
2986 script_path = (char *)malloc (strlen (scripts_dir)
2987 + strlen (script_name) + 1);
2988 CHECK_NON_NULL (script_path);
2989 sprintf (script_path, "%s%s", scripts_dir, script_name);
2991 fn = toyvm_function_parse (script_path, script_name);
2992 CHECK_NON_NULL (fn);
2994 interpreted_result = toyvm_function_interpret (fn, input, NULL);
2995 CHECK_VALUE (interpreted_result, expected_result);
2997 compiled_fn = toyvm_function_compile (fn);
2998 CHECK_NON_NULL (compiled_fn);
3000 code = (toyvm_compiled_code)compiled_fn->cf_code;
3001 CHECK_NON_NULL (code);
3003 compiled_result = code (input);
3004 CHECK_VALUE (compiled_result, expected_result);
3006 gcc_jit_result_release (compiled_fn->cf_jit_result);
3012 #define PATH_TO_SCRIPTS ("/jit/docs/examples/tut04-toyvm/")
3020 snprintf (test, sizeof (test), "toyvm.c");
3022 /* We need to locate the test scripts.
3023 Rely on "srcdir" being set in the environment. */
3025 srcdir = getenv ("srcdir");
3026 CHECK_NON_NULL (srcdir);
3028 scripts_dir = (char *)malloc (strlen (srcdir) + strlen(PATH_TO_SCRIPTS)
3030 CHECK_NON_NULL (scripts_dir);
3031 sprintf (scripts_dir, "%s%s", srcdir, PATH_TO_SCRIPTS);
3033 test_script (scripts_dir, "factorial.toy", 10, 3628800);
3034 test_script (scripts_dir, "fibonacci.toy", 10, 55);
3040 main (int argc, char **argv)
3042 const char *filename = NULL;
3043 toyvm_function *fn = NULL;
3045 /* If called with no args, assume we're being run by the test suite. */
3055 "%s FILENAME INPUT: Parse and run a .toy file\n",
3061 fn = toyvm_function_parse (filename, filename);
3066 toyvm_function_disassemble (fn, stdout);
3068 printf ("interpreter result: %d\n",
3069 toyvm_function_interpret (fn, atoi (argv[2]), NULL));
3071 /* JIT-compilation. */
3072 toyvm_compiled_function *compiled_fn
3073 = toyvm_function_compile (fn);
3075 toyvm_compiled_code code = compiled_fn->cf_code;
3076 printf ("compiler result: %d\n",
3077 code (atoi (argv[2])));
3079 gcc_jit_result_release (compiled_fn->cf_jit_result);
3090 We can now run the result:
3095 toyvm_compiled_function *compiled_fn
3096 = toyvm_function_compile (fn);
3098 toyvm_compiled_code code = compiled_fn->cf_code;
3099 printf ("compiler result: %d\n",
3100 code (atoi (argv[2])));
3102 gcc_jit_result_release (compiled_fn->cf_jit_result);
3111 @node Single-stepping through the generated code,Examining the generated code,Compiling the context,Tutorial part 4 Adding JIT-compilation to a toy interpreter
3112 @anchor{intro/tutorial04 single-stepping-through-the-generated-code}@anchor{40}
3113 @subsection Single-stepping through the generated code
3116 It's possible to debug the generated code. To do this we need to both:
3124 Set up source code locations for our statements, so that we can
3125 meaningfully step through the code. We did this above by
3126 calling @pxref{41,,gcc_jit_context_new_location()} and using the
3130 Enable the generation of debugging information, by setting
3131 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} on the
3132 @pxref{8,,gcc_jit_context} via
3133 @pxref{1b,,gcc_jit_context_set_bool_option()}:
3136 gcc_jit_context_set_bool_option (
3138 GCC_JIT_BOOL_OPTION_DEBUGINFO,
3146 Having done this, we can put a breakpoint on the generated function:
3149 $ gdb --args ./toyvm factorial.toy 10
3150 (gdb) break factorial
3151 Function "factorial" not defined.
3152 Make breakpoint pending on future shared library load? (y or [n]) y
3153 Breakpoint 1 (factorial) pending.
3155 Breakpoint 1, factorial (arg=10) at factorial.toy:14
3161 We've set up location information, which references @code{factorial.toy}.
3162 This allows us to use e.g. @code{list} to see where we are in the script:
3172 15 # stack: [arg, arg]
3180 and to step through the function, examining the data:
3186 22 BINARY_COMPARE_LT
3188 $5 = @{10, 10, 2, 0, -7152, 32767, 0, 0@}
3189 (gdb) print stack_depth
3195 You'll see that the parts of the @code{stack} array that haven't been
3196 touched yet are uninitialized.
3200 Turning on optimizations may lead to unpredictable results when
3201 stepping through the generated code: the execution may appear to
3202 "jump around" the source code. This is analogous to turning up the
3203 optimization level in a regular compiler.
3207 @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
3208 @anchor{intro/tutorial04 examining-the-generated-code}@anchor{43}
3209 @subsection Examining the generated code
3212 How good is the optimized code?
3214 We can turn up optimizations, by calling
3215 @pxref{1e,,gcc_jit_context_set_int_option()} with
3216 @pxref{1f,,GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}:
3219 gcc_jit_context_set_int_option (
3221 GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL,
3227 One of GCC's internal representations is called "gimple". A dump of the
3228 initial gimple representation of the code can be seen by setting:
3231 gcc_jit_context_set_bool_option (ctxt,
3232 GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE,
3238 With optimization on and source locations displayed, this gives:
3240 @c We'll use "c" for gimple dumps
3243 factorial (signed int arg)
3245 <unnamed type> D.80;
3253 signed int stack_depth;
3254 signed int stack[8];
3260 stack[stack_depth] = arg;
3261 stack_depth = stack_depth + 1;
3265 stack_depth = stack_depth + -1;
3266 x = stack[stack_depth];
3267 stack[stack_depth] = x;
3268 stack_depth = stack_depth + 1;
3269 stack[stack_depth] = x;
3270 stack_depth = stack_depth + 1;
3274 stack[stack_depth] = 2;
3275 stack_depth = stack_depth + 1;
3283 You can see the generated machine code in assembly form via:
3286 gcc_jit_context_set_bool_option (
3288 GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
3290 result = gcc_jit_context_compile (ctxt);
3295 which shows that (on this x86_64 box) the compiler has unrolled the loop
3296 and is using MMX instructions to perform several multiplications
3305 .type factorial, @@function
3308 .file 1 "factorial.toy"
3319 leal 0(,%rcx,4), %esi
3325 movl %eax, -16(%rsp)
3327 movd -16(%rsp), %xmm0
3328 movl %edi, -16(%rsp)
3329 movl %eax, -12(%rsp)
3330 movd -16(%rsp), %xmm1
3332 movl %edx, -16(%rsp)
3333 movd -12(%rsp), %xmm4
3334 movd -16(%rsp), %xmm6
3335 punpckldq %xmm4, %xmm0
3336 movdqa .LC1(%rip), %xmm4
3337 punpckldq %xmm6, %xmm1
3338 punpcklqdq %xmm0, %xmm1
3339 movdqa .LC0(%rip), %xmm0
3341 # etc - edited for brevity
3346 This is clearly overkill for a function that will likely overflow the
3347 @code{int} type before the vectorization is worthwhile - but then again, this
3350 Turning down the optimization level to 2:
3353 gcc_jit_context_set_int_option (
3355 GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL,
3361 yields this code, which is simple enough to quote in its entirety:
3368 .type factorial, @@function
3397 .size factorial, .-factorial
3398 .ident "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-%@{gcc_release@})"
3399 .section .note.GNU-stack,"",@@progbits
3404 Note that the stack pushing and popping have been eliminated, as has the
3405 recursive call (in favor of an iteration).
3407 @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
3408 @anchor{intro/tutorial04 putting-it-all-together}@anchor{44}
3409 @subsection Putting it all together
3412 The complete example can be seen in the source tree at
3413 @code{gcc/jit/docs/examples/tut04-toyvm/toyvm.c}
3415 along with a Makefile and a couple of sample .toy scripts:
3419 drwxrwxr-x. 2 david david 4096 Sep 19 17:46 .
3420 drwxrwxr-x. 3 david david 4096 Sep 19 15:26 ..
3421 -rw-rw-r--. 1 david david 615 Sep 19 12:43 factorial.toy
3422 -rw-rw-r--. 1 david david 834 Sep 19 13:08 fibonacci.toy
3423 -rw-rw-r--. 1 david david 238 Sep 19 14:22 Makefile
3424 -rw-rw-r--. 1 david david 16457 Sep 19 17:07 toyvm.c
3427 g++ -Wall -g -o toyvm toyvm.c -lgccjit
3429 $ ./toyvm factorial.toy 10
3430 interpreter result: 3628800
3431 compiler result: 3628800
3433 $ ./toyvm fibonacci.toy 10
3434 interpreter result: 55
3440 @node Behind the curtain How does our code get optimized?,,Putting it all together,Tutorial part 4 Adding JIT-compilation to a toy interpreter
3441 @anchor{intro/tutorial04 behind-the-curtain-how-does-our-code-get-optimized}@anchor{45}
3442 @subsection Behind the curtain: How does our code get optimized?
3445 Our example is done, but you may be wondering about exactly how the
3446 compiler turned what we gave it into the machine code seen above.
3448 We can examine what the compiler is doing in detail by setting:
3451 gcc_jit_context_set_bool_option (state.ctxt,
3452 GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING,
3454 gcc_jit_context_set_bool_option (state.ctxt,
3455 GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES,
3461 This will dump detailed information about the compiler's state to a
3462 directory under @code{/tmp}, and keep it from being cleaned up.
3464 The precise names and their formats of these files is subject to change.
3465 Higher optimization levels lead to more files.
3466 Here's what I saw (edited for brevity; there were almost 200 files):
3469 intermediate files written to /tmp/libgccjit-KPQbGw
3470 $ ls /tmp/libgccjit-KPQbGw/
3472 fake.c.000i.type-inheritance
3474 fake.c.007t.omplower
3478 fake.c.014i.visibility
3479 fake.c.015i.early_local_cleanups
3486 The gimple code is converted into Static Single Assignment form,
3487 with annotations for use when generating the debuginfo:
3490 $ less /tmp/libgccjit-KPQbGw/fake.c.016t.ssa
3496 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3498 factorial (signed int arg)
3500 signed int stack[8];
3501 signed int stack_depth;
3513 # DEBUG stack_depth => stack_depth_3
3514 stack[stack_depth_3] = arg_5(D);
3515 stack_depth_7 = stack_depth_3 + 1;
3516 # DEBUG stack_depth => stack_depth_7
3517 # DEBUG instr0 => NULL
3518 # DEBUG /* DUP */ => NULL
3519 stack_depth_8 = stack_depth_7 + -1;
3520 # DEBUG stack_depth => stack_depth_8
3521 x_9 = stack[stack_depth_8];
3523 stack[stack_depth_8] = x_9;
3524 stack_depth_11 = stack_depth_8 + 1;
3525 # DEBUG stack_depth => stack_depth_11
3526 stack[stack_depth_11] = x_9;
3527 stack_depth_13 = stack_depth_11 + 1;
3528 # DEBUG stack_depth => stack_depth_13
3529 # DEBUG instr1 => NULL
3530 # DEBUG /* PUSH_CONST */ => NULL
3531 stack[stack_depth_13] = 2;
3533 /* etc; edited for brevity */
3538 We can perhaps better see the code by turning off
3539 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} to suppress all those @code{DEBUG}
3543 $ less /tmp/libgccjit-1Hywc0/fake.c.016t.ssa
3549 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3551 factorial (signed int arg)
3553 signed int stack[8];
3554 signed int stack_depth;
3566 stack[stack_depth_3] = arg_5(D);
3567 stack_depth_7 = stack_depth_3 + 1;
3568 stack_depth_8 = stack_depth_7 + -1;
3569 x_9 = stack[stack_depth_8];
3570 stack[stack_depth_8] = x_9;
3571 stack_depth_11 = stack_depth_8 + 1;
3572 stack[stack_depth_11] = x_9;
3573 stack_depth_13 = stack_depth_11 + 1;
3574 stack[stack_depth_13] = 2;
3575 stack_depth_15 = stack_depth_13 + 1;
3576 stack_depth_16 = stack_depth_15 + -1;
3577 y_17 = stack[stack_depth_16];
3578 stack_depth_18 = stack_depth_16 + -1;
3579 x_19 = stack[stack_depth_18];
3581 _21 = (signed int) _20;
3582 stack[stack_depth_18] = _21;
3583 stack_depth_23 = stack_depth_18 + 1;
3584 stack_depth_24 = stack_depth_23 + -1;
3585 x_25 = stack[stack_depth_24];
3587 goto <bb 4> (instr9);
3589 goto <bb 3> (instr4);
3593 stack_depth_26 = stack_depth_24 + -1;
3594 x_27 = stack[stack_depth_26];
3595 stack[stack_depth_26] = x_27;
3596 stack_depth_29 = stack_depth_26 + 1;
3597 stack[stack_depth_29] = x_27;
3598 stack_depth_31 = stack_depth_29 + 1;
3599 stack[stack_depth_31] = 1;
3600 stack_depth_33 = stack_depth_31 + 1;
3601 stack_depth_34 = stack_depth_33 + -1;
3602 y_35 = stack[stack_depth_34];
3603 stack_depth_36 = stack_depth_34 + -1;
3604 x_37 = stack[stack_depth_36];
3606 stack[stack_depth_36] = _38;
3607 stack_depth_40 = stack_depth_36 + 1;
3608 stack_depth_41 = stack_depth_40 + -1;
3609 x_42 = stack[stack_depth_41];
3610 _44 = factorial (x_42);
3611 stack[stack_depth_41] = _44;
3612 stack_depth_46 = stack_depth_41 + 1;
3613 stack_depth_47 = stack_depth_46 + -1;
3614 y_48 = stack[stack_depth_47];
3615 stack_depth_49 = stack_depth_47 + -1;
3616 x_50 = stack[stack_depth_49];
3618 stack[stack_depth_49] = _51;
3619 stack_depth_53 = stack_depth_49 + 1;
3621 # stack_depth_1 = PHI <stack_depth_24(2), stack_depth_53(3)>
3624 stack_depth_54 = stack_depth_1 + -1;
3625 x_55 = stack[stack_depth_54];
3627 stack =@{v@} @{CLOBBER@};
3635 Note in the above how all the @pxref{28,,gcc_jit_block} instances we
3636 created have been consolidated into just 3 blocks in GCC's internal
3637 representation: @code{initial}, @code{instr4} and @code{instr9}.
3640 * Optimizing away stack manipulation::
3641 * Elimination of tail recursion::
3645 @node Optimizing away stack manipulation,Elimination of tail recursion,,Behind the curtain How does our code get optimized?
3646 @anchor{intro/tutorial04 optimizing-away-stack-manipulation}@anchor{46}
3647 @subsubsection Optimizing away stack manipulation
3650 Recall our simple implementation of stack operations. Let's examine
3651 how the stack operations are optimized away.
3653 After a pass of constant-propagation, the depth of the stack at each
3654 opcode can be determined at compile-time:
3657 $ less /tmp/libgccjit-1Hywc0/fake.c.021t.ccp1
3663 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3665 factorial (signed int arg)
3667 signed int stack[8];
3668 signed int stack_depth;
3678 stack[0] = arg_5(D);
3686 _21 = (signed int) _20;
3690 goto <bb 4> (instr9);
3692 goto <bb 3> (instr4);
3705 _44 = factorial (x_42);
3716 stack =@{v@} @{CLOBBER@};
3724 Note how, in the above, all those @code{stack_depth} values are now just
3725 constants: we're accessing specific stack locations at each opcode.
3727 The "esra" pass ("Early Scalar Replacement of Aggregates") breaks
3728 out our "stack" array into individual elements:
3731 $ less /tmp/libgccjit-1Hywc0/fake.c.024t.esra
3737 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3739 Created a replacement for stack offset: 0, size: 32: stack$0
3740 Created a replacement for stack offset: 32, size: 32: stack$1
3741 Created a replacement for stack offset: 64, size: 32: stack$2
3743 Symbols to be put in SSA form
3744 @{ D.89 D.90 D.91 @}
3745 Incremental SSA update started at block: 0
3746 Number of blocks in CFG: 5
3747 Number of blocks to update: 4 ( 80%)
3750 factorial (signed int arg)
3755 signed int stack[8];
3756 signed int stack_depth;
3766 stack$0_45 = arg_5(D);
3774 _21 = (signed int) _20;
3778 goto <bb 4> (instr9);
3780 goto <bb 3> (instr4);
3793 _44 = factorial (x_42);
3800 # stack$0_52 = PHI <stack$0_39(2), stack$0_1(3)>
3805 stack =@{v@} @{CLOBBER@};
3813 Hence at this point, all those pushes and pops of the stack are now
3814 simply assignments to specific temporary variables.
3816 After some copy propagation, the stack manipulation has been completely
3820 $ less /tmp/libgccjit-1Hywc0/fake.c.026t.copyprop1
3826 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3828 factorial (signed int arg)
3833 signed int stack[8];
3834 signed int stack_depth;
3844 stack$0_39 = arg_5(D);
3845 _20 = arg_5(D) <= 1;
3846 _21 = (signed int) _20;
3848 goto <bb 4> (instr9);
3850 goto <bb 3> (instr4);
3854 _38 = arg_5(D) + -1;
3855 _44 = factorial (_38);
3856 _51 = arg_5(D) * _44;
3859 # stack$0_52 = PHI <arg_5(D)(2), _51(3)>
3862 stack =@{v@} @{CLOBBER@};
3870 Later on, another pass finally eliminated @code{stack_depth} local and the
3871 unused parts of the @cite{stack`} array altogether:
3874 $ less /tmp/libgccjit-1Hywc0/fake.c.036t.release_ssa
3880 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3882 Released 44 names, 314.29%, removed 44 holes
3883 factorial (signed int arg)
3886 signed int mult_acc_1;
3890 signed int mul_tmp_10;
3891 signed int mult_acc_11;
3892 signed int mult_acc_13;
3894 # arg_9 = PHI <arg_8(D)(0)>
3895 # mult_acc_13 = PHI <1(0)>
3899 # arg_4 = PHI <arg_9(2), _7(3)>
3900 # mult_acc_1 = PHI <mult_acc_13(2), mult_acc_11(3)>
3902 _6 = (signed int) _5;
3904 goto <bb 4> (instr9);
3906 goto <bb 3> (instr4);
3911 mult_acc_11 = mult_acc_1 * arg_4;
3914 # stack$0_12 = PHI <arg_4(5)>
3917 mul_tmp_10 = mult_acc_1 * stack$0_12;
3925 @node Elimination of tail recursion,,Optimizing away stack manipulation,Behind the curtain How does our code get optimized?
3926 @anchor{intro/tutorial04 elimination-of-tail-recursion}@anchor{47}
3927 @subsubsection Elimination of tail recursion
3930 Another significant optimization is the detection that the call to
3931 @code{factorial} is tail recursion, which can be eliminated in favor of
3935 $ less /tmp/libgccjit-1Hywc0/fake.c.030t.tailr1
3941 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3944 Symbols to be put in SSA form
3946 Incremental SSA update started at block: 0
3947 Number of blocks in CFG: 5
3948 Number of blocks to update: 4 ( 80%)
3951 factorial (signed int arg)
3956 signed int stack[8];
3957 signed int stack_depth;
3960 signed int mult_acc_1;
3964 signed int mul_tmp_44;
3965 signed int mult_acc_51;
3967 # arg_5 = PHI <arg_39(D)(0), _38(3)>
3968 # mult_acc_1 = PHI <1(0), mult_acc_51(3)>
3971 _21 = (signed int) _20;
3973 goto <bb 4> (instr9);
3975 goto <bb 3> (instr4);
3980 mult_acc_51 = mult_acc_1 * arg_5;
3981 goto <bb 2> (initial);
3983 # stack$0_52 = PHI <arg_5(2)>
3986 stack =@{v@} @{CLOBBER@};
3987 mul_tmp_44 = mult_acc_1 * stack$0_52;
3995 @c Copyright (C) 2015-2019 Free Software Foundation, Inc.
3996 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
3998 @c This is free software: you can redistribute it and/or modify it
3999 @c under the terms of the GNU General Public License as published by
4000 @c the Free Software Foundation, either version 3 of the License, or
4001 @c (at your option) any later version.
4003 @c This program is distributed in the hope that it will be useful, but
4004 @c WITHOUT ANY WARRANTY; without even the implied warranty of
4005 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
4006 @c General Public License for more details.
4008 @c You should have received a copy of the GNU General Public License
4009 @c along with this program. If not, see
4010 @c <http://www.gnu.org/licenses/>.
4012 @node Tutorial part 5 Implementing an Ahead-of-Time compiler,,Tutorial part 4 Adding JIT-compilation to a toy interpreter,Tutorial
4013 @anchor{intro/tutorial05 doc}@anchor{48}@anchor{intro/tutorial05 tutorial-part-5-implementing-an-ahead-of-time-compiler}@anchor{49}
4014 @section Tutorial part 5: Implementing an Ahead-of-Time compiler
4017 If you have a pre-existing language frontend that's compatible with
4018 libgccjit's license, it's possible to hook it up to libgccjit as a
4019 backend. In the previous example we showed
4020 how to do that for in-memory JIT-compilation, but libgccjit can also
4021 compile code directly to a file, allowing you to implement a more
4022 traditional ahead-of-time compiler ("JIT" is something of a misnomer
4025 The essential difference is to compile the context using
4026 @pxref{4a,,gcc_jit_context_compile_to_file()} rather than
4027 @pxref{15,,gcc_jit_context_compile()}.
4030 * The "brainf" language::
4031 * Converting a brainf script to libgccjit IR::
4032 * Compiling a context to a file::
4033 * Other forms of ahead-of-time-compilation::
4037 @node The "brainf" language,Converting a brainf script to libgccjit IR,,Tutorial part 5 Implementing an Ahead-of-Time compiler
4038 @anchor{intro/tutorial05 the-brainf-language}@anchor{4b}
4039 @subsection The "brainf" language
4042 In this example we use libgccjit to construct an ahead-of-time compiler
4043 for an esoteric programming language that we shall refer to as "brainf".
4045 brainf scripts operate on an array of bytes, with a notional data pointer
4048 brainf is hard for humans to read, but it's trivial to write a parser for
4049 it, as there is no lexing; just a stream of bytes. The operations are:
4052 @multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
4083 @code{data[idx] += 1}
4091 @code{data[idx] -= 1}
4099 @code{output (data[idx])}
4107 @code{data[idx] = input ()}
4115 loop until @code{data[idx] == 0}
4136 Unlike the previous example, we'll implement an ahead-of-time compiler,
4137 which reads @code{.bf} scripts and outputs executables (though it would
4138 be trivial to have it run them JIT-compiled in-process).
4140 Here's what a simple @code{.bf} script looks like:
4146 Emit the uppercase alphabet
4150 ++++++++++++++++++++++++++
4153 >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<
4160 <- decrement cell@@0
4170 This example makes use of whitespace and comments for legibility, but
4171 could have been written as:
4174 ++++++++++++++++++++++++++
4175 >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<
4181 It's not a particularly useful language, except for providing
4182 compiler-writers with a test case that's easy to parse. The point
4183 is that you can use @pxref{4a,,gcc_jit_context_compile_to_file()}
4184 to use libgccjit as a backend for a pre-existing language frontend
4185 (provided that the pre-existing frontend is compatible with libgccjit's
4190 @node Converting a brainf script to libgccjit IR,Compiling a context to a file,The "brainf" language,Tutorial part 5 Implementing an Ahead-of-Time compiler
4191 @anchor{intro/tutorial05 converting-a-brainf-script-to-libgccjit-ir}@anchor{4c}
4192 @subsection Converting a brainf script to libgccjit IR
4195 As before we write simple code to populate a @pxref{8,,gcc_jit_context *}.
4201 typedef struct bf_compiler
4203 const char *filename;
4207 gcc_jit_context *ctxt;
4209 gcc_jit_type *void_type;
4210 gcc_jit_type *int_type;
4211 gcc_jit_type *byte_type;
4212 gcc_jit_type *array_type;
4214 gcc_jit_function *func_getchar;
4215 gcc_jit_function *func_putchar;
4217 gcc_jit_function *func;
4218 gcc_jit_block *curblock;
4220 gcc_jit_rvalue *int_zero;
4221 gcc_jit_rvalue *int_one;
4222 gcc_jit_rvalue *byte_zero;
4223 gcc_jit_rvalue *byte_one;
4224 gcc_jit_lvalue *data_cells;
4225 gcc_jit_lvalue *idx;
4227 int num_open_parens;
4228 gcc_jit_block *paren_test[MAX_OPEN_PARENS];
4229 gcc_jit_block *paren_body[MAX_OPEN_PARENS];
4230 gcc_jit_block *paren_after[MAX_OPEN_PARENS];
4234 /* Bail out, with a message on stderr. */
4237 fatal_error (bf_compiler *bfc, const char *msg)
4241 bfc->filename, bfc->line, bfc->column, msg);
4245 /* Get "data_cells[idx]" as an lvalue. */
4247 static gcc_jit_lvalue *
4248 bf_get_current_data (bf_compiler *bfc, gcc_jit_location *loc)
4250 return gcc_jit_context_new_array_access (
4253 gcc_jit_lvalue_as_rvalue (bfc->data_cells),
4254 gcc_jit_lvalue_as_rvalue (bfc->idx));
4257 /* Get "data_cells[idx] == 0" as a boolean rvalue. */
4259 static gcc_jit_rvalue *
4260 bf_current_data_is_zero (bf_compiler *bfc, gcc_jit_location *loc)
4262 return gcc_jit_context_new_comparison (
4265 GCC_JIT_COMPARISON_EQ,
4266 gcc_jit_lvalue_as_rvalue (bf_get_current_data (bfc, loc)),
4270 /* Compile one bf character. */
4273 bf_compile_char (bf_compiler *bfc,
4276 gcc_jit_location *loc =
4277 gcc_jit_context_new_location (bfc->ctxt,
4282 /* Turn this on to trace execution, by injecting putchar ()
4283 of each source char. */
4286 gcc_jit_rvalue *arg =
4287 gcc_jit_context_new_rvalue_from_int (
4291 gcc_jit_rvalue *call =
4292 gcc_jit_context_new_call (bfc->ctxt,
4296 gcc_jit_block_add_eval (bfc->curblock,
4304 gcc_jit_block_add_comment (bfc->curblock,
4307 gcc_jit_block_add_assignment_op (bfc->curblock,
4310 GCC_JIT_BINARY_OP_PLUS,
4315 gcc_jit_block_add_comment (bfc->curblock,
4318 gcc_jit_block_add_assignment_op (bfc->curblock,
4321 GCC_JIT_BINARY_OP_MINUS,
4326 gcc_jit_block_add_comment (bfc->curblock,
4328 "'+': data[idx] += 1;");
4329 gcc_jit_block_add_assignment_op (bfc->curblock,
4331 bf_get_current_data (bfc, loc),
4332 GCC_JIT_BINARY_OP_PLUS,
4337 gcc_jit_block_add_comment (bfc->curblock,
4339 "'-': data[idx] -= 1;");
4340 gcc_jit_block_add_assignment_op (bfc->curblock,
4342 bf_get_current_data (bfc, loc),
4343 GCC_JIT_BINARY_OP_MINUS,
4349 gcc_jit_rvalue *arg =
4350 gcc_jit_context_new_cast (
4353 gcc_jit_lvalue_as_rvalue (bf_get_current_data (bfc, loc)),
4355 gcc_jit_rvalue *call =
4356 gcc_jit_context_new_call (bfc->ctxt,
4360 gcc_jit_block_add_comment (bfc->curblock,
4362 "'.': putchar ((int)data[idx]);");
4363 gcc_jit_block_add_eval (bfc->curblock,
4371 gcc_jit_rvalue *call =
4372 gcc_jit_context_new_call (bfc->ctxt,
4376 gcc_jit_block_add_comment (
4379 "',': data[idx] = (unsigned char)getchar ();");
4380 gcc_jit_block_add_assignment (bfc->curblock,
4382 bf_get_current_data (bfc, loc),
4383 gcc_jit_context_new_cast (
4393 gcc_jit_block *loop_test =
4394 gcc_jit_function_new_block (bfc->func, NULL);
4395 gcc_jit_block *on_zero =
4396 gcc_jit_function_new_block (bfc->func, NULL);
4397 gcc_jit_block *on_non_zero =
4398 gcc_jit_function_new_block (bfc->func, NULL);
4400 if (bfc->num_open_parens == MAX_OPEN_PARENS)
4401 fatal_error (bfc, "too many open parens");
4403 gcc_jit_block_end_with_jump (
4408 gcc_jit_block_add_comment (
4412 gcc_jit_block_end_with_conditional (
4415 bf_current_data_is_zero (bfc, loc),
4418 bfc->paren_test[bfc->num_open_parens] = loop_test;
4419 bfc->paren_body[bfc->num_open_parens] = on_non_zero;
4420 bfc->paren_after[bfc->num_open_parens] = on_zero;
4421 bfc->num_open_parens += 1;
4422 bfc->curblock = on_non_zero;
4428 gcc_jit_block_add_comment (
4433 if (bfc->num_open_parens == 0)
4434 fatal_error (bfc, "mismatching parens");
4435 bfc->num_open_parens -= 1;
4436 gcc_jit_block_end_with_jump (
4439 bfc->paren_test[bfc->num_open_parens]);
4440 bfc->curblock = bfc->paren_after[bfc->num_open_parens];
4454 /* Compile the given .bf file into a gcc_jit_context, containing a
4455 single "main" function suitable for compiling into an executable. */
4458 bf_compile (const char *filename)
4464 memset (&bfc, 0, sizeof (bfc));
4466 bfc.filename = filename;
4467 f_in = fopen (filename, "r");
4469 fatal_error (&bfc, "unable to open file");
4472 bfc.ctxt = gcc_jit_context_acquire ();
4474 gcc_jit_context_set_int_option (
4476 GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL,
4478 gcc_jit_context_set_bool_option (
4480 GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE,
4482 gcc_jit_context_set_bool_option (
4484 GCC_JIT_BOOL_OPTION_DEBUGINFO,
4486 gcc_jit_context_set_bool_option (
4488 GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING,
4490 gcc_jit_context_set_bool_option (
4492 GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES,
4496 gcc_jit_context_get_type (bfc.ctxt, GCC_JIT_TYPE_VOID);
4498 gcc_jit_context_get_type (bfc.ctxt, GCC_JIT_TYPE_INT);
4500 gcc_jit_context_get_type (bfc.ctxt, GCC_JIT_TYPE_UNSIGNED_CHAR);
4502 gcc_jit_context_new_array_type (bfc.ctxt,
4508 gcc_jit_context_new_function (bfc.ctxt, NULL,
4509 GCC_JIT_FUNCTION_IMPORTED,
4515 gcc_jit_param *param_c =
4516 gcc_jit_context_new_param (bfc.ctxt, NULL, bfc.int_type, "c");
4518 gcc_jit_context_new_function (bfc.ctxt, NULL,
4519 GCC_JIT_FUNCTION_IMPORTED,
4525 bfc.func = make_main (bfc.ctxt);
4527 gcc_jit_function_new_block (bfc.func, "initial");
4528 bfc.int_zero = gcc_jit_context_zero (bfc.ctxt, bfc.int_type);
4529 bfc.int_one = gcc_jit_context_one (bfc.ctxt, bfc.int_type);
4530 bfc.byte_zero = gcc_jit_context_zero (bfc.ctxt, bfc.byte_type);
4531 bfc.byte_one = gcc_jit_context_one (bfc.ctxt, bfc.byte_type);
4534 gcc_jit_context_new_global (bfc.ctxt, NULL,
4535 GCC_JIT_GLOBAL_INTERNAL,
4539 gcc_jit_function_new_local (bfc.func, NULL,
4543 gcc_jit_block_add_comment (bfc.curblock,
4546 gcc_jit_block_add_assignment (bfc.curblock,
4551 bfc.num_open_parens = 0;
4553 while ( EOF != (ch = fgetc (f_in)))
4554 bf_compile_char (&bfc, (unsigned char)ch);
4556 gcc_jit_block_end_with_return (bfc.curblock, NULL, bfc.int_zero);
4569 @node Compiling a context to a file,Other forms of ahead-of-time-compilation,Converting a brainf script to libgccjit IR,Tutorial part 5 Implementing an Ahead-of-Time compiler
4570 @anchor{intro/tutorial05 compiling-a-context-to-a-file}@anchor{4d}
4571 @subsection Compiling a context to a file
4574 Unlike the previous tutorial, this time we'll compile the context
4575 directly to an executable, using @pxref{4a,,gcc_jit_context_compile_to_file()}:
4578 gcc_jit_context_compile_to_file (ctxt,
4579 GCC_JIT_OUTPUT_KIND_EXECUTABLE,
4585 Here's the top-level of the compiler, which is what actually calls into
4586 @pxref{4a,,gcc_jit_context_compile_to_file()}:
4593 main (int argc, char **argv)
4595 const char *input_file;
4596 const char *output_file;
4597 gcc_jit_context *ctxt;
4602 fprintf (stderr, "%s: INPUT_FILE OUTPUT_FILE\n", argv[0]);
4606 input_file = argv[1];
4607 output_file = argv[2];
4608 ctxt = bf_compile (input_file);
4610 gcc_jit_context_compile_to_file (ctxt,
4611 GCC_JIT_OUTPUT_KIND_EXECUTABLE,
4614 err = gcc_jit_context_get_first_error (ctxt);
4618 gcc_jit_context_release (ctxt);
4622 gcc_jit_context_release (ctxt);
4632 Note how once the context is populated you could trivially instead compile
4633 it to memory using @pxref{15,,gcc_jit_context_compile()} and run it in-process
4634 as in the previous tutorial.
4636 To create an executable, we need to export a @code{main} function. Here's
4637 how to create one from the JIT API:
4643 /* Make "main" function:
4645 main (int argc, char **argv)
4650 static gcc_jit_function *
4651 make_main (gcc_jit_context *ctxt)
4653 gcc_jit_type *int_type =
4654 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
4655 gcc_jit_param *param_argc =
4656 gcc_jit_context_new_param (ctxt, NULL, int_type, "argc");
4657 gcc_jit_type *char_ptr_ptr_type =
4658 gcc_jit_type_get_pointer (
4659 gcc_jit_type_get_pointer (
4660 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_CHAR)));
4661 gcc_jit_param *param_argv =
4662 gcc_jit_context_new_param (ctxt, NULL, char_ptr_ptr_type, "argv");
4663 gcc_jit_param *params[2] = @{param_argc, param_argv@};
4664 gcc_jit_function *func_main =
4665 gcc_jit_context_new_function (ctxt, NULL,
4666 GCC_JIT_FUNCTION_EXPORTED,
4682 The above implementation ignores @code{argc} and @code{argv}, but you could
4683 make use of them by exposing @code{param_argc} and @code{param_argv} to the
4688 Upon compiling this C code, we obtain a bf-to-machine-code compiler;
4689 let's call it @code{bfc}:
4700 We can now use @code{bfc} to compile .bf files into machine code executables:
4710 which we can run directly:
4714 ABCDEFGHIJKLMNOPQRSTUVWXYZ
4721 We can also inspect the generated executable using standard tools:
4724 $ objdump -d a.out |less
4729 which shows that libgccjit has managed to optimize the function
4730 somewhat (for example, the runs of 26 and 65 increment operations
4731 have become integer constants 0x1a and 0x41):
4734 0000000000400620 <main>:
4735 400620: 80 3d 39 0a 20 00 00 cmpb $0x0,0x200a39(%rip) # 601060 <data
4736 400627: 74 07 je 400630 <main
4737 400629: eb fe jmp 400629 <main+0x9>
4738 40062b: 0f 1f 44 00 00 nopl 0x0(%rax,%rax,1)
4739 400630: 48 83 ec 08 sub $0x8,%rsp
4740 400634: 0f b6 05 26 0a 20 00 movzbl 0x200a26(%rip),%eax # 601061 <data_cells+0x1>
4741 40063b: c6 05 1e 0a 20 00 1a movb $0x1a,0x200a1e(%rip) # 601060 <data_cells>
4742 400642: 8d 78 41 lea 0x41(%rax),%edi
4743 400645: 40 88 3d 15 0a 20 00 mov %dil,0x200a15(%rip) # 601061 <data_cells+0x1>
4744 40064c: 0f 1f 40 00 nopl 0x0(%rax)
4745 400650: 40 0f b6 ff movzbl %dil,%edi
4746 400654: e8 87 fe ff ff callq 4004e0 <putchar@@plt>
4747 400659: 0f b6 05 01 0a 20 00 movzbl 0x200a01(%rip),%eax # 601061 <data_cells+0x1>
4748 400660: 80 2d f9 09 20 00 01 subb $0x1,0x2009f9(%rip) # 601060 <data_cells>
4749 400667: 8d 78 01 lea 0x1(%rax),%edi
4750 40066a: 40 88 3d f0 09 20 00 mov %dil,0x2009f0(%rip) # 601061 <data_cells+0x1>
4751 400671: 75 dd jne 400650 <main+0x30>
4752 400673: 31 c0 xor %eax,%eax
4753 400675: 48 83 c4 08 add $0x8,%rsp
4755 40067a: 66 0f 1f 44 00 00 nopw 0x0(%rax,%rax,1)
4760 We also set up debugging information (via
4761 @pxref{41,,gcc_jit_context_new_location()} and
4762 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO}), so it's possible to use @code{gdb}
4763 to singlestep through the generated binary and inspect the internal
4764 state @code{idx} and @code{data_cells}:
4768 Breakpoint 1 at 0x400790
4770 Starting program: a.out
4772 Breakpoint 1, 0x0000000000400790 in main (argc=1, argv=0x7fffffffe448)
4774 0x0000000000400797 in main (argc=1, argv=0x7fffffffe448)
4776 0x00000000004007a0 in main (argc=1, argv=0x7fffffffe448)
4778 9 >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<
4782 6 ++++++++++++++++++++++++++
4785 9 >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<
4787 11 while cell#0 != 0
4791 6 ++++++++++++++++++++++++++
4793 9 >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<
4797 $2 = "\032", '\000' <repeats 29998 times>
4798 (gdb) p data_cells[0]
4800 (gdb) p data_cells[1]
4805 6 ++++++++++++++++++++++++++
4808 9 >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<
4810 11 while cell#0 != 0
4817 @node Other forms of ahead-of-time-compilation,,Compiling a context to a file,Tutorial part 5 Implementing an Ahead-of-Time compiler
4818 @anchor{intro/tutorial05 other-forms-of-ahead-of-time-compilation}@anchor{4e}
4819 @subsection Other forms of ahead-of-time-compilation
4822 The above demonstrates compiling a @pxref{8,,gcc_jit_context *} directly
4823 to an executable. It's also possible to compile it to an object file,
4824 and to a dynamic library. See the documentation of
4825 @pxref{4a,,gcc_jit_context_compile_to_file()} for more information.
4827 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
4828 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
4830 @c This is free software: you can redistribute it and/or modify it
4831 @c under the terms of the GNU General Public License as published by
4832 @c the Free Software Foundation, either version 3 of the License, or
4833 @c (at your option) any later version.
4835 @c This program is distributed in the hope that it will be useful, but
4836 @c WITHOUT ANY WARRANTY; without even the implied warranty of
4837 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
4838 @c General Public License for more details.
4840 @c You should have received a copy of the GNU General Public License
4841 @c along with this program. If not, see
4842 @c <http://www.gnu.org/licenses/>.
4844 @node Topic Reference,C++ bindings for libgccjit,Tutorial,Top
4845 @anchor{topics/index doc}@anchor{4f}@anchor{topics/index topic-reference}@anchor{50}
4846 @chapter Topic Reference
4849 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
4850 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
4852 @c This is free software: you can redistribute it and/or modify it
4853 @c under the terms of the GNU General Public License as published by
4854 @c the Free Software Foundation, either version 3 of the License, or
4855 @c (at your option) any later version.
4857 @c This program is distributed in the hope that it will be useful, but
4858 @c WITHOUT ANY WARRANTY; without even the implied warranty of
4859 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
4860 @c General Public License for more details.
4862 @c You should have received a copy of the GNU General Public License
4863 @c along with this program. If not, see
4864 @c <http://www.gnu.org/licenses/>.
4867 * Compilation contexts::
4871 * Creating and using functions::
4872 * Function pointers: Function pointers<2>.
4873 * Source Locations::
4874 * Compiling a context::
4875 * ABI and API compatibility::
4878 Compilation contexts
4880 * Lifetime-management::
4882 * Error-handling: Error-handling<2>.
4884 * Options: Options<2>.
4891 * Additional command-line options::
4896 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile.
4898 * Structures and unions::
4899 * Function pointer types::
4905 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions.
4909 * Simple expressions::
4910 * Vector expressions::
4911 * Unary Operations::
4912 * Binary Operations::
4915 * Function pointers::
4920 * Global variables::
4922 Creating and using functions
4935 * In-memory compilation::
4936 * Ahead-of-time compilation::
4938 ABI and API compatibility
4954 * LIBGCCJIT_ABI_10::
4963 @node Compilation contexts,Objects,,Topic Reference
4964 @anchor{topics/contexts compilation-contexts}@anchor{51}@anchor{topics/contexts doc}@anchor{52}
4965 @section Compilation contexts
4968 @geindex gcc_jit_context (C type)
4969 @anchor{topics/contexts gcc_jit_context}@anchor{8}
4970 @deffn {C Type} gcc_jit_context
4973 The top-level of the API is the @pxref{8,,gcc_jit_context} type.
4975 A @pxref{8,,gcc_jit_context} instance encapsulates the state of a
4978 You can set up options on it, and add types, functions and code.
4979 Invoking @pxref{15,,gcc_jit_context_compile()} on it gives you a
4980 @pxref{16,,gcc_jit_result}.
4983 * Lifetime-management::
4985 * Error-handling: Error-handling<2>.
4987 * Options: Options<2>.
4991 @node Lifetime-management,Thread-safety,,Compilation contexts
4992 @anchor{topics/contexts lifetime-management}@anchor{53}
4993 @subsection Lifetime-management
4996 Contexts are the unit of lifetime-management within the API: objects
4997 have their lifetime bounded by the context they are created within, and
4998 cleanup of such objects is done for you when the context is released.
5000 @geindex gcc_jit_context_acquire (C function)
5001 @anchor{topics/contexts gcc_jit_context_acquire}@anchor{9}
5002 @deffn {C Function} gcc_jit_context *gcc_jit_context_acquire (void)
5004 This function acquires a new @pxref{8,,gcc_jit_context *} instance,
5005 which is independent of any others that may be present within this
5009 @geindex gcc_jit_context_release (C function)
5010 @anchor{topics/contexts gcc_jit_context_release}@anchor{c}
5011 @deffn {C Function} void gcc_jit_context_release (gcc_jit_context@w{ }*ctxt)
5013 This function releases all resources associated with the given context.
5014 Both the context itself and all of its @pxref{e,,gcc_jit_object *}
5015 instances are cleaned up. It should be called exactly once on a given
5018 It is invalid to use the context or any of its "contextual" objects
5022 gcc_jit_context_release (ctxt);
5028 @geindex gcc_jit_context_new_child_context (C function)
5029 @anchor{topics/contexts gcc_jit_context_new_child_context}@anchor{54}
5030 @deffn {C Function} gcc_jit_context * gcc_jit_context_new_child_context (gcc_jit_context@w{ }*parent_ctxt)
5032 Given an existing JIT context, create a child context.
5034 The child inherits a copy of all option-settings from the parent.
5036 The child can reference objects created within the parent, but not
5039 The lifetime of the child context must be bounded by that of the
5040 parent: you should release a child context before releasing the parent
5043 If you use a function from a parent context within a child context,
5044 you have to compile the parent context before you can compile the
5045 child context, and the gcc_jit_result of the parent context must
5046 outlive the gcc_jit_result of the child context.
5048 This allows caching of shared initializations. For example, you could
5049 create types and declarations of global functions in a parent context
5050 once within a process, and then create child contexts whenever a
5051 function or loop becomes hot. Each such child context can be used for
5052 JIT-compiling just one function or loop, but can reference types
5053 and helper functions created within the parent context.
5055 Contexts can be arbitrarily nested, provided the above rules are
5056 followed, but it's probably not worth going above 2 or 3 levels, and
5057 there will likely be a performance hit for such nesting.
5060 @node Thread-safety,Error-handling<2>,Lifetime-management,Compilation contexts
5061 @anchor{topics/contexts thread-safety}@anchor{55}
5062 @subsection Thread-safety
5065 Instances of @pxref{8,,gcc_jit_context *} created via
5066 @pxref{9,,gcc_jit_context_acquire()} are independent from each other:
5067 only one thread may use a given context at once, but multiple threads
5068 could each have their own contexts without needing locks.
5070 Contexts created via @pxref{54,,gcc_jit_context_new_child_context()} are
5071 related to their parent context. They can be partitioned by their
5072 ultimate ancestor into independent "family trees". Only one thread
5073 within a process may use a given "family tree" of such contexts at once,
5074 and if you're using multiple threads you should provide your own locking
5075 around entire such context partitions.
5077 @node Error-handling<2>,Debugging,Thread-safety,Compilation contexts
5078 @anchor{topics/contexts error-handling}@anchor{19}@anchor{topics/contexts id1}@anchor{56}
5079 @subsection Error-handling
5082 Various kinds of errors are possible when using the API, such as
5083 mismatched types in an assignment. You can only compile and get code from
5084 a context if no errors occur.
5086 Errors are printed on stderr and can be queried using
5087 @pxref{57,,gcc_jit_context_get_first_error()}.
5089 They typically contain the name of the API entrypoint where the error
5090 occurred, and pertinent information on the problem:
5093 ./buggy-program: error: gcc_jit_block_add_assignment: mismatching types: assignment to i (type: int) from "hello world" (type: const char *)
5098 In general, if an error occurs when using an API entrypoint, the
5099 entrypoint returns NULL. You don't have to check everywhere for NULL
5100 results, since the API handles a NULL being passed in for any
5101 argument by issuing another error. This typically leads to a cascade of
5102 followup error messages, but is safe (albeit verbose). The first error
5103 message is usually the one to pay attention to, since it is likely to
5104 be responsible for all of the rest:
5106 @geindex gcc_jit_context_get_first_error (C function)
5107 @anchor{topics/contexts gcc_jit_context_get_first_error}@anchor{57}
5108 @deffn {C Function} const char * gcc_jit_context_get_first_error (gcc_jit_context@w{ }*ctxt)
5110 Returns the first error message that occurred on the context.
5112 The returned string is valid for the rest of the lifetime of the
5115 If no errors occurred, this will be NULL.
5118 If you are wrapping the C API for a higher-level language that supports
5119 exception-handling, you may instead be interested in the last error that
5120 occurred on the context, so that you can embed this in an exception:
5122 @geindex gcc_jit_context_get_last_error (C function)
5123 @anchor{topics/contexts gcc_jit_context_get_last_error}@anchor{58}
5124 @deffn {C Function} const char * gcc_jit_context_get_last_error (gcc_jit_context@w{ }*ctxt)
5126 Returns the last error message that occurred on the context.
5128 If no errors occurred, this will be NULL.
5130 If non-NULL, the returned string is only guaranteed to be valid until
5131 the next call to libgccjit relating to this context.
5134 @node Debugging,Options<2>,Error-handling<2>,Compilation contexts
5135 @anchor{topics/contexts debugging}@anchor{59}
5136 @subsection Debugging
5139 @geindex gcc_jit_context_dump_to_file (C function)
5140 @anchor{topics/contexts gcc_jit_context_dump_to_file}@anchor{5a}
5141 @deffn {C Function} void gcc_jit_context_dump_to_file (gcc_jit_context@w{ }*ctxt, const char@w{ }*path, int@w{ }update_locations)
5143 To help with debugging: dump a C-like representation to the given path,
5144 describing what's been set up on the context.
5146 If "update_locations" is true, then also set up @pxref{3b,,gcc_jit_location}
5147 information throughout the context, pointing at the dump file as if it
5148 were a source file. This may be of use in conjunction with
5149 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} to allow stepping through the
5153 @geindex gcc_jit_context_set_logfile (C function)
5154 @anchor{topics/contexts gcc_jit_context_set_logfile}@anchor{5b}
5155 @deffn {C Function} void gcc_jit_context_set_logfile (gcc_jit_context@w{ }*ctxt, FILE@w{ }*logfile, int@w{ }flags, int@w{ }verbosity)
5157 To help with debugging; enable ongoing logging of the context's
5158 activity to the given file.
5160 For example, the following will enable logging to stderr.
5163 gcc_jit_context_set_logfile (ctxt, stderr, 0, 0);
5168 Examples of information logged include:
5177 the various steps involved within compilation
5180 activity on any @pxref{16,,gcc_jit_result} instances created by
5184 activity within any child contexts
5187 An example of a log can be seen @pxref{5c,,here},
5188 though the precise format and kinds of information logged is subject
5191 The caller remains responsible for closing @cite{logfile}, and it must not
5192 be closed until all users are released. In particular, note that
5193 child contexts and @pxref{16,,gcc_jit_result} instances created by
5194 the context will use the logfile.
5196 There may a performance cost for logging.
5198 You can turn off logging on @cite{ctxt} by passing @cite{NULL} for @cite{logfile}.
5199 Doing so only affects the context; it does not affect child contexts
5200 or @pxref{16,,gcc_jit_result} instances already created by
5203 The parameters "flags" and "verbosity" are reserved for future
5204 expansion, and must be zero for now.
5207 To contrast the above: @pxref{5a,,gcc_jit_context_dump_to_file()} dumps the
5208 current state of a context to the given path, whereas
5209 @pxref{5b,,gcc_jit_context_set_logfile()} enables on-going logging of
5210 future activies on a context to the given @cite{FILE *}.
5212 @geindex gcc_jit_context_dump_reproducer_to_file (C function)
5213 @anchor{topics/contexts gcc_jit_context_dump_reproducer_to_file}@anchor{5d}
5214 @deffn {C Function} void gcc_jit_context_dump_reproducer_to_file (gcc_jit_context@w{ }*ctxt, const char@w{ }*path)
5216 Write C source code into @cite{path} that can be compiled into a
5217 self-contained executable (i.e. with libgccjit as the only dependency).
5218 The generated code will attempt to replay the API calls that have been
5219 made into the given context.
5221 This may be useful when debugging the library or client code, for
5222 reducing a complicated recipe for reproducing a bug into a simpler
5223 form. For example, consider client code that parses some source file
5224 into some internal representation, and then walks this IR, calling into
5225 libgccjit. If this encounters a bug, a call to
5226 @cite{gcc_jit_context_dump_reproducer_to_file} will write out C code for
5227 a much simpler executable that performs the equivalent calls into
5228 libgccjit, without needing the client code and its data.
5230 Typically you need to supply @code{-Wno-unused-variable} when
5231 compiling the generated file (since the result of each API call is
5232 assigned to a unique variable within the generated C source, and not
5233 all are necessarily then used).
5236 @geindex gcc_jit_context_enable_dump (C function)
5237 @anchor{topics/contexts gcc_jit_context_enable_dump}@anchor{5e}
5238 @deffn {C Function} void gcc_jit_context_enable_dump (gcc_jit_context@w{ }*ctxt, const char@w{ }*dumpname, char@w{ }**out_ptr)
5240 Enable the dumping of a specific set of internal state from the
5241 compilation, capturing the result in-memory as a buffer.
5243 Parameter "dumpname" corresponds to the equivalent gcc command-line
5244 option, without the "-fdump-" prefix.
5245 For example, to get the equivalent of @code{-fdump-tree-vrp1},
5246 supply @code{"tree-vrp1"}:
5249 static char *dump_vrp1;
5252 create_code (gcc_jit_context *ctxt)
5254 gcc_jit_context_enable_dump (ctxt, "tree-vrp1", &dump_vrp1);
5255 /* (other API calls omitted for brevity) */
5261 The context directly stores the dumpname as a @code{(const char *)}, so
5262 the passed string must outlive the context.
5264 @pxref{15,,gcc_jit_context_compile()} will capture the dump as a
5265 dynamically-allocated buffer, writing it to @code{*out_ptr}.
5267 The caller becomes responsible for calling:
5275 each time that @pxref{15,,gcc_jit_context_compile()} is called.
5276 @code{*out_ptr} will be written to, either with the address of a buffer,
5277 or with @code{NULL} if an error occurred.
5281 This API entrypoint is likely to be less stable than the others.
5282 In particular, both the precise dumpnames, and the format and content
5283 of the dumps are subject to change.
5285 It exists primarily for writing the library's own test suite.
5290 @node Options<2>,,Debugging,Compilation contexts
5291 @anchor{topics/contexts options}@anchor{5f}
5295 Options present in the initial release of libgccjit were handled using
5296 enums, whereas those added subsequently have their own per-option API
5299 Adding entrypoints for each new option means that client code that use
5300 the new options can be identified directly from binary metadata, which
5301 would not be possible if we instead extended the various
5302 @code{enum gcc_jit_*_option}.
5308 * Additional command-line options::
5312 @node String Options,Boolean options,,Options<2>
5313 @anchor{topics/contexts string-options}@anchor{60}
5314 @subsubsection String Options
5317 @geindex gcc_jit_context_set_str_option (C function)
5318 @anchor{topics/contexts gcc_jit_context_set_str_option}@anchor{61}
5319 @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)
5321 Set a string option of the context.
5323 @geindex gcc_jit_str_option (C type)
5324 @anchor{topics/contexts gcc_jit_str_option}@anchor{62}
5325 @deffn {C Type} enum gcc_jit_str_option
5328 The parameter @code{value} can be NULL. If non-NULL, the call takes a
5329 copy of the underlying string, so it is valid to pass in a pointer to
5332 There is just one string option specified this way:
5334 @geindex GCC_JIT_STR_OPTION_PROGNAME (C macro)
5335 @anchor{topics/contexts GCC_JIT_STR_OPTION_PROGNAME}@anchor{63}
5336 @deffn {C Macro} GCC_JIT_STR_OPTION_PROGNAME
5338 The name of the program, for use as a prefix when printing error
5339 messages to stderr. If @cite{NULL}, or default, "libgccjit.so" is used.
5343 @node Boolean options,Integer options,String Options,Options<2>
5344 @anchor{topics/contexts boolean-options}@anchor{64}
5345 @subsubsection Boolean options
5348 @geindex gcc_jit_context_set_bool_option (C function)
5349 @anchor{topics/contexts gcc_jit_context_set_bool_option}@anchor{1b}
5350 @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)
5352 Set a boolean option of the context.
5353 Zero is "false" (the default), non-zero is "true".
5355 @geindex gcc_jit_bool_option (C type)
5356 @anchor{topics/contexts gcc_jit_bool_option}@anchor{65}
5357 @deffn {C Type} enum gcc_jit_bool_option
5360 @geindex GCC_JIT_BOOL_OPTION_DEBUGINFO (C macro)
5361 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DEBUGINFO}@anchor{42}
5362 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DEBUGINFO
5364 If true, @pxref{15,,gcc_jit_context_compile()} will attempt to do the right
5365 thing so that if you attach a debugger to the process, it will
5366 be able to inspect variables and step through your code.
5368 Note that you can't step through code unless you set up source
5369 location information for the code (by creating and passing in
5370 @pxref{3b,,gcc_jit_location} instances).
5373 @geindex GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE (C macro)
5374 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE}@anchor{66}
5375 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE
5377 If true, @pxref{15,,gcc_jit_context_compile()} will dump its initial
5378 "tree" representation of your code to stderr (before any
5381 Here's some sample output (from the @cite{square} example):
5384 <statement_list 0x7f4875a62cc0
5385 type <void_type 0x7f4875a64bd0 VOID
5386 align 8 symtab 0 alias set -1 canonical type 0x7f4875a64bd0
5387 pointer_to_this <pointer_type 0x7f4875a64c78>>
5388 side-effects head 0x7f4875a761e0 tail 0x7f4875a761f8 stmts 0x7f4875a62d20 0x7f4875a62d00
5390 stmt <label_expr 0x7f4875a62d20 type <void_type 0x7f4875a64bd0>
5392 arg 0 <label_decl 0x7f4875a79080 entry type <void_type 0x7f4875a64bd0>
5393 VOID file (null) line 0 col 0
5394 align 1 context <function_decl 0x7f4875a77500 square>>>
5395 stmt <return_expr 0x7f4875a62d00
5396 type <integer_type 0x7f4875a645e8 public SI
5397 size <integer_cst 0x7f4875a623a0 constant 32>
5398 unit size <integer_cst 0x7f4875a623c0 constant 4>
5399 align 32 symtab 0 alias set -1 canonical type 0x7f4875a645e8 precision 32 min <integer_cst 0x7f4875a62340 -2147483648> max <integer_cst 0x7f4875a62360 2147483647>
5400 pointer_to_this <pointer_type 0x7f4875a6b348>>
5402 arg 0 <modify_expr 0x7f4875a72a78 type <integer_type 0x7f4875a645e8>
5403 side-effects arg 0 <result_decl 0x7f4875a7a000 D.54>
5404 arg 1 <mult_expr 0x7f4875a72a50 type <integer_type 0x7f4875a645e8>
5405 arg 0 <parm_decl 0x7f4875a79000 i> arg 1 <parm_decl 0x7f4875a79000 i>>>>>
5411 @geindex GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE (C macro)
5412 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE}@anchor{1c}
5413 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE
5415 If true, @pxref{15,,gcc_jit_context_compile()} will dump the "gimple"
5416 representation of your code to stderr, before any optimizations
5417 are performed. The dump resembles C code:
5420 square (signed int i)
5433 @geindex GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE (C macro)
5434 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE}@anchor{1d}
5435 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE
5437 If true, @pxref{15,,gcc_jit_context_compile()} will dump the final
5438 generated code to stderr, in the form of assembly language:
5444 .type square, @@function
5449 .cfi_def_cfa_offset 16
5452 .cfi_def_cfa_register 6
5456 imull -4(%rbp), %eax
5462 .size square, .-square
5463 .ident "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.1-%@{gcc_release@})"
5464 .section .note.GNU-stack,"",@@progbits
5470 @geindex GCC_JIT_BOOL_OPTION_DUMP_SUMMARY (C macro)
5471 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_SUMMARY}@anchor{67}
5472 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_SUMMARY
5474 If true, @pxref{15,,gcc_jit_context_compile()} will print information to stderr
5475 on the actions it is performing.
5478 @geindex GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING (C macro)
5479 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING}@anchor{68}
5480 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING
5482 If true, @pxref{15,,gcc_jit_context_compile()} will dump copious
5483 amount of information on what it's doing to various
5484 files within a temporary directory. Use
5485 @pxref{69,,GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES} (see below) to
5486 see the results. The files are intended to be human-readable,
5487 but the exact files and their formats are subject to change.
5490 @geindex GCC_JIT_BOOL_OPTION_SELFCHECK_GC (C macro)
5491 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_SELFCHECK_GC}@anchor{6a}
5492 @deffn {C Macro} GCC_JIT_BOOL_OPTION_SELFCHECK_GC
5494 If true, libgccjit will aggressively run its garbage collector, to
5495 shake out bugs (greatly slowing down the compile). This is likely
5496 to only be of interest to developers @emph{of} the library. It is
5497 used when running the selftest suite.
5500 @geindex GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES (C macro)
5501 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES}@anchor{69}
5502 @deffn {C Macro} GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES
5504 If true, the @pxref{8,,gcc_jit_context} will not clean up intermediate files
5505 written to the filesystem, and will display their location on stderr.
5509 @geindex gcc_jit_context_set_bool_allow_unreachable_blocks (C function)
5510 @anchor{topics/contexts gcc_jit_context_set_bool_allow_unreachable_blocks}@anchor{6b}
5511 @deffn {C Function} void gcc_jit_context_set_bool_allow_unreachable_blocks (gcc_jit_context@w{ }*ctxt, int@w{ }bool_value)
5513 By default, libgccjit will issue an error about unreachable blocks
5516 This entrypoint can be used to disable that error.
5518 This entrypoint was added in @pxref{6c,,LIBGCCJIT_ABI_2}; you can test for
5522 #ifdef LIBGCCJIT_HAVE_gcc_jit_context_set_bool_allow_unreachable_blocks
5528 @geindex gcc_jit_context_set_bool_use_external_driver (C function)
5529 @anchor{topics/contexts gcc_jit_context_set_bool_use_external_driver}@anchor{6d}
5530 @deffn {C Function} void gcc_jit_context_set_bool_use_external_driver (gcc_jit_context@w{ }*ctxt, int@w{ }bool_value)
5532 libgccjit internally generates assembler, and uses "driver" code
5533 for converting it to other formats (e.g. shared libraries).
5535 By default, libgccjit will use an embedded copy of the driver
5538 This option can be used to instead invoke an external driver executable
5541 This entrypoint was added in @pxref{6e,,LIBGCCJIT_ABI_5}; you can test for
5545 #ifdef LIBGCCJIT_HAVE_gcc_jit_context_set_bool_use_external_driver
5551 @node Integer options,Additional command-line options,Boolean options,Options<2>
5552 @anchor{topics/contexts integer-options}@anchor{6f}
5553 @subsubsection Integer options
5556 @geindex gcc_jit_context_set_int_option (C function)
5557 @anchor{topics/contexts gcc_jit_context_set_int_option}@anchor{1e}
5558 @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)
5560 Set an integer option of the context.
5562 @geindex gcc_jit_int_option (C type)
5563 @anchor{topics/contexts gcc_jit_int_option}@anchor{70}
5564 @deffn {C Type} enum gcc_jit_int_option
5567 There is just one integer option specified this way:
5569 @geindex GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL (C macro)
5570 @anchor{topics/contexts GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}@anchor{1f}
5571 @deffn {C Macro} GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL
5573 How much to optimize the code.
5575 Valid values are 0-3, corresponding to GCC's command-line options
5578 The default value is 0 (unoptimized).
5582 @node Additional command-line options,,Integer options,Options<2>
5583 @anchor{topics/contexts additional-command-line-options}@anchor{71}
5584 @subsubsection Additional command-line options
5587 @geindex gcc_jit_context_add_command_line_option (C function)
5588 @anchor{topics/contexts gcc_jit_context_add_command_line_option}@anchor{72}
5589 @deffn {C Function} void gcc_jit_context_add_command_line_option (gcc_jit_context@w{ }*ctxt, const char@w{ }*optname)
5591 Add an arbitrary gcc command-line option to the context, for use
5592 by @pxref{15,,gcc_jit_context_compile()} and
5593 @pxref{4a,,gcc_jit_context_compile_to_file()}.
5595 The parameter @code{optname} must be non-NULL. The underlying buffer is
5596 copied, so that it does not need to outlive the call.
5598 Extra options added by @cite{gcc_jit_context_add_command_line_option} are
5599 applied @emph{after} the regular options above, potentially overriding them.
5600 Options from parent contexts are inherited by child contexts; options
5601 from the parent are applied @emph{before} those from the child.
5606 gcc_jit_context_add_command_line_option (ctxt, "-ffast-math");
5607 gcc_jit_context_add_command_line_option (ctxt, "-fverbose-asm");
5612 Note that only some options are likely to be meaningful; there is no
5613 "frontend" within libgccjit, so typically only those affecting
5614 optimization and code-generation are likely to be useful.
5616 This entrypoint was added in @pxref{73,,LIBGCCJIT_ABI_1}; you can test for
5620 #ifdef LIBGCCJIT_HAVE_gcc_jit_context_add_command_line_option
5626 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
5627 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
5629 @c This is free software: you can redistribute it and/or modify it
5630 @c under the terms of the GNU General Public License as published by
5631 @c the Free Software Foundation, either version 3 of the License, or
5632 @c (at your option) any later version.
5634 @c This program is distributed in the hope that it will be useful, but
5635 @c WITHOUT ANY WARRANTY; without even the implied warranty of
5636 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
5637 @c General Public License for more details.
5639 @c You should have received a copy of the GNU General Public License
5640 @c along with this program. If not, see
5641 @c <http://www.gnu.org/licenses/>.
5643 @node Objects,Types,Compilation contexts,Topic Reference
5644 @anchor{topics/objects objects}@anchor{74}@anchor{topics/objects doc}@anchor{75}
5648 @geindex gcc_jit_object (C type)
5649 @anchor{topics/objects gcc_jit_object}@anchor{e}
5650 @deffn {C Type} gcc_jit_object
5653 Almost every entity in the API (with the exception of
5654 @pxref{8,,gcc_jit_context *} and @pxref{16,,gcc_jit_result *}) is a
5655 "contextual" object, a @pxref{e,,gcc_jit_object *}
5665 is associated with a @pxref{8,,gcc_jit_context *}.
5668 is automatically cleaned up for you when its context is released so
5669 you don't need to manually track and cleanup all objects, just the
5674 Although the API is C-based, there is a form of class hierarchy, which
5693 There are casting methods for upcasting from subclasses to parent classes.
5694 For example, @pxref{d,,gcc_jit_type_as_object()}:
5697 gcc_jit_object *obj = gcc_jit_type_as_object (int_type);
5702 The object "base class" has the following operations:
5704 @geindex gcc_jit_object_get_context (C function)
5705 @anchor{topics/objects gcc_jit_object_get_context}@anchor{76}
5706 @deffn {C Function} gcc_jit_context *gcc_jit_object_get_context (gcc_jit_object@w{ }*obj)
5708 Which context is "obj" within?
5711 @geindex gcc_jit_object_get_debug_string (C function)
5712 @anchor{topics/objects gcc_jit_object_get_debug_string}@anchor{f}
5713 @deffn {C Function} const char *gcc_jit_object_get_debug_string (gcc_jit_object@w{ }*obj)
5715 Generate a human-readable description for the given object.
5720 printf ("obj: %s\n", gcc_jit_object_get_debug_string (obj));
5725 might give this text on stdout:
5735 If you call this on an object, the @cite{const char *} buffer is allocated
5736 and generated on the first call for that object, and the buffer will
5737 have the same lifetime as the object i.e. it will exist until the
5738 object's context is released.
5743 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
5744 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
5746 @c This is free software: you can redistribute it and/or modify it
5747 @c under the terms of the GNU General Public License as published by
5748 @c the Free Software Foundation, either version 3 of the License, or
5749 @c (at your option) any later version.
5751 @c This program is distributed in the hope that it will be useful, but
5752 @c WITHOUT ANY WARRANTY; without even the implied warranty of
5753 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
5754 @c General Public License for more details.
5756 @c You should have received a copy of the GNU General Public License
5757 @c along with this program. If not, see
5758 @c <http://www.gnu.org/licenses/>.
5760 @node Types,Expressions,Objects,Topic Reference
5761 @anchor{topics/types doc}@anchor{77}@anchor{topics/types types}@anchor{78}
5765 @geindex gcc_jit_type (C type)
5766 @anchor{topics/types gcc_jit_type}@anchor{a}
5767 @deffn {C Type} gcc_jit_type
5769 gcc_jit_type represents a type within the library.
5772 @geindex gcc_jit_type_as_object (C function)
5773 @anchor{topics/types gcc_jit_type_as_object}@anchor{d}
5774 @deffn {C Function} gcc_jit_object *gcc_jit_type_as_object (gcc_jit_type@w{ }*type)
5776 Upcast a type to an object.
5779 Types can be created in several ways:
5785 fundamental types can be accessed using
5786 @pxref{b,,gcc_jit_context_get_type()}:
5789 gcc_jit_type *int_type = gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
5794 See @pxref{b,,gcc_jit_context_get_type()} for the available types.
5797 derived types can be accessed by using functions such as
5798 @pxref{79,,gcc_jit_type_get_pointer()} and @pxref{7a,,gcc_jit_type_get_const()}:
5801 gcc_jit_type *const_int_star = gcc_jit_type_get_pointer (gcc_jit_type_get_const (int_type));
5802 gcc_jit_type *int_const_star = gcc_jit_type_get_const (gcc_jit_type_get_pointer (int_type));
5808 by creating structures (see below).
5813 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile.
5815 * Structures and unions::
5816 * Function pointer types::
5820 @node Standard types,Pointers const and volatile,,Types
5821 @anchor{topics/types standard-types}@anchor{7b}
5822 @subsection Standard types
5825 @geindex gcc_jit_context_get_type (C function)
5826 @anchor{topics/types gcc_jit_context_get_type}@anchor{b}
5827 @deffn {C Function} gcc_jit_type *gcc_jit_context_get_type (gcc_jit_context@w{ }*ctxt, enum gcc_jit_types@w{ }type_)
5829 Access a specific type. The available types are:
5832 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
5835 @cite{enum gcc_jit_types} value
5843 @code{GCC_JIT_TYPE_VOID}
5847 C's @code{void} type.
5851 @code{GCC_JIT_TYPE_VOID_PTR}
5859 @code{GCC_JIT_TYPE_BOOL}
5863 C++'s @code{bool} type; also C99's
5864 @code{_Bool} type, aka @code{bool} if
5869 @code{GCC_JIT_TYPE_CHAR}
5873 C's @code{char} (of some signedness)
5877 @code{GCC_JIT_TYPE_SIGNED_CHAR}
5881 C's @code{signed char}
5885 @code{GCC_JIT_TYPE_UNSIGNED_CHAR}
5889 C's @code{unsigned char}
5893 @code{GCC_JIT_TYPE_SHORT}
5897 C's @code{short} (signed)
5901 @code{GCC_JIT_TYPE_UNSIGNED_SHORT}
5905 C's @code{unsigned short}
5909 @code{GCC_JIT_TYPE_INT}
5913 C's @code{int} (signed)
5917 @code{GCC_JIT_TYPE_UNSIGNED_INT}
5921 C's @code{unsigned int}
5925 @code{GCC_JIT_TYPE_LONG}
5929 C's @code{long} (signed)
5933 @code{GCC_JIT_TYPE_UNSIGNED_LONG}
5937 C's @code{unsigned long}
5941 @code{GCC_JIT_TYPE_LONG_LONG}
5945 C99's @code{long long} (signed)
5949 @code{GCC_JIT_TYPE_UNSIGNED_LONG_LONG}
5953 C99's @code{unsigned long long}
5957 @code{GCC_JIT_TYPE_FLOAT}
5963 @code{GCC_JIT_TYPE_DOUBLE}
5969 @code{GCC_JIT_TYPE_LONG_DOUBLE}
5975 @code{GCC_JIT_TYPE_CONST_CHAR_PTR}
5979 C type: @code{(const char *)}
5983 @code{GCC_JIT_TYPE_SIZE_T}
5987 C's @code{size_t} type
5991 @code{GCC_JIT_TYPE_FILE_PTR}
5995 C type: @code{(FILE *)}
5999 @code{GCC_JIT_TYPE_COMPLEX_FLOAT}
6003 C99's @code{_Complex float}
6007 @code{GCC_JIT_TYPE_COMPLEX_DOUBLE}
6011 C99's @code{_Complex double}
6015 @code{GCC_JIT_TYPE_COMPLEX_LONG_DOUBLE}
6019 C99's @code{_Complex long double}
6025 @geindex gcc_jit_context_get_int_type (C function)
6026 @anchor{topics/types gcc_jit_context_get_int_type}@anchor{7c}
6027 @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)
6029 Access the integer type of the given size.
6032 @node Pointers const and volatile,Vector types,Standard types,Types
6033 @anchor{topics/types pointers-const-and-volatile}@anchor{7d}
6034 @subsection Pointers, @cite{const}, and @cite{volatile}
6037 @geindex gcc_jit_type_get_pointer (C function)
6038 @anchor{topics/types gcc_jit_type_get_pointer}@anchor{79}
6039 @deffn {C Function} gcc_jit_type *gcc_jit_type_get_pointer (gcc_jit_type@w{ }*type)
6041 Given type "T", get type "T*".
6044 @geindex gcc_jit_type_get_const (C function)
6045 @anchor{topics/types gcc_jit_type_get_const}@anchor{7a}
6046 @deffn {C Function} gcc_jit_type *gcc_jit_type_get_const (gcc_jit_type@w{ }*type)
6048 Given type "T", get type "const T".
6051 @geindex gcc_jit_type_get_volatile (C function)
6052 @anchor{topics/types gcc_jit_type_get_volatile}@anchor{7e}
6053 @deffn {C Function} gcc_jit_type *gcc_jit_type_get_volatile (gcc_jit_type@w{ }*type)
6055 Given type "T", get type "volatile T".
6058 @geindex gcc_jit_context_new_array_type (C function)
6059 @anchor{topics/types gcc_jit_context_new_array_type}@anchor{7f}
6060 @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)
6062 Given type "T", get type "T[N]" (for a constant N).
6065 @geindex gcc_jit_type_get_aligned (C function)
6066 @anchor{topics/types gcc_jit_type_get_aligned}@anchor{80}
6067 @deffn {C Function} gcc_jit_type * gcc_jit_type_get_aligned (gcc_jit_type@w{ }*type, size_t@w{ }alignment_in_bytes)
6069 Given type "T", get type:
6072 T __attribute__ ((aligned (ALIGNMENT_IN_BYTES)))
6077 The alignment must be a power of two.
6079 This entrypoint was added in @pxref{81,,LIBGCCJIT_ABI_7}; you can test for
6083 #ifdef LIBGCCJIT_HAVE_gcc_jit_type_get_aligned
6089 @node Vector types,Structures and unions,Pointers const and volatile,Types
6090 @anchor{topics/types vector-types}@anchor{82}
6091 @subsection Vector types
6094 @geindex gcc_jit_type_get_vector (C function)
6095 @anchor{topics/types gcc_jit_type_get_vector}@anchor{83}
6096 @deffn {C Function} gcc_jit_type * gcc_jit_type_get_vector (gcc_jit_type@w{ }*type, size_t@w{ }num_units)
6098 Given type "T", get type:
6101 T __attribute__ ((vector_size (sizeof(T) * num_units))
6106 T must be integral or floating point; num_units must be a power of two.
6108 This can be used to construct a vector type in which operations
6109 are applied element-wise. The compiler will automatically
6110 use SIMD instructions where possible. See:
6111 @indicateurl{https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html}
6113 For example, assuming 4-byte @code{ints}, then:
6116 typedef int v4si __attribute__ ((vector_size (16)));
6121 can be obtained using:
6124 gcc_jit_type *int_type = gcc_jit_context_get_type (ctxt,
6126 gcc_jit_type *v4si_type = gcc_jit_type_get_vector (int_type, 4);
6131 This API entrypoint was added in @pxref{84,,LIBGCCJIT_ABI_8}; you can test
6132 for its presence using
6135 #ifdef LIBGCCJIT_HAVE_gcc_jit_type_get_vector
6140 Vector rvalues can be generated using
6141 @pxref{85,,gcc_jit_context_new_rvalue_from_vector()}.
6144 @node Structures and unions,Function pointer types,Vector types,Types
6145 @anchor{topics/types structures-and-unions}@anchor{86}
6146 @subsection Structures and unions
6149 @geindex gcc_jit_struct (C type)
6150 @anchor{topics/types gcc_jit_struct}@anchor{87}
6151 @deffn {C Type} gcc_jit_struct
6154 A compound type analagous to a C @cite{struct}.
6156 @geindex gcc_jit_field (C type)
6157 @anchor{topics/types gcc_jit_field}@anchor{88}
6158 @deffn {C Type} gcc_jit_field
6161 A field within a @pxref{87,,gcc_jit_struct}.
6163 You can model C @cite{struct} types by creating @pxref{87,,gcc_jit_struct *} and
6164 @pxref{88,,gcc_jit_field} instances, in either order:
6170 by creating the fields, then the structure. For example, to model:
6173 struct coord @{double x; double y; @};
6181 gcc_jit_field *field_x =
6182 gcc_jit_context_new_field (ctxt, NULL, double_type, "x");
6183 gcc_jit_field *field_y =
6184 gcc_jit_context_new_field (ctxt, NULL, double_type, "y");
6185 gcc_jit_field *fields[2] = @{field_x, field_y@};
6186 gcc_jit_struct *coord =
6187 gcc_jit_context_new_struct_type (ctxt, NULL, "coord", 2, fields);
6193 by creating the structure, then populating it with fields, typically
6194 to allow modelling self-referential structs such as:
6197 struct node @{ int m_hash; struct node *m_next; @};
6205 gcc_jit_type *node =
6206 gcc_jit_context_new_opaque_struct (ctxt, NULL, "node");
6207 gcc_jit_type *node_ptr =
6208 gcc_jit_type_get_pointer (node);
6209 gcc_jit_field *field_hash =
6210 gcc_jit_context_new_field (ctxt, NULL, int_type, "m_hash");
6211 gcc_jit_field *field_next =
6212 gcc_jit_context_new_field (ctxt, NULL, node_ptr, "m_next");
6213 gcc_jit_field *fields[2] = @{field_hash, field_next@};
6214 gcc_jit_struct_set_fields (node, NULL, 2, fields);
6220 @geindex gcc_jit_context_new_field (C function)
6221 @anchor{topics/types gcc_jit_context_new_field}@anchor{89}
6222 @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)
6224 Construct a new field, with the given type and name.
6226 The parameter @code{name} must be non-NULL. The call takes a copy of the
6227 underlying string, so it is valid to pass in a pointer to an on-stack
6231 @geindex gcc_jit_field_as_object (C function)
6232 @anchor{topics/types gcc_jit_field_as_object}@anchor{8a}
6233 @deffn {C Function} gcc_jit_object * gcc_jit_field_as_object (gcc_jit_field@w{ }*field)
6235 Upcast from field to object.
6238 @geindex gcc_jit_context_new_struct_type (C function)
6239 @anchor{topics/types gcc_jit_context_new_struct_type}@anchor{8b}
6240 @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)
6244 Construct a new struct type, with the given name and fields.
6246 The parameter @code{name} must be non-NULL. The call takes a copy of
6247 the underlying string, so it is valid to pass in a pointer to an
6252 @geindex gcc_jit_context_new_opaque_struct (C function)
6253 @anchor{topics/types gcc_jit_context_new_opaque_struct}@anchor{8c}
6254 @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)
6256 Construct a new struct type, with the given name, but without
6257 specifying the fields. The fields can be omitted (in which case the
6258 size of the struct is not known), or later specified using
6259 @pxref{8d,,gcc_jit_struct_set_fields()}.
6261 The parameter @code{name} must be non-NULL. The call takes a copy of
6262 the underlying string, so it is valid to pass in a pointer to an
6266 @geindex gcc_jit_struct_as_type (C function)
6267 @anchor{topics/types gcc_jit_struct_as_type}@anchor{8e}
6268 @deffn {C Function} gcc_jit_type * gcc_jit_struct_as_type (gcc_jit_struct@w{ }*struct_type)
6270 Upcast from struct to type.
6273 @geindex gcc_jit_struct_set_fields (C function)
6274 @anchor{topics/types gcc_jit_struct_set_fields}@anchor{8d}
6275 @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)
6277 Populate the fields of a formerly-opaque struct type.
6279 This can only be called once on a given struct type.
6282 @geindex gcc_jit_context_new_union_type (C function)
6283 @anchor{topics/types gcc_jit_context_new_union_type}@anchor{8f}
6284 @deffn {C Function} gcc_jit_type * gcc_jit_context_new_union_type (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, const char@w{ }*name, int@w{ }num_fields, gcc_jit_field@w{ }**fields)
6286 Construct a new union type, with the given name and fields.
6288 The parameter @code{name} must be non-NULL. It is copied, so the input
6289 buffer does not need to outlive the call.
6302 create_code (gcc_jit_context *ctxt, void *user_data)
6304 /* Let's try to inject the equivalent of:
6308 union int_or_float u;
6313 gcc_jit_type *int_type =
6314 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
6315 gcc_jit_type *float_type =
6316 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_FLOAT);
6317 gcc_jit_field *as_int =
6318 gcc_jit_context_new_field (ctxt,
6322 gcc_jit_field *as_float =
6323 gcc_jit_context_new_field (ctxt,
6327 gcc_jit_field *fields[] = @{as_int, as_float@};
6328 gcc_jit_type *union_type =
6329 gcc_jit_context_new_union_type (ctxt, NULL,
6330 "int_or_float", 2, fields);
6332 /* Build the test function. */
6333 gcc_jit_param *param_i =
6334 gcc_jit_context_new_param (ctxt, NULL, int_type, "i");
6335 gcc_jit_function *test_fn =
6336 gcc_jit_context_new_function (ctxt, NULL,
6337 GCC_JIT_FUNCTION_EXPORTED,
6344 gcc_jit_function_new_local (test_fn, NULL,
6347 gcc_jit_block *block = gcc_jit_function_new_block (test_fn, NULL);
6350 gcc_jit_block_add_assignment (
6353 /* "u.as_int = ..." */
6354 gcc_jit_lvalue_access_field (u,
6357 gcc_jit_param_as_rvalue (param_i));
6359 /* return u.as_float; */
6360 gcc_jit_block_end_with_return (
6362 gcc_jit_rvalue_access_field (gcc_jit_lvalue_as_rvalue (u),
6373 @node Function pointer types,,Structures and unions,Types
6374 @anchor{topics/types function-pointer-types}@anchor{90}
6375 @subsection Function pointer types
6378 Function pointer types can be created using
6379 @pxref{91,,gcc_jit_context_new_function_ptr_type()}.
6381 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
6382 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6384 @c This is free software: you can redistribute it and/or modify it
6385 @c under the terms of the GNU General Public License as published by
6386 @c the Free Software Foundation, either version 3 of the License, or
6387 @c (at your option) any later version.
6389 @c This program is distributed in the hope that it will be useful, but
6390 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6391 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
6392 @c General Public License for more details.
6394 @c You should have received a copy of the GNU General Public License
6395 @c along with this program. If not, see
6396 @c <http://www.gnu.org/licenses/>.
6398 @node Expressions,Creating and using functions,Types,Topic Reference
6399 @anchor{topics/expressions expressions}@anchor{92}@anchor{topics/expressions doc}@anchor{93}
6400 @section Expressions
6406 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions.
6410 * Simple expressions::
6411 * Vector expressions::
6412 * Unary Operations::
6413 * Binary Operations::
6416 * Function pointers::
6421 * Global variables::
6426 @node Rvalues,Lvalues,,Expressions
6427 @anchor{topics/expressions rvalues}@anchor{94}
6431 @geindex gcc_jit_rvalue (C type)
6432 @anchor{topics/expressions gcc_jit_rvalue}@anchor{13}
6433 @deffn {C Type} gcc_jit_rvalue
6436 A @pxref{13,,gcc_jit_rvalue *} is an expression that can be computed.
6438 It can be simple, e.g.:
6446 an integer value e.g. @cite{0} or @cite{42}
6449 a string literal e.g. @cite{"Hello world"}
6452 a variable e.g. @cite{i}. These are also lvalues (see below).
6464 a unary expression e.g. @cite{!cond}
6467 a binary expression e.g. @cite{(a + b)}
6470 a function call e.g. @cite{get_distance (&player_ship@comma{} &target)}
6477 Every rvalue has an associated type, and the API will check to ensure
6478 that types match up correctly (otherwise the context will emit an error).
6480 @geindex gcc_jit_rvalue_get_type (C function)
6481 @anchor{topics/expressions gcc_jit_rvalue_get_type}@anchor{95}
6482 @deffn {C Function} gcc_jit_type *gcc_jit_rvalue_get_type (gcc_jit_rvalue@w{ }*rvalue)
6484 Get the type of this rvalue.
6487 @geindex gcc_jit_rvalue_as_object (C function)
6488 @anchor{topics/expressions gcc_jit_rvalue_as_object}@anchor{14}
6489 @deffn {C Function} gcc_jit_object *gcc_jit_rvalue_as_object (gcc_jit_rvalue@w{ }*rvalue)
6491 Upcast the given rvalue to be an object.
6495 * Simple expressions::
6496 * Vector expressions::
6497 * Unary Operations::
6498 * Binary Operations::
6501 * Function pointers::
6506 @node Simple expressions,Vector expressions,,Rvalues
6507 @anchor{topics/expressions simple-expressions}@anchor{96}
6508 @subsubsection Simple expressions
6511 @geindex gcc_jit_context_new_rvalue_from_int (C function)
6512 @anchor{topics/expressions gcc_jit_context_new_rvalue_from_int}@anchor{30}
6513 @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)
6515 Given a numeric type (integer or floating point), build an rvalue for
6516 the given constant @code{int} value.
6519 @geindex gcc_jit_context_new_rvalue_from_long (C function)
6520 @anchor{topics/expressions gcc_jit_context_new_rvalue_from_long}@anchor{97}
6521 @deffn {C Function} gcc_jit_rvalue * gcc_jit_context_new_rvalue_from_long (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*numeric_type, long@w{ }value)
6523 Given a numeric type (integer or floating point), build an rvalue for
6524 the given constant @code{long} value.
6527 @geindex gcc_jit_context_zero (C function)
6528 @anchor{topics/expressions gcc_jit_context_zero}@anchor{2b}
6529 @deffn {C Function} gcc_jit_rvalue *gcc_jit_context_zero (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*numeric_type)
6531 Given a numeric type (integer or floating point), get the rvalue for
6532 zero. Essentially this is just a shortcut for:
6535 gcc_jit_context_new_rvalue_from_int (ctxt, numeric_type, 0)
6541 @geindex gcc_jit_context_one (C function)
6542 @anchor{topics/expressions gcc_jit_context_one}@anchor{2f}
6543 @deffn {C Function} gcc_jit_rvalue *gcc_jit_context_one (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*numeric_type)
6545 Given a numeric type (integer or floating point), get the rvalue for
6546 one. Essentially this is just a shortcut for:
6549 gcc_jit_context_new_rvalue_from_int (ctxt, numeric_type, 1)
6555 @geindex gcc_jit_context_new_rvalue_from_double (C function)
6556 @anchor{topics/expressions gcc_jit_context_new_rvalue_from_double}@anchor{31}
6557 @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)
6559 Given a numeric type (integer or floating point), build an rvalue for
6560 the given constant @code{double} value.
6563 @geindex gcc_jit_context_new_rvalue_from_ptr (C function)
6564 @anchor{topics/expressions gcc_jit_context_new_rvalue_from_ptr}@anchor{98}
6565 @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)
6567 Given a pointer type, build an rvalue for the given address.
6570 @geindex gcc_jit_context_null (C function)
6571 @anchor{topics/expressions gcc_jit_context_null}@anchor{99}
6572 @deffn {C Function} gcc_jit_rvalue *gcc_jit_context_null (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*pointer_type)
6574 Given a pointer type, build an rvalue for @code{NULL}. Essentially this
6575 is just a shortcut for:
6578 gcc_jit_context_new_rvalue_from_ptr (ctxt, pointer_type, NULL)
6584 @geindex gcc_jit_context_new_string_literal (C function)
6585 @anchor{topics/expressions gcc_jit_context_new_string_literal}@anchor{9a}
6586 @deffn {C Function} gcc_jit_rvalue * gcc_jit_context_new_string_literal (gcc_jit_context@w{ }*ctxt, const char@w{ }*value)
6588 Generate an rvalue for the given NIL-terminated string, of type
6589 @code{GCC_JIT_TYPE_CONST_CHAR_PTR}.
6591 The parameter @code{value} must be non-NULL. The call takes a copy of the
6592 underlying string, so it is valid to pass in a pointer to an on-stack
6596 @node Vector expressions,Unary Operations,Simple expressions,Rvalues
6597 @anchor{topics/expressions vector-expressions}@anchor{9b}
6598 @subsubsection Vector expressions
6601 @geindex gcc_jit_context_new_rvalue_from_vector (C function)
6602 @anchor{topics/expressions gcc_jit_context_new_rvalue_from_vector}@anchor{85}
6603 @deffn {C Function} gcc_jit_rvalue * gcc_jit_context_new_rvalue_from_vector (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, gcc_jit_type@w{ }*vec_type, size_t@w{ }num_elements, gcc_jit_rvalue@w{ }**elements)
6605 Build a vector rvalue from an array of elements.
6607 "vec_type" should be a vector type, created using
6608 @pxref{83,,gcc_jit_type_get_vector()}.
6610 "num_elements" should match that of the vector type.
6612 This entrypoint was added in @pxref{9c,,LIBGCCJIT_ABI_10}; you can test for
6616 #ifdef LIBGCCJIT_HAVE_gcc_jit_context_new_rvalue_from_vector
6622 @node Unary Operations,Binary Operations,Vector expressions,Rvalues
6623 @anchor{topics/expressions unary-operations}@anchor{9d}
6624 @subsubsection Unary Operations
6627 @geindex gcc_jit_context_new_unary_op (C function)
6628 @anchor{topics/expressions gcc_jit_context_new_unary_op}@anchor{9e}
6629 @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)
6631 Build a unary operation out of an input rvalue.
6634 @geindex gcc_jit_unary_op (C type)
6635 @anchor{topics/expressions gcc_jit_unary_op}@anchor{9f}
6636 @deffn {C Type} enum gcc_jit_unary_op
6639 The available unary operations are:
6642 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx}
6653 @pxref{a0,,GCC_JIT_UNARY_OP_MINUS}
6661 @pxref{a1,,GCC_JIT_UNARY_OP_BITWISE_NEGATE}
6669 @pxref{a2,,GCC_JIT_UNARY_OP_LOGICAL_NEGATE}
6677 @pxref{a3,,GCC_JIT_UNARY_OP_ABS}
6686 @geindex GCC_JIT_UNARY_OP_MINUS (C macro)
6687 @anchor{topics/expressions GCC_JIT_UNARY_OP_MINUS}@anchor{a0}
6688 @deffn {C Macro} GCC_JIT_UNARY_OP_MINUS
6690 Negate an arithmetic value; analogous to:
6701 @geindex GCC_JIT_UNARY_OP_BITWISE_NEGATE (C macro)
6702 @anchor{topics/expressions GCC_JIT_UNARY_OP_BITWISE_NEGATE}@anchor{a1}
6703 @deffn {C Macro} GCC_JIT_UNARY_OP_BITWISE_NEGATE
6705 Bitwise negation of an integer value (one's complement); analogous
6717 @geindex GCC_JIT_UNARY_OP_LOGICAL_NEGATE (C macro)
6718 @anchor{topics/expressions GCC_JIT_UNARY_OP_LOGICAL_NEGATE}@anchor{a2}
6719 @deffn {C Macro} GCC_JIT_UNARY_OP_LOGICAL_NEGATE
6721 Logical negation of an arithmetic or pointer value; analogous to:
6732 @geindex GCC_JIT_UNARY_OP_ABS (C macro)
6733 @anchor{topics/expressions GCC_JIT_UNARY_OP_ABS}@anchor{a3}
6734 @deffn {C Macro} GCC_JIT_UNARY_OP_ABS
6736 Absolute value of an arithmetic expression; analogous to:
6747 @node Binary Operations,Comparisons,Unary Operations,Rvalues
6748 @anchor{topics/expressions binary-operations}@anchor{a4}
6749 @subsubsection Binary Operations
6752 @geindex gcc_jit_context_new_binary_op (C function)
6753 @anchor{topics/expressions gcc_jit_context_new_binary_op}@anchor{12}
6754 @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)
6756 Build a binary operation out of two constituent rvalues.
6759 @geindex gcc_jit_binary_op (C type)
6760 @anchor{topics/expressions gcc_jit_binary_op}@anchor{a5}
6761 @deffn {C Type} enum gcc_jit_binary_op
6764 The available binary operations are:
6767 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx}
6778 @pxref{a6,,GCC_JIT_BINARY_OP_PLUS}
6786 @pxref{a7,,GCC_JIT_BINARY_OP_MINUS}
6794 @pxref{a8,,GCC_JIT_BINARY_OP_MULT}
6802 @pxref{a9,,GCC_JIT_BINARY_OP_DIVIDE}
6810 @pxref{aa,,GCC_JIT_BINARY_OP_MODULO}
6818 @pxref{ab,,GCC_JIT_BINARY_OP_BITWISE_AND}
6826 @pxref{ac,,GCC_JIT_BINARY_OP_BITWISE_XOR}
6834 @pxref{ad,,GCC_JIT_BINARY_OP_BITWISE_OR}
6842 @pxref{ae,,GCC_JIT_BINARY_OP_LOGICAL_AND}
6850 @pxref{af,,GCC_JIT_BINARY_OP_LOGICAL_OR}
6858 @pxref{b0,,GCC_JIT_BINARY_OP_LSHIFT}
6866 @pxref{b1,,GCC_JIT_BINARY_OP_RSHIFT}
6875 @geindex GCC_JIT_BINARY_OP_PLUS (C macro)
6876 @anchor{topics/expressions GCC_JIT_BINARY_OP_PLUS}@anchor{a6}
6877 @deffn {C Macro} GCC_JIT_BINARY_OP_PLUS
6879 Addition of arithmetic values; analogous to:
6889 For pointer addition, use @pxref{b2,,gcc_jit_context_new_array_access()}.
6892 @geindex GCC_JIT_BINARY_OP_MINUS (C macro)
6893 @anchor{topics/expressions GCC_JIT_BINARY_OP_MINUS}@anchor{a7}
6894 @deffn {C Macro} GCC_JIT_BINARY_OP_MINUS
6896 Subtraction of arithmetic values; analogous to:
6907 @geindex GCC_JIT_BINARY_OP_MULT (C macro)
6908 @anchor{topics/expressions GCC_JIT_BINARY_OP_MULT}@anchor{a8}
6909 @deffn {C Macro} GCC_JIT_BINARY_OP_MULT
6911 Multiplication of a pair of arithmetic values; analogous to:
6922 @geindex GCC_JIT_BINARY_OP_DIVIDE (C macro)
6923 @anchor{topics/expressions GCC_JIT_BINARY_OP_DIVIDE}@anchor{a9}
6924 @deffn {C Macro} GCC_JIT_BINARY_OP_DIVIDE
6926 Quotient of division of arithmetic values; analogous to:
6936 The result type affects the kind of division: if the result type is
6937 integer-based, then the result is truncated towards zero, whereas
6938 a floating-point result type indicates floating-point division.
6941 @geindex GCC_JIT_BINARY_OP_MODULO (C macro)
6942 @anchor{topics/expressions GCC_JIT_BINARY_OP_MODULO}@anchor{aa}
6943 @deffn {C Macro} GCC_JIT_BINARY_OP_MODULO
6945 Remainder of division of arithmetic values; analogous to:
6956 @geindex GCC_JIT_BINARY_OP_BITWISE_AND (C macro)
6957 @anchor{topics/expressions GCC_JIT_BINARY_OP_BITWISE_AND}@anchor{ab}
6958 @deffn {C Macro} GCC_JIT_BINARY_OP_BITWISE_AND
6960 Bitwise AND; analogous to:
6971 @geindex GCC_JIT_BINARY_OP_BITWISE_XOR (C macro)
6972 @anchor{topics/expressions GCC_JIT_BINARY_OP_BITWISE_XOR}@anchor{ac}
6973 @deffn {C Macro} GCC_JIT_BINARY_OP_BITWISE_XOR
6975 Bitwise exclusive OR; analogous to:
6986 @geindex GCC_JIT_BINARY_OP_BITWISE_OR (C macro)
6987 @anchor{topics/expressions GCC_JIT_BINARY_OP_BITWISE_OR}@anchor{ad}
6988 @deffn {C Macro} GCC_JIT_BINARY_OP_BITWISE_OR
6990 Bitwise inclusive OR; analogous to:
7001 @geindex GCC_JIT_BINARY_OP_LOGICAL_AND (C macro)
7002 @anchor{topics/expressions GCC_JIT_BINARY_OP_LOGICAL_AND}@anchor{ae}
7003 @deffn {C Macro} GCC_JIT_BINARY_OP_LOGICAL_AND
7005 Logical AND; analogous to:
7008 (EXPR_A) && (EXPR_B)
7016 @geindex GCC_JIT_BINARY_OP_LOGICAL_OR (C macro)
7017 @anchor{topics/expressions GCC_JIT_BINARY_OP_LOGICAL_OR}@anchor{af}
7018 @deffn {C Macro} GCC_JIT_BINARY_OP_LOGICAL_OR
7020 Logical OR; analogous to:
7023 (EXPR_A) || (EXPR_B)
7031 @geindex GCC_JIT_BINARY_OP_LSHIFT (C macro)
7032 @anchor{topics/expressions GCC_JIT_BINARY_OP_LSHIFT}@anchor{b0}
7033 @deffn {C Macro} GCC_JIT_BINARY_OP_LSHIFT
7035 Left shift; analogous to:
7038 (EXPR_A) << (EXPR_B)
7046 @geindex GCC_JIT_BINARY_OP_RSHIFT (C macro)
7047 @anchor{topics/expressions GCC_JIT_BINARY_OP_RSHIFT}@anchor{b1}
7048 @deffn {C Macro} GCC_JIT_BINARY_OP_RSHIFT
7050 Right shift; analogous to:
7053 (EXPR_A) >> (EXPR_B)
7061 @node Comparisons,Function calls,Binary Operations,Rvalues
7062 @anchor{topics/expressions comparisons}@anchor{b3}
7063 @subsubsection Comparisons
7066 @geindex gcc_jit_context_new_comparison (C function)
7067 @anchor{topics/expressions gcc_jit_context_new_comparison}@anchor{2c}
7068 @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)
7070 Build a boolean rvalue out of the comparison of two other rvalues.
7073 @geindex gcc_jit_comparison (C type)
7074 @anchor{topics/expressions gcc_jit_comparison}@anchor{b4}
7075 @deffn {C Type} enum gcc_jit_comparison
7079 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx}
7090 @code{GCC_JIT_COMPARISON_EQ}
7098 @code{GCC_JIT_COMPARISON_NE}
7106 @code{GCC_JIT_COMPARISON_LT}
7114 @code{GCC_JIT_COMPARISON_LE}
7122 @code{GCC_JIT_COMPARISON_GT}
7130 @code{GCC_JIT_COMPARISON_GE}
7139 @node Function calls,Function pointers,Comparisons,Rvalues
7140 @anchor{topics/expressions function-calls}@anchor{b5}
7141 @subsubsection Function calls
7144 @geindex gcc_jit_context_new_call (C function)
7145 @anchor{topics/expressions gcc_jit_context_new_call}@anchor{b6}
7146 @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)
7148 Given a function and the given table of argument rvalues, construct a
7149 call to the function, with the result as an rvalue.
7153 @pxref{b6,,gcc_jit_context_new_call()} merely builds a
7154 @pxref{13,,gcc_jit_rvalue} i.e. an expression that can be evaluated,
7155 perhaps as part of a more complicated expression.
7156 The call @emph{won't} happen unless you add a statement to a function
7157 that evaluates the expression.
7159 For example, if you want to call a function and discard the result
7160 (or to call a function with @code{void} return type), use
7161 @pxref{b7,,gcc_jit_block_add_eval()}:
7164 /* Add "(void)printf (arg0, arg1);". */
7165 gcc_jit_block_add_eval (
7167 gcc_jit_context_new_call (
7179 @geindex gcc_jit_context_new_call_through_ptr (C function)
7180 @anchor{topics/expressions gcc_jit_context_new_call_through_ptr}@anchor{b8}
7181 @deffn {C Function} gcc_jit_rvalue * gcc_jit_context_new_call_through_ptr (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, gcc_jit_rvalue@w{ }*fn_ptr, int@w{ }numargs, gcc_jit_rvalue@w{ }**args)
7183 Given an rvalue of function pointer type (e.g. from
7184 @pxref{91,,gcc_jit_context_new_function_ptr_type()}), and the given table of
7185 argument rvalues, construct a call to the function pointer, with the
7186 result as an rvalue.
7190 The same caveat as for @pxref{b6,,gcc_jit_context_new_call()} applies.
7195 @geindex gcc_jit_rvalue_set_bool_require_tail_call (C function)
7196 @anchor{topics/expressions gcc_jit_rvalue_set_bool_require_tail_call}@anchor{b9}
7197 @deffn {C Function} void gcc_jit_rvalue_set_bool_require_tail_call (gcc_jit_rvalue@w{ }*call, int@w{ }require_tail_call)
7199 Given an @pxref{13,,gcc_jit_rvalue *} for a call created through
7200 @pxref{b6,,gcc_jit_context_new_call()} or
7201 @pxref{b8,,gcc_jit_context_new_call_through_ptr()}, mark/clear the
7202 call as needing tail-call optimization. The optimizer will
7203 attempt to optimize the call into a jump instruction; if it is
7204 unable to do do, an error will be emitted.
7206 This may be useful when implementing functions that use the
7207 continuation-passing style (e.g. for functional programming
7208 languages), in which every function "returns" by calling a
7209 "continuation" function pointer. This call must be
7210 guaranteed to be implemented as a jump, otherwise the program
7211 could consume an arbitrary amount of stack space as it executed.
7213 This entrypoint was added in @pxref{ba,,LIBGCCJIT_ABI_6}; you can test for
7217 #ifdef LIBGCCJIT_HAVE_gcc_jit_rvalue_set_bool_require_tail_call
7223 @node Function pointers,Type-coercion,Function calls,Rvalues
7224 @anchor{topics/expressions function-pointers}@anchor{bb}
7225 @subsubsection Function pointers
7228 Function pointers can be obtained:
7236 from a @pxref{29,,gcc_jit_function} using
7237 @pxref{bc,,gcc_jit_function_get_address()}, or
7240 from an existing function using
7241 @pxref{98,,gcc_jit_context_new_rvalue_from_ptr()},
7242 using a function pointer type obtained using
7243 @pxref{91,,gcc_jit_context_new_function_ptr_type()}.
7247 @node Type-coercion,,Function pointers,Rvalues
7248 @anchor{topics/expressions type-coercion}@anchor{bd}
7249 @subsubsection Type-coercion
7252 @geindex gcc_jit_context_new_cast (C function)
7253 @anchor{topics/expressions gcc_jit_context_new_cast}@anchor{be}
7254 @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)
7256 Given an rvalue of T, construct another rvalue of another type.
7258 Currently only a limited set of conversions are possible:
7272 P* <-> Q*, for pointer types P and Q
7277 @node Lvalues,Working with pointers structs and unions,Rvalues,Expressions
7278 @anchor{topics/expressions lvalues}@anchor{bf}
7282 @geindex gcc_jit_lvalue (C type)
7283 @anchor{topics/expressions gcc_jit_lvalue}@anchor{24}
7284 @deffn {C Type} gcc_jit_lvalue
7287 An lvalue is something that can of the @emph{left}-hand side of an assignment:
7288 a storage area (such as a variable). It is also usable as an rvalue,
7289 where the rvalue is computed by reading from the storage area.
7291 @geindex gcc_jit_lvalue_as_object (C function)
7292 @anchor{topics/expressions gcc_jit_lvalue_as_object}@anchor{c0}
7293 @deffn {C Function} gcc_jit_object * gcc_jit_lvalue_as_object (gcc_jit_lvalue@w{ }*lvalue)
7295 Upcast an lvalue to be an object.
7298 @geindex gcc_jit_lvalue_as_rvalue (C function)
7299 @anchor{topics/expressions gcc_jit_lvalue_as_rvalue}@anchor{c1}
7300 @deffn {C Function} gcc_jit_rvalue * gcc_jit_lvalue_as_rvalue (gcc_jit_lvalue@w{ }*lvalue)
7302 Upcast an lvalue to be an rvalue.
7305 @geindex gcc_jit_lvalue_get_address (C function)
7306 @anchor{topics/expressions gcc_jit_lvalue_get_address}@anchor{c2}
7307 @deffn {C Function} gcc_jit_rvalue * gcc_jit_lvalue_get_address (gcc_jit_lvalue@w{ }*lvalue, gcc_jit_location@w{ }*loc)
7309 Take the address of an lvalue; analogous to:
7321 * Global variables::
7325 @node Global variables,,,Lvalues
7326 @anchor{topics/expressions global-variables}@anchor{c3}
7327 @subsubsection Global variables
7330 @geindex gcc_jit_context_new_global (C function)
7331 @anchor{topics/expressions gcc_jit_context_new_global}@anchor{c4}
7332 @deffn {C Function} gcc_jit_lvalue * gcc_jit_context_new_global (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, enum gcc_jit_global_kind@w{ }kind, gcc_jit_type@w{ }*type, const char@w{ }*name)
7334 Add a new global variable of the given type and name to the context.
7336 The parameter @code{name} must be non-NULL. The call takes a copy of the
7337 underlying string, so it is valid to pass in a pointer to an on-stack
7340 The "kind" parameter determines the visibility of the "global" outside
7341 of the @pxref{16,,gcc_jit_result}:
7343 @geindex gcc_jit_global_kind (C type)
7344 @anchor{topics/expressions gcc_jit_global_kind}@anchor{c5}
7345 @deffn {C Type} enum gcc_jit_global_kind
7348 @geindex GCC_JIT_GLOBAL_EXPORTED (C macro)
7349 @anchor{topics/expressions GCC_JIT_GLOBAL_EXPORTED}@anchor{c6}
7350 @deffn {C Macro} GCC_JIT_GLOBAL_EXPORTED
7352 Global is defined by the client code and is visible
7353 by name outside of this JIT context via
7354 @pxref{c7,,gcc_jit_result_get_global()} (and this value is required for
7355 the global to be accessible via that entrypoint).
7358 @geindex GCC_JIT_GLOBAL_INTERNAL (C macro)
7359 @anchor{topics/expressions GCC_JIT_GLOBAL_INTERNAL}@anchor{c8}
7360 @deffn {C Macro} GCC_JIT_GLOBAL_INTERNAL
7362 Global is defined by the client code, but is invisible
7363 outside of it. Analogous to a "static" global within a .c file.
7364 Specifically, the variable will only be visible within this
7365 context and within child contexts.
7368 @geindex GCC_JIT_GLOBAL_IMPORTED (C macro)
7369 @anchor{topics/expressions GCC_JIT_GLOBAL_IMPORTED}@anchor{c9}
7370 @deffn {C Macro} GCC_JIT_GLOBAL_IMPORTED
7372 Global is not defined by the client code; we're merely
7373 referring to it. Analogous to using an "extern" global from a
7378 @node Working with pointers structs and unions,,Lvalues,Expressions
7379 @anchor{topics/expressions working-with-pointers-structs-and-unions}@anchor{ca}
7380 @subsection Working with pointers, structs and unions
7383 @geindex gcc_jit_rvalue_dereference (C function)
7384 @anchor{topics/expressions gcc_jit_rvalue_dereference}@anchor{cb}
7385 @deffn {C Function} gcc_jit_lvalue * gcc_jit_rvalue_dereference (gcc_jit_rvalue@w{ }*rvalue, gcc_jit_location@w{ }*loc)
7387 Given an rvalue of pointer type @code{T *}, dereferencing the pointer,
7388 getting an lvalue of type @code{T}. Analogous to:
7399 Field access is provided separately for both lvalues and rvalues.
7401 @geindex gcc_jit_lvalue_access_field (C function)
7402 @anchor{topics/expressions gcc_jit_lvalue_access_field}@anchor{cc}
7403 @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)
7405 Given an lvalue of struct or union type, access the given field,
7406 getting an lvalue of the field's type. Analogous to:
7417 @geindex gcc_jit_rvalue_access_field (C function)
7418 @anchor{topics/expressions gcc_jit_rvalue_access_field}@anchor{cd}
7419 @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)
7421 Given an rvalue of struct or union type, access the given field
7422 as an rvalue. Analogous to:
7433 @geindex gcc_jit_rvalue_dereference_field (C function)
7434 @anchor{topics/expressions gcc_jit_rvalue_dereference_field}@anchor{ce}
7435 @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)
7437 Given an rvalue of pointer type @code{T *} where T is of struct or union
7438 type, access the given field as an lvalue. Analogous to:
7446 in C, itself equivalent to @code{(*EXPR).FIELD}.
7449 @geindex gcc_jit_context_new_array_access (C function)
7450 @anchor{topics/expressions gcc_jit_context_new_array_access}@anchor{b2}
7451 @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)
7453 Given an rvalue of pointer type @code{T *}, get at the element @cite{T} at
7454 the given index, using standard C array indexing rules i.e. each
7455 increment of @code{index} corresponds to @code{sizeof(T)} bytes.
7464 in C (or, indeed, to @code{PTR + INDEX}).
7467 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
7468 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
7470 @c This is free software: you can redistribute it and/or modify it
7471 @c under the terms of the GNU General Public License as published by
7472 @c the Free Software Foundation, either version 3 of the License, or
7473 @c (at your option) any later version.
7475 @c This program is distributed in the hope that it will be useful, but
7476 @c WITHOUT ANY WARRANTY; without even the implied warranty of
7477 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
7478 @c General Public License for more details.
7480 @c You should have received a copy of the GNU General Public License
7481 @c along with this program. If not, see
7482 @c <http://www.gnu.org/licenses/>.
7484 @node Creating and using functions,Function pointers<2>,Expressions,Topic Reference
7485 @anchor{topics/functions doc}@anchor{cf}@anchor{topics/functions creating-and-using-functions}@anchor{d0}
7486 @section Creating and using functions
7497 @node Params,Functions,,Creating and using functions
7498 @anchor{topics/functions params}@anchor{d1}
7502 @geindex gcc_jit_param (C type)
7503 @anchor{topics/functions gcc_jit_param}@anchor{25}
7504 @deffn {C Type} gcc_jit_param
7506 A @cite{gcc_jit_param} represents a parameter to a function.
7509 @geindex gcc_jit_context_new_param (C function)
7510 @anchor{topics/functions gcc_jit_context_new_param}@anchor{10}
7511 @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)
7513 In preparation for creating a function, create a new parameter of the
7514 given type and name.
7516 The parameter @code{name} must be non-NULL. The call takes a copy of the
7517 underlying string, so it is valid to pass in a pointer to an on-stack
7521 Parameters are lvalues, and thus are also rvalues (and objects), so the
7522 following upcasts are available:
7524 @geindex gcc_jit_param_as_lvalue (C function)
7525 @anchor{topics/functions gcc_jit_param_as_lvalue}@anchor{d2}
7526 @deffn {C Function} gcc_jit_lvalue * gcc_jit_param_as_lvalue (gcc_jit_param@w{ }*param)
7528 Upcasting from param to lvalue.
7531 @geindex gcc_jit_param_as_rvalue (C function)
7532 @anchor{topics/functions gcc_jit_param_as_rvalue}@anchor{d3}
7533 @deffn {C Function} gcc_jit_rvalue * gcc_jit_param_as_rvalue (gcc_jit_param@w{ }*param)
7535 Upcasting from param to rvalue.
7538 @geindex gcc_jit_param_as_object (C function)
7539 @anchor{topics/functions gcc_jit_param_as_object}@anchor{d4}
7540 @deffn {C Function} gcc_jit_object * gcc_jit_param_as_object (gcc_jit_param@w{ }*param)
7542 Upcasting from param to object.
7545 @node Functions,Blocks,Params,Creating and using functions
7546 @anchor{topics/functions functions}@anchor{d5}
7547 @subsection Functions
7550 @geindex gcc_jit_function (C type)
7551 @anchor{topics/functions gcc_jit_function}@anchor{29}
7552 @deffn {C Type} gcc_jit_function
7554 A @cite{gcc_jit_function} represents a function - either one that we're
7555 creating ourselves, or one that we're referencing.
7558 @geindex gcc_jit_context_new_function (C function)
7559 @anchor{topics/functions gcc_jit_context_new_function}@anchor{11}
7560 @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)
7562 Create a gcc_jit_function with the given name and parameters.
7564 @geindex gcc_jit_function_kind (C type)
7565 @anchor{topics/functions gcc_jit_function_kind}@anchor{d6}
7566 @deffn {C Type} enum gcc_jit_function_kind
7569 This enum controls the kind of function created, and has the following
7574 @geindex GCC_JIT_FUNCTION_EXPORTED (C macro)
7575 @anchor{topics/functions GCC_JIT_FUNCTION_EXPORTED}@anchor{d7}
7576 @deffn {C Macro} GCC_JIT_FUNCTION_EXPORTED
7578 Function is defined by the client code and visible
7579 by name outside of the JIT.
7581 This value is required if you want to extract machine code
7582 for this function from a @pxref{16,,gcc_jit_result} via
7583 @pxref{17,,gcc_jit_result_get_code()}.
7586 @geindex GCC_JIT_FUNCTION_INTERNAL (C macro)
7587 @anchor{topics/functions GCC_JIT_FUNCTION_INTERNAL}@anchor{d8}
7588 @deffn {C Macro} GCC_JIT_FUNCTION_INTERNAL
7590 Function is defined by the client code, but is invisible
7591 outside of the JIT. Analogous to a "static" function.
7594 @geindex GCC_JIT_FUNCTION_IMPORTED (C macro)
7595 @anchor{topics/functions GCC_JIT_FUNCTION_IMPORTED}@anchor{d9}
7596 @deffn {C Macro} GCC_JIT_FUNCTION_IMPORTED
7598 Function is not defined by the client code; we're merely
7599 referring to it. Analogous to using an "extern" function from a
7603 @geindex GCC_JIT_FUNCTION_ALWAYS_INLINE (C macro)
7604 @anchor{topics/functions GCC_JIT_FUNCTION_ALWAYS_INLINE}@anchor{da}
7605 @deffn {C Macro} GCC_JIT_FUNCTION_ALWAYS_INLINE
7607 Function is only ever inlined into other functions, and is
7608 invisible outside of the JIT.
7610 Analogous to prefixing with @code{inline} and adding
7611 @code{__attribute__((always_inline))}
7613 Inlining will only occur when the optimization level is
7614 above 0; when optimization is off, this is essentially the
7615 same as GCC_JIT_FUNCTION_INTERNAL.
7619 The parameter @code{name} must be non-NULL. The call takes a copy of the
7620 underlying string, so it is valid to pass in a pointer to an on-stack
7624 @geindex gcc_jit_context_get_builtin_function (C function)
7625 @anchor{topics/functions gcc_jit_context_get_builtin_function}@anchor{db}
7626 @deffn {C Function} gcc_jit_function *gcc_jit_context_get_builtin_function (gcc_jit_context@w{ }*ctxt, const char@w{ }*name)
7629 @geindex gcc_jit_function_as_object (C function)
7630 @anchor{topics/functions gcc_jit_function_as_object}@anchor{dc}
7631 @deffn {C Function} gcc_jit_object * gcc_jit_function_as_object (gcc_jit_function@w{ }*func)
7633 Upcasting from function to object.
7636 @geindex gcc_jit_function_get_param (C function)
7637 @anchor{topics/functions gcc_jit_function_get_param}@anchor{dd}
7638 @deffn {C Function} gcc_jit_param * gcc_jit_function_get_param (gcc_jit_function@w{ }*func, int@w{ }index)
7640 Get the param of the given index (0-based).
7643 @geindex gcc_jit_function_dump_to_dot (C function)
7644 @anchor{topics/functions gcc_jit_function_dump_to_dot}@anchor{33}
7645 @deffn {C Function} void gcc_jit_function_dump_to_dot (gcc_jit_function@w{ }*func, const char@w{ }*path)
7647 Emit the function in graphviz format to the given path.
7650 @geindex gcc_jit_function_new_local (C function)
7651 @anchor{topics/functions gcc_jit_function_new_local}@anchor{26}
7652 @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)
7654 Create a new local variable within the function, of the given type and
7657 The parameter @code{name} must be non-NULL. The call takes a copy of the
7658 underlying string, so it is valid to pass in a pointer to an on-stack
7662 @node Blocks,Statements,Functions,Creating and using functions
7663 @anchor{topics/functions blocks}@anchor{de}
7667 @geindex gcc_jit_block (C type)
7668 @anchor{topics/functions gcc_jit_block}@anchor{28}
7669 @deffn {C Type} gcc_jit_block
7671 A @cite{gcc_jit_block} represents a basic block within a function i.e. a
7672 sequence of statements with a single entry point and a single exit
7675 The first basic block that you create within a function will
7678 Each basic block that you create within a function must be
7679 terminated, either with a conditional, a jump, a return, or a
7682 It's legal to have multiple basic blocks that return within
7686 @geindex gcc_jit_function_new_block (C function)
7687 @anchor{topics/functions gcc_jit_function_new_block}@anchor{df}
7688 @deffn {C Function} gcc_jit_block * gcc_jit_function_new_block (gcc_jit_function@w{ }*func, const char@w{ }*name)
7690 Create a basic block of the given name. The name may be NULL, but
7691 providing meaningful names is often helpful when debugging: it may
7692 show up in dumps of the internal representation, and in error
7693 messages. It is copied, so the input buffer does not need to outlive
7694 the call; you can pass in a pointer to an on-stack buffer, e.g.:
7697 for (pc = 0; pc < fn->fn_num_ops; pc++)
7700 sprintf (buf, "instr%i", pc);
7701 state.op_blocks[pc] = gcc_jit_function_new_block (state.fn, buf);
7708 @geindex gcc_jit_block_as_object (C function)
7709 @anchor{topics/functions gcc_jit_block_as_object}@anchor{e0}
7710 @deffn {C Function} gcc_jit_object * gcc_jit_block_as_object (gcc_jit_block@w{ }*block)
7712 Upcast from block to object.
7715 @geindex gcc_jit_block_get_function (C function)
7716 @anchor{topics/functions gcc_jit_block_get_function}@anchor{e1}
7717 @deffn {C Function} gcc_jit_function * gcc_jit_block_get_function (gcc_jit_block@w{ }*block)
7719 Which function is this block within?
7722 @node Statements,,Blocks,Creating and using functions
7723 @anchor{topics/functions statements}@anchor{e2}
7724 @subsection Statements
7727 @geindex gcc_jit_block_add_eval (C function)
7728 @anchor{topics/functions gcc_jit_block_add_eval}@anchor{b7}
7729 @deffn {C Function} void gcc_jit_block_add_eval (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, gcc_jit_rvalue@w{ }*rvalue)
7731 Add evaluation of an rvalue, discarding the result
7732 (e.g. a function call that "returns" void).
7734 This is equivalent to this C code:
7743 @geindex gcc_jit_block_add_assignment (C function)
7744 @anchor{topics/functions gcc_jit_block_add_assignment}@anchor{2a}
7745 @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)
7747 Add evaluation of an rvalue, assigning the result to the given
7750 This is roughly equivalent to this C code:
7759 @geindex gcc_jit_block_add_assignment_op (C function)
7760 @anchor{topics/functions gcc_jit_block_add_assignment_op}@anchor{2e}
7761 @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)
7763 Add evaluation of an rvalue, using the result to modify an
7766 This is analogous to "+=" and friends:
7780 gcc_jit_block_add_assignment_op (
7783 GCC_JIT_BINARY_OP_PLUS,
7784 gcc_jit_context_one (ctxt, int_type));
7790 @geindex gcc_jit_block_add_comment (C function)
7791 @anchor{topics/functions gcc_jit_block_add_comment}@anchor{3d}
7792 @deffn {C Function} void gcc_jit_block_add_comment (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, const char@w{ }*text)
7794 Add a no-op textual comment to the internal representation of the
7795 code. It will be optimized away, but will be visible in the dumps
7796 seen via @pxref{66,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE}
7797 and @pxref{1c,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE},
7798 and thus may be of use when debugging how your project's internal
7799 representation gets converted to the libgccjit IR.
7801 The parameter @code{text} must be non-NULL. It is copied, so the input
7802 buffer does not need to outlive the call. For example:
7806 snprintf (buf, sizeof (buf),
7808 pc, opcode_names[op->op_opcode]);
7809 gcc_jit_block_add_comment (block, loc, buf);
7815 @geindex gcc_jit_block_end_with_conditional (C function)
7816 @anchor{topics/functions gcc_jit_block_end_with_conditional}@anchor{2d}
7817 @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)
7819 Terminate a block by adding evaluation of an rvalue, branching on the
7820 result to the appropriate successor block.
7822 This is roughly equivalent to this C code:
7833 block, boolval, on_true, and on_false must be non-NULL.
7836 @geindex gcc_jit_block_end_with_jump (C function)
7837 @anchor{topics/functions gcc_jit_block_end_with_jump}@anchor{e3}
7838 @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)
7840 Terminate a block by adding a jump to the given target block.
7842 This is roughly equivalent to this C code:
7851 @geindex gcc_jit_block_end_with_return (C function)
7852 @anchor{topics/functions gcc_jit_block_end_with_return}@anchor{e4}
7853 @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)
7855 Terminate a block by adding evaluation of an rvalue, returning the value.
7857 This is roughly equivalent to this C code:
7866 @geindex gcc_jit_block_end_with_void_return (C function)
7867 @anchor{topics/functions gcc_jit_block_end_with_void_return}@anchor{e5}
7868 @deffn {C Function} void gcc_jit_block_end_with_void_return (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc)
7870 Terminate a block by adding a valueless return, for use within a function
7871 with "void" return type.
7873 This is equivalent to this C code:
7882 @geindex gcc_jit_block_end_with_switch (C function)
7883 @anchor{topics/functions gcc_jit_block_end_with_switch}@anchor{e6}
7884 @deffn {C Function} void gcc_jit_block_end_with_switch (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, gcc_jit_rvalue@w{ }*expr, gcc_jit_block@w{ }*default_block, int@w{ }num_cases, gcc_jit_case@w{ }**cases)
7886 Terminate a block by adding evalation of an rvalue, then performing
7889 This is roughly equivalent to this C code:
7897 case C0.min_value ... C0.max_value:
7900 case C1.min_value ... C1.max_value:
7905 case C[N - 1].min_value ... C[N - 1].max_value:
7906 goto C[N - 1].dest_block;
7912 @code{block}, @code{expr}, @code{default_block} and @code{cases} must all be
7915 @code{expr} must be of the same integer type as all of the @code{min_value}
7916 and @code{max_value} within the cases.
7918 @code{num_cases} must be >= 0.
7920 The ranges of the cases must not overlap (or have duplicate
7923 The API entrypoints relating to switch statements and cases:
7931 @pxref{e6,,gcc_jit_block_end_with_switch()}
7934 @pxref{e7,,gcc_jit_case_as_object()}
7937 @pxref{e8,,gcc_jit_context_new_case()}
7941 were added in @pxref{e9,,LIBGCCJIT_ABI_3}; you can test for their presence
7945 #ifdef LIBGCCJIT_HAVE_SWITCH_STATEMENTS
7950 @geindex gcc_jit_case (C type)
7951 @anchor{topics/functions gcc_jit_case}@anchor{ea}
7952 @deffn {C Type} gcc_jit_case
7955 A @cite{gcc_jit_case} represents a case within a switch statement, and
7956 is created within a particular @pxref{8,,gcc_jit_context} using
7957 @pxref{e8,,gcc_jit_context_new_case()}.
7959 Each case expresses a multivalued range of integer values. You
7960 can express single-valued cases by passing in the same value for
7961 both @cite{min_value} and @cite{max_value}.
7963 @geindex gcc_jit_context_new_case (C function)
7964 @anchor{topics/functions gcc_jit_context_new_case}@anchor{e8}
7965 @deffn {C Function} gcc_jit_case * gcc_jit_context_new_case (gcc_jit_context@w{ }*ctxt, gcc_jit_rvalue@w{ }*min_value, gcc_jit_rvalue@w{ }*max_value, gcc_jit_block@w{ }*dest_block)
7967 Create a new gcc_jit_case instance for use in a switch statement.
7968 @cite{min_value} and @cite{max_value} must be constants of an integer type,
7969 which must match that of the expression of the switch statement.
7971 @cite{dest_block} must be within the same function as the switch
7975 @geindex gcc_jit_case_as_object (C function)
7976 @anchor{topics/functions gcc_jit_case_as_object}@anchor{e7}
7977 @deffn {C Function} gcc_jit_object * gcc_jit_case_as_object (gcc_jit_case@w{ }*case_)
7979 Upcast from a case to an object.
7982 Here's an example of creating a switch statement:
7989 create_code (gcc_jit_context *ctxt, void *user_data)
7991 /* Let's try to inject the equivalent of:
8014 gcc_jit_type *t_int =
8015 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
8016 gcc_jit_type *return_type = t_int;
8018 gcc_jit_context_new_param (ctxt, NULL, t_int, "x");
8019 gcc_jit_param *params[1] = @{x@};
8020 gcc_jit_function *func =
8021 gcc_jit_context_new_function (ctxt, NULL,
8022 GCC_JIT_FUNCTION_EXPORTED,
8027 gcc_jit_block *b_initial =
8028 gcc_jit_function_new_block (func, "initial");
8030 gcc_jit_block *b_default =
8031 gcc_jit_function_new_block (func, "default");
8032 gcc_jit_block *b_case_0_5 =
8033 gcc_jit_function_new_block (func, "case_0_5");
8034 gcc_jit_block *b_case_25_27 =
8035 gcc_jit_function_new_block (func, "case_25_27");
8036 gcc_jit_block *b_case_m42_m17 =
8037 gcc_jit_function_new_block (func, "case_m42_m17");
8038 gcc_jit_block *b_case_40 =
8039 gcc_jit_function_new_block (func, "case_40");
8041 gcc_jit_case *cases[4] = @{
8042 gcc_jit_context_new_case (
8044 gcc_jit_context_new_rvalue_from_int (ctxt, t_int, 0),
8045 gcc_jit_context_new_rvalue_from_int (ctxt, t_int, 5),
8047 gcc_jit_context_new_case (
8049 gcc_jit_context_new_rvalue_from_int (ctxt, t_int, 25),
8050 gcc_jit_context_new_rvalue_from_int (ctxt, t_int, 27),
8052 gcc_jit_context_new_case (
8054 gcc_jit_context_new_rvalue_from_int (ctxt, t_int, -42),
8055 gcc_jit_context_new_rvalue_from_int (ctxt, t_int, -17),
8057 gcc_jit_context_new_case (
8059 gcc_jit_context_new_rvalue_from_int (ctxt, t_int, 40),
8060 gcc_jit_context_new_rvalue_from_int (ctxt, t_int, 40),
8063 gcc_jit_block_end_with_switch (
8065 gcc_jit_param_as_rvalue (x),
8069 gcc_jit_block_end_with_return (
8071 gcc_jit_context_new_rvalue_from_int (ctxt, t_int, 3));
8072 gcc_jit_block_end_with_return (
8074 gcc_jit_context_new_rvalue_from_int (ctxt, t_int, 4));
8075 gcc_jit_block_end_with_return (
8076 b_case_m42_m17, NULL,
8077 gcc_jit_context_new_rvalue_from_int (ctxt, t_int, 83));
8078 gcc_jit_block_end_with_return (
8080 gcc_jit_context_new_rvalue_from_int (ctxt, t_int, 8));
8081 gcc_jit_block_end_with_return (
8083 gcc_jit_context_new_rvalue_from_int (ctxt, t_int, 10));
8093 @c Copyright (C) 2017-2019 Free Software Foundation, Inc.
8094 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
8096 @c This is free software: you can redistribute it and/or modify it
8097 @c under the terms of the GNU General Public License as published by
8098 @c the Free Software Foundation, either version 3 of the License, or
8099 @c (at your option) any later version.
8101 @c This program is distributed in the hope that it will be useful, but
8102 @c WITHOUT ANY WARRANTY; without even the implied warranty of
8103 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
8104 @c General Public License for more details.
8106 @c You should have received a copy of the GNU General Public License
8107 @c along with this program. If not, see
8108 @c <http://www.gnu.org/licenses/>.
8110 @node Function pointers<2>,Source Locations,Creating and using functions,Topic Reference
8111 @anchor{topics/function-pointers doc}@anchor{eb}@anchor{topics/function-pointers function-pointers}@anchor{ec}
8112 @section Function pointers
8115 You can generate calls that use a function pointer via
8116 @pxref{b8,,gcc_jit_context_new_call_through_ptr()}.
8118 To do requires a @pxref{13,,gcc_jit_rvalue} of the correct function pointer type.
8120 Function pointers for a @pxref{29,,gcc_jit_function} can be obtained
8121 via @pxref{bc,,gcc_jit_function_get_address()}.
8123 @geindex gcc_jit_function_get_address (C function)
8124 @anchor{topics/function-pointers gcc_jit_function_get_address}@anchor{bc}
8125 @deffn {C Function} gcc_jit_rvalue * gcc_jit_function_get_address (gcc_jit_function@w{ }*fn, gcc_jit_location@w{ }*loc)
8127 Get the address of a function as an rvalue, of function pointer
8130 This entrypoint was added in @pxref{ed,,LIBGCCJIT_ABI_9}; you can test
8131 for its presence using
8134 #ifdef LIBGCCJIT_HAVE_gcc_jit_function_get_address
8140 Alternatively, given an existing function, you can obtain a pointer
8141 to it in @pxref{13,,gcc_jit_rvalue} form using
8142 @pxref{98,,gcc_jit_context_new_rvalue_from_ptr()}, using a function pointer
8143 type obtained using @pxref{91,,gcc_jit_context_new_function_ptr_type()}.
8145 Here's an example of creating a function pointer type corresponding to C's
8146 @code{void (*) (int, int, int)}:
8149 gcc_jit_type *void_type =
8150 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_VOID);
8151 gcc_jit_type *int_type =
8152 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
8154 /* Build the function ptr type. */
8155 gcc_jit_type *param_types[3];
8156 param_types[0] = int_type;
8157 param_types[1] = int_type;
8158 param_types[2] = int_type;
8160 gcc_jit_type *fn_ptr_type =
8161 gcc_jit_context_new_function_ptr_type (ctxt, NULL,
8168 @geindex gcc_jit_context_new_function_ptr_type (C function)
8169 @anchor{topics/function-pointers gcc_jit_context_new_function_ptr_type}@anchor{91}
8170 @deffn {C Function} gcc_jit_type * gcc_jit_context_new_function_ptr_type (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, gcc_jit_type@w{ }*return_type, int@w{ }num_params, gcc_jit_type@w{ }**param_types, int@w{ }is_variadic)
8172 Generate a @pxref{a,,gcc_jit_type} for a function pointer with the
8173 given return type and parameters.
8176 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
8177 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
8179 @c This is free software: you can redistribute it and/or modify it
8180 @c under the terms of the GNU General Public License as published by
8181 @c the Free Software Foundation, either version 3 of the License, or
8182 @c (at your option) any later version.
8184 @c This program is distributed in the hope that it will be useful, but
8185 @c WITHOUT ANY WARRANTY; without even the implied warranty of
8186 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
8187 @c General Public License for more details.
8189 @c You should have received a copy of the GNU General Public License
8190 @c along with this program. If not, see
8191 @c <http://www.gnu.org/licenses/>.
8193 @node Source Locations,Compiling a context,Function pointers<2>,Topic Reference
8194 @anchor{topics/locations source-locations}@anchor{ee}@anchor{topics/locations doc}@anchor{ef}
8195 @section Source Locations
8198 @geindex gcc_jit_location (C type)
8199 @anchor{topics/locations gcc_jit_location}@anchor{3b}
8200 @deffn {C Type} gcc_jit_location
8202 A @cite{gcc_jit_location} encapsulates a source code location, so that
8203 you can (optionally) associate locations in your language with
8204 statements in the JIT-compiled code, allowing the debugger to
8205 single-step through your language.
8207 @cite{gcc_jit_location} instances are optional: you can always pass NULL to
8208 any API entrypoint accepting one.
8210 You can construct them using @pxref{41,,gcc_jit_context_new_location()}.
8212 You need to enable @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} on the
8213 @pxref{8,,gcc_jit_context} for these locations to actually be usable by
8217 gcc_jit_context_set_bool_option (
8219 GCC_JIT_BOOL_OPTION_DEBUGINFO,
8226 @geindex gcc_jit_context_new_location (C function)
8227 @anchor{topics/locations gcc_jit_context_new_location}@anchor{41}
8228 @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)
8230 Create a @cite{gcc_jit_location} instance representing the given source
8233 The parameter @code{filename} must be non-NULL. The call takes a copy of
8234 the underlying string, so it is valid to pass in a pointer to an
8243 @node Faking it,,,Source Locations
8244 @anchor{topics/locations faking-it}@anchor{f0}
8245 @subsection Faking it
8248 If you don't have source code for your internal representation, but need
8249 to debug, you can generate a C-like representation of the functions in
8250 your context using @pxref{5a,,gcc_jit_context_dump_to_file()}:
8253 gcc_jit_context_dump_to_file (ctxt, "/tmp/something.c",
8254 1 /* update_locations */);
8259 This will dump C-like code to the given path. If the @cite{update_locations}
8260 argument is true, this will also set up @cite{gcc_jit_location} information
8261 throughout the context, pointing at the dump file as if it were a source
8262 file, giving you @emph{something} you can step through in the debugger.
8264 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
8265 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
8267 @c This is free software: you can redistribute it and/or modify it
8268 @c under the terms of the GNU General Public License as published by
8269 @c the Free Software Foundation, either version 3 of the License, or
8270 @c (at your option) any later version.
8272 @c This program is distributed in the hope that it will be useful, but
8273 @c WITHOUT ANY WARRANTY; without even the implied warranty of
8274 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
8275 @c General Public License for more details.
8277 @c You should have received a copy of the GNU General Public License
8278 @c along with this program. If not, see
8279 @c <http://www.gnu.org/licenses/>.
8281 @node Compiling a context,ABI and API compatibility,Source Locations,Topic Reference
8282 @anchor{topics/compilation compiling-a-context}@anchor{f1}@anchor{topics/compilation doc}@anchor{f2}
8283 @section Compiling a context
8286 Once populated, a @pxref{8,,gcc_jit_context *} can be compiled to
8287 machine code, either in-memory via @pxref{15,,gcc_jit_context_compile()} or
8288 to disk via @pxref{4a,,gcc_jit_context_compile_to_file()}.
8290 You can compile a context multiple times (using either form of
8291 compilation), although any errors that occur on the context will
8292 prevent any future compilation of that context.
8295 * In-memory compilation::
8296 * Ahead-of-time compilation::
8300 @node In-memory compilation,Ahead-of-time compilation,,Compiling a context
8301 @anchor{topics/compilation in-memory-compilation}@anchor{f3}
8302 @subsection In-memory compilation
8305 @geindex gcc_jit_context_compile (C function)
8306 @anchor{topics/compilation gcc_jit_context_compile}@anchor{15}
8307 @deffn {C Function} gcc_jit_result * gcc_jit_context_compile (gcc_jit_context@w{ }*ctxt)
8309 This calls into GCC and builds the code, returning a
8310 @cite{gcc_jit_result *}.
8312 If the result is non-NULL, the caller becomes responsible for
8313 calling @pxref{39,,gcc_jit_result_release()} on it once they're done
8317 @geindex gcc_jit_result (C type)
8318 @anchor{topics/compilation gcc_jit_result}@anchor{16}
8319 @deffn {C Type} gcc_jit_result
8321 A @cite{gcc_jit_result} encapsulates the result of compiling a context
8322 in-memory, and the lifetimes of any machine code functions or globals
8323 that are within the result.
8326 @geindex gcc_jit_result_get_code (C function)
8327 @anchor{topics/compilation gcc_jit_result_get_code}@anchor{17}
8328 @deffn {C Function} void * gcc_jit_result_get_code (gcc_jit_result@w{ }*result, const char@w{ }*funcname)
8330 Locate a given function within the built machine code.
8332 Functions are looked up by name. For this to succeed, a function
8333 with a name matching @cite{funcname} must have been created on
8334 @cite{result}'s context (or a parent context) via a call to
8335 @pxref{11,,gcc_jit_context_new_function()} with @cite{kind}
8336 @pxref{d7,,GCC_JIT_FUNCTION_EXPORTED}:
8339 gcc_jit_context_new_function (ctxt,
8340 any_location, /* or NULL */
8341 /* Required for func to be visible to
8342 gcc_jit_result_get_code: */
8343 GCC_JIT_FUNCTION_EXPORTED,
8345 /* Must string-compare equal: */
8352 If such a function is not found (or @cite{result} or @cite{funcname} are
8353 @code{NULL}), an error message will be emitted on stderr and
8354 @code{NULL} will be returned.
8356 If the function is found, the result will need to be cast to a
8357 function pointer of the correct type before it can be called.
8359 Note that the resulting machine code becomes invalid after
8360 @pxref{39,,gcc_jit_result_release()} is called on the
8361 @pxref{16,,gcc_jit_result *}; attempting to call it after that may lead
8362 to a segmentation fault.
8365 @geindex gcc_jit_result_get_global (C function)
8366 @anchor{topics/compilation gcc_jit_result_get_global}@anchor{c7}
8367 @deffn {C Function} void * gcc_jit_result_get_global (gcc_jit_result@w{ }*result, const char@w{ }*name)
8369 Locate a given global within the built machine code.
8371 Globals are looked up by name. For this to succeed, a global
8372 with a name matching @cite{name} must have been created on
8373 @cite{result}'s context (or a parent context) via a call to
8374 @pxref{c4,,gcc_jit_context_new_global()} with @cite{kind}
8375 @pxref{c6,,GCC_JIT_GLOBAL_EXPORTED}.
8377 If the global is found, the result will need to be cast to a
8378 pointer of the correct type before it can be called.
8380 This is a @emph{pointer} to the global, so e.g. for an @code{int} this is
8383 For example, given an @code{int foo;} created this way:
8386 gcc_jit_lvalue *exported_global =
8387 gcc_jit_context_new_global (ctxt,
8388 any_location, /* or NULL */
8389 GCC_JIT_GLOBAL_EXPORTED,
8396 we can access it like this:
8400 (int *)gcc_jit_result_get_global (result, "foo");
8405 If such a global is not found (or @cite{result} or @cite{name} are
8406 @code{NULL}), an error message will be emitted on stderr and
8407 @code{NULL} will be returned.
8409 Note that the resulting address becomes invalid after
8410 @pxref{39,,gcc_jit_result_release()} is called on the
8411 @pxref{16,,gcc_jit_result *}; attempting to use it after that may lead
8412 to a segmentation fault.
8415 @geindex gcc_jit_result_release (C function)
8416 @anchor{topics/compilation gcc_jit_result_release}@anchor{39}
8417 @deffn {C Function} void gcc_jit_result_release (gcc_jit_result@w{ }*result)
8419 Once we're done with the code, this unloads the built .so file.
8420 This cleans up the result; after calling this, it's no longer
8421 valid to use the result, or any code or globals that were obtained
8422 by calling @pxref{17,,gcc_jit_result_get_code()} or
8423 @pxref{c7,,gcc_jit_result_get_global()} on it.
8426 @node Ahead-of-time compilation,,In-memory compilation,Compiling a context
8427 @anchor{topics/compilation ahead-of-time-compilation}@anchor{f4}
8428 @subsection Ahead-of-time compilation
8431 Although libgccjit is primarily aimed at just-in-time compilation, it
8432 can also be used for implementing more traditional ahead-of-time
8433 compilers, via the @pxref{4a,,gcc_jit_context_compile_to_file()}
8436 @geindex gcc_jit_context_compile_to_file (C function)
8437 @anchor{topics/compilation gcc_jit_context_compile_to_file}@anchor{4a}
8438 @deffn {C Function} void gcc_jit_context_compile_to_file (gcc_jit_context@w{ }*ctxt, enum gcc_jit_output_kind@w{ }output_kind, const char@w{ }*output_path)
8440 Compile the @pxref{8,,gcc_jit_context *} to a file of the given
8444 @pxref{4a,,gcc_jit_context_compile_to_file()} ignores the suffix of
8445 @code{output_path}, and insteads uses the given
8446 @code{enum gcc_jit_output_kind} to decide what to do.
8450 This is different from the @code{gcc} program, which does make use of the
8451 suffix of the output file when determining what to do.
8455 @geindex gcc_jit_output_kind (C type)
8456 @anchor{topics/compilation gcc_jit_output_kind}@anchor{f5}
8457 @deffn {C Type} enum gcc_jit_output_kind
8460 The available kinds of output are:
8463 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx}
8474 @pxref{f6,,GCC_JIT_OUTPUT_KIND_ASSEMBLER}
8482 @pxref{f7,,GCC_JIT_OUTPUT_KIND_OBJECT_FILE}
8490 @pxref{f8,,GCC_JIT_OUTPUT_KIND_DYNAMIC_LIBRARY}
8498 @pxref{f9,,GCC_JIT_OUTPUT_KIND_EXECUTABLE}
8507 @geindex GCC_JIT_OUTPUT_KIND_ASSEMBLER (C macro)
8508 @anchor{topics/compilation GCC_JIT_OUTPUT_KIND_ASSEMBLER}@anchor{f6}
8509 @deffn {C Macro} GCC_JIT_OUTPUT_KIND_ASSEMBLER
8511 Compile the context to an assembler file.
8514 @geindex GCC_JIT_OUTPUT_KIND_OBJECT_FILE (C macro)
8515 @anchor{topics/compilation GCC_JIT_OUTPUT_KIND_OBJECT_FILE}@anchor{f7}
8516 @deffn {C Macro} GCC_JIT_OUTPUT_KIND_OBJECT_FILE
8518 Compile the context to an object file.
8521 @geindex GCC_JIT_OUTPUT_KIND_DYNAMIC_LIBRARY (C macro)
8522 @anchor{topics/compilation GCC_JIT_OUTPUT_KIND_DYNAMIC_LIBRARY}@anchor{f8}
8523 @deffn {C Macro} GCC_JIT_OUTPUT_KIND_DYNAMIC_LIBRARY
8525 Compile the context to a dynamic library.
8527 There is currently no support for specifying other libraries to link
8531 @geindex GCC_JIT_OUTPUT_KIND_EXECUTABLE (C macro)
8532 @anchor{topics/compilation GCC_JIT_OUTPUT_KIND_EXECUTABLE}@anchor{f9}
8533 @deffn {C Macro} GCC_JIT_OUTPUT_KIND_EXECUTABLE
8535 Compile the context to an executable.
8537 There is currently no support for specifying libraries to link
8541 @c Copyright (C) 2015-2019 Free Software Foundation, Inc.
8542 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
8544 @c This is free software: you can redistribute it and/or modify it
8545 @c under the terms of the GNU General Public License as published by
8546 @c the Free Software Foundation, either version 3 of the License, or
8547 @c (at your option) any later version.
8549 @c This program is distributed in the hope that it will be useful, but
8550 @c WITHOUT ANY WARRANTY; without even the implied warranty of
8551 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
8552 @c General Public License for more details.
8554 @c You should have received a copy of the GNU General Public License
8555 @c along with this program. If not, see
8556 @c <http://www.gnu.org/licenses/>.
8558 @node ABI and API compatibility,Performance,Compiling a context,Topic Reference
8559 @anchor{topics/compatibility abi-and-api-compatibility}@anchor{fa}@anchor{topics/compatibility doc}@anchor{fb}
8560 @section ABI and API compatibility
8563 The libgccjit developers strive for ABI and API backward-compatibility:
8564 programs built against libgccjit.so stand a good chance of running
8565 without recompilation against newer versions of libgccjit.so, and
8566 ought to recompile without modification against newer versions of
8571 The libgccjit++.h C++ API is more experimental, and less
8572 locked-down at this time.
8576 API compatibility is achieved by extending the API rather than changing
8577 it. For ABI compatiblity, we avoid bumping the SONAME, and instead use
8578 symbol versioning to tag each symbol, so that a binary linked against
8579 libgccjit.so is tagged according to the symbols that it uses.
8581 For example, @pxref{72,,gcc_jit_context_add_command_line_option()} was added in
8582 @code{LIBGCCJIT_ABI_1}. If a client program uses it, this can be detected
8583 from metadata by using @code{objdump}:
8586 $ objdump -p testsuite/jit/test-extra-options.c.exe | tail -n 8
8589 required from libgccjit.so.0:
8590 0x00824161 0x00 04 LIBGCCJIT_ABI_1
8591 0x00824160 0x00 03 LIBGCCJIT_ABI_0
8592 required from libc.so.6:
8597 You can see the symbol tags provided by libgccjit.so using @code{objdump}:
8600 $ objdump -p libgccjit.so | less
8602 Version definitions:
8603 1 0x01 0x0ff81f20 libgccjit.so.0
8604 2 0x00 0x00824160 LIBGCCJIT_ABI_0
8605 3 0x00 0x00824161 LIBGCCJIT_ABI_1
8627 * LIBGCCJIT_ABI_10::
8632 @node ABI symbol tags,,,ABI and API compatibility
8633 @anchor{topics/compatibility abi-symbol-tags}@anchor{fc}
8634 @subsection ABI symbol tags
8637 The initial release of libgccjit (in gcc 5.1) did not use symbol versioning.
8639 Newer releases use the following tags.
8652 * LIBGCCJIT_ABI_10::
8656 @node LIBGCCJIT_ABI_0,LIBGCCJIT_ABI_1,,ABI symbol tags
8657 @anchor{topics/compatibility libgccjit-abi-0}@anchor{fd}@anchor{topics/compatibility id1}@anchor{fe}
8658 @subsubsection @code{LIBGCCJIT_ABI_0}
8661 All entrypoints in the initial release of libgccjit are tagged with
8662 @code{LIBGCCJIT_ABI_0}, to signify the transition to symbol versioning.
8664 Binaries built against older copies of @code{libgccjit.so} should
8665 continue to work, with this being handled transparently by the linker
8666 (see this post@footnote{https://gcc.gnu.org/ml/gcc-patches/2015-06/msg02126.html})
8668 @node LIBGCCJIT_ABI_1,LIBGCCJIT_ABI_2,LIBGCCJIT_ABI_0,ABI symbol tags
8669 @anchor{topics/compatibility libgccjit-abi-1}@anchor{73}@anchor{topics/compatibility id2}@anchor{ff}
8670 @subsubsection @code{LIBGCCJIT_ABI_1}
8673 @code{LIBGCCJIT_ABI_1} covers the addition of
8674 @pxref{72,,gcc_jit_context_add_command_line_option()}
8676 @node LIBGCCJIT_ABI_2,LIBGCCJIT_ABI_3,LIBGCCJIT_ABI_1,ABI symbol tags
8677 @anchor{topics/compatibility libgccjit-abi-2}@anchor{6c}@anchor{topics/compatibility id3}@anchor{100}
8678 @subsubsection @code{LIBGCCJIT_ABI_2}
8681 @code{LIBGCCJIT_ABI_2} covers the addition of
8682 @pxref{6b,,gcc_jit_context_set_bool_allow_unreachable_blocks()}
8684 @node LIBGCCJIT_ABI_3,LIBGCCJIT_ABI_4,LIBGCCJIT_ABI_2,ABI symbol tags
8685 @anchor{topics/compatibility libgccjit-abi-3}@anchor{e9}@anchor{topics/compatibility id4}@anchor{101}
8686 @subsubsection @code{LIBGCCJIT_ABI_3}
8689 @code{LIBGCCJIT_ABI_3} covers the addition of switch statements via API
8698 @pxref{e6,,gcc_jit_block_end_with_switch()}
8701 @pxref{e7,,gcc_jit_case_as_object()}
8704 @pxref{e8,,gcc_jit_context_new_case()}
8708 @node LIBGCCJIT_ABI_4,LIBGCCJIT_ABI_5,LIBGCCJIT_ABI_3,ABI symbol tags
8709 @anchor{topics/compatibility id5}@anchor{102}@anchor{topics/compatibility libgccjit-abi-4}@anchor{103}
8710 @subsubsection @code{LIBGCCJIT_ABI_4}
8713 @code{LIBGCCJIT_ABI_4} covers the addition of timers via API
8722 @pxref{104,,gcc_jit_context_get_timer()}
8725 @pxref{105,,gcc_jit_context_set_timer()}
8728 @pxref{106,,gcc_jit_timer_new()}
8731 @pxref{107,,gcc_jit_timer_release()}
8734 @pxref{108,,gcc_jit_timer_push()}
8737 @pxref{109,,gcc_jit_timer_pop()}
8740 @pxref{10a,,gcc_jit_timer_print()}
8744 @node LIBGCCJIT_ABI_5,LIBGCCJIT_ABI_6,LIBGCCJIT_ABI_4,ABI symbol tags
8745 @anchor{topics/compatibility id6}@anchor{10b}@anchor{topics/compatibility libgccjit-abi-5}@anchor{6e}
8746 @subsubsection @code{LIBGCCJIT_ABI_5}
8749 @code{LIBGCCJIT_ABI_5} covers the addition of
8750 @pxref{6d,,gcc_jit_context_set_bool_use_external_driver()}
8752 @node LIBGCCJIT_ABI_6,LIBGCCJIT_ABI_7,LIBGCCJIT_ABI_5,ABI symbol tags
8753 @anchor{topics/compatibility id7}@anchor{10c}@anchor{topics/compatibility libgccjit-abi-6}@anchor{ba}
8754 @subsubsection @code{LIBGCCJIT_ABI_6}
8757 @code{LIBGCCJIT_ABI_6} covers the addition of
8758 @pxref{b9,,gcc_jit_rvalue_set_bool_require_tail_call()}
8760 @node LIBGCCJIT_ABI_7,LIBGCCJIT_ABI_8,LIBGCCJIT_ABI_6,ABI symbol tags
8761 @anchor{topics/compatibility libgccjit-abi-7}@anchor{81}@anchor{topics/compatibility id8}@anchor{10d}
8762 @subsubsection @code{LIBGCCJIT_ABI_7}
8765 @code{LIBGCCJIT_ABI_7} covers the addition of
8766 @pxref{80,,gcc_jit_type_get_aligned()}
8768 @node LIBGCCJIT_ABI_8,LIBGCCJIT_ABI_9,LIBGCCJIT_ABI_7,ABI symbol tags
8769 @anchor{topics/compatibility libgccjit-abi-8}@anchor{84}@anchor{topics/compatibility id9}@anchor{10e}
8770 @subsubsection @code{LIBGCCJIT_ABI_8}
8773 @code{LIBGCCJIT_ABI_8} covers the addition of
8774 @pxref{83,,gcc_jit_type_get_vector()}
8776 @node LIBGCCJIT_ABI_9,LIBGCCJIT_ABI_10,LIBGCCJIT_ABI_8,ABI symbol tags
8777 @anchor{topics/compatibility id10}@anchor{10f}@anchor{topics/compatibility libgccjit-abi-9}@anchor{ed}
8778 @subsubsection @code{LIBGCCJIT_ABI_9}
8781 @code{LIBGCCJIT_ABI_9} covers the addition of
8782 @pxref{bc,,gcc_jit_function_get_address()}
8784 @node LIBGCCJIT_ABI_10,,LIBGCCJIT_ABI_9,ABI symbol tags
8785 @anchor{topics/compatibility id11}@anchor{110}@anchor{topics/compatibility libgccjit-abi-10}@anchor{9c}
8786 @subsubsection @code{LIBGCCJIT_ABI_10}
8789 @code{LIBGCCJIT_ABI_10} covers the addition of
8790 @pxref{85,,gcc_jit_context_new_rvalue_from_vector()}
8792 @c Copyright (C) 2015-2019 Free Software Foundation, Inc.
8793 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
8795 @c This is free software: you can redistribute it and/or modify it
8796 @c under the terms of the GNU General Public License as published by
8797 @c the Free Software Foundation, either version 3 of the License, or
8798 @c (at your option) any later version.
8800 @c This program is distributed in the hope that it will be useful, but
8801 @c WITHOUT ANY WARRANTY; without even the implied warranty of
8802 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
8803 @c General Public License for more details.
8805 @c You should have received a copy of the GNU General Public License
8806 @c along with this program. If not, see
8807 @c <http://www.gnu.org/licenses/>.
8809 @node Performance,,ABI and API compatibility,Topic Reference
8810 @anchor{topics/performance performance}@anchor{111}@anchor{topics/performance doc}@anchor{112}
8811 @section Performance
8819 @node The timing API,,,Performance
8820 @anchor{topics/performance the-timing-api}@anchor{113}
8821 @subsection The timing API
8824 As of GCC 6, libgccjit exposes a timing API, for printing reports on
8825 how long was spent in different parts of code.
8827 You can create a @pxref{114,,gcc_jit_timer} instance, which will
8828 measure time spent since its creation. The timer maintains a stack
8829 of "timer items": as control flow moves through your code, you can push
8830 and pop named items relating to your code onto the stack, and the timer
8831 will account the time spent accordingly.
8833 You can also asssociate a timer with a @pxref{8,,gcc_jit_context}, in
8834 which case the time spent inside compilation will be subdivided.
8836 For example, the following code uses a timer, recording client items
8837 "create_code", "compile", and "running code":
8840 /* Create a timer. */
8841 gcc_jit_timer *timer = gcc_jit_timer_new ();
8844 error ("gcc_jit_timer_new failed");
8848 /* Let's repeatedly compile and run some code, accumulating it
8849 all into the timer. */
8850 for (int i = 0; i < num_iterations; i++)
8852 /* Create a context and associate it with the timer. */
8853 gcc_jit_context *ctxt = gcc_jit_context_acquire ();
8856 error ("gcc_jit_context_acquire failed");
8859 gcc_jit_context_set_timer (ctxt, timer);
8861 /* Populate the context, timing it as client item "create_code". */
8862 gcc_jit_timer_push (timer, "create_code");
8864 gcc_jit_timer_pop (timer, "create_code");
8866 /* Compile the context, timing it as client item "compile". */
8867 gcc_jit_timer_push (timer, "compile");
8868 result = gcc_jit_context_compile (ctxt);
8869 gcc_jit_timer_pop (timer, "compile");
8871 /* Run the generated code, timing it as client item "running code". */
8872 gcc_jit_timer_push (timer, "running code");
8873 run_the_code (ctxt, result);
8874 gcc_jit_timer_pop (timer, "running code");
8877 gcc_jit_context_release (ctxt);
8878 gcc_jit_result_release (result);
8881 /* Print the accumulated timings. */
8882 gcc_jit_timer_print (timer, stderr);
8883 gcc_jit_timer_release (timer);
8888 giving output like this, showing the internal GCC items at the top, then
8889 client items, then the total:
8892 Execution times (seconds)
8894 phase setup : 0.29 (14%) usr 0.00 ( 0%) sys 0.32 ( 5%) wall 10661 kB (50%) ggc
8895 phase parsing : 0.02 ( 1%) usr 0.00 ( 0%) sys 0.00 ( 0%) wall 653 kB ( 3%) ggc
8896 phase finalize : 0.01 ( 1%) usr 0.00 ( 0%) sys 0.00 ( 0%) wall 0 kB ( 0%) ggc
8897 dump files : 0.02 ( 1%) usr 0.00 ( 0%) sys 0.01 ( 0%) wall 0 kB ( 0%) ggc
8898 callgraph construction : 0.02 ( 1%) usr 0.01 ( 6%) sys 0.01 ( 0%) wall 242 kB ( 1%) ggc
8899 callgraph optimization : 0.03 ( 2%) usr 0.00 ( 0%) sys 0.02 ( 0%) wall 142 kB ( 1%) ggc
8900 trivially dead code : 0.01 ( 1%) usr 0.00 ( 0%) sys 0.00 ( 0%) wall 0 kB ( 0%) ggc
8901 df scan insns : 0.01 ( 1%) usr 0.00 ( 0%) sys 0.00 ( 0%) wall 9 kB ( 0%) ggc
8902 df live regs : 0.01 ( 1%) usr 0.00 ( 0%) sys 0.01 ( 0%) wall 0 kB ( 0%) ggc
8903 inline parameters : 0.02 ( 1%) usr 0.00 ( 0%) sys 0.01 ( 0%) wall 82 kB ( 0%) ggc
8904 tree CFG cleanup : 0.01 ( 1%) usr 0.00 ( 0%) sys 0.00 ( 0%) wall 0 kB ( 0%) ggc
8905 tree PHI insertion : 0.01 ( 1%) usr 0.00 ( 0%) sys 0.02 ( 0%) wall 64 kB ( 0%) ggc
8906 tree SSA other : 0.01 ( 1%) usr 0.00 ( 0%) sys 0.01 ( 0%) wall 18 kB ( 0%) ggc
8907 expand : 0.01 ( 1%) usr 0.00 ( 0%) sys 0.00 ( 0%) wall 398 kB ( 2%) ggc
8908 jump : 0.01 ( 1%) usr 0.00 ( 0%) sys 0.00 ( 0%) wall 0 kB ( 0%) ggc
8909 loop init : 0.01 ( 0%) usr 0.00 ( 0%) sys 0.00 ( 0%) wall 67 kB ( 0%) ggc
8910 integrated RA : 0.02 ( 1%) usr 0.00 ( 0%) sys 0.00 ( 0%) wall 2468 kB (12%) ggc
8911 thread pro- & epilogue : 0.01 ( 1%) usr 0.00 ( 0%) sys 0.00 ( 0%) wall 162 kB ( 1%) ggc
8912 final : 0.01 ( 1%) usr 0.00 ( 0%) sys 0.00 ( 0%) wall 216 kB ( 1%) ggc
8913 rest of compilation : 1.37 (69%) usr 0.00 ( 0%) sys 1.13 (18%) wall 1391 kB ( 6%) ggc
8914 assemble JIT code : 0.01 ( 1%) usr 0.00 ( 0%) sys 4.04 (66%) wall 0 kB ( 0%) ggc
8915 load JIT result : 0.02 ( 1%) usr 0.00 ( 0%) sys 0.00 ( 0%) wall 0 kB ( 0%) ggc
8916 JIT client code : 0.00 ( 0%) usr 0.01 ( 6%) sys 0.00 ( 0%) wall 0 kB ( 0%) ggc
8918 create_code : 0.00 ( 0%) usr 0.01 ( 6%) sys 0.00 ( 0%) wall 0 kB ( 0%) ggc
8919 compile : 0.36 (18%) usr 0.15 (83%) sys 0.86 (14%) wall 14939 kB (70%) ggc
8920 running code : 0.00 ( 0%) usr 0.00 ( 0%) sys 0.00 ( 0%) wall 0 kB ( 0%) ggc
8921 TOTAL : 2.00 0.18 6.12 21444 kB
8926 The exact format is intended to be human-readable, and is subject to change.
8928 @geindex LIBGCCJIT_HAVE_TIMING_API (C macro)
8929 @anchor{topics/performance LIBGCCJIT_HAVE_TIMING_API}@anchor{115}
8930 @deffn {C Macro} LIBGCCJIT_HAVE_TIMING_API
8932 The timer API was added to libgccjit in GCC 6.
8933 This macro is only defined in versions of libgccjit.h which have the
8934 timer API, and so can be used to guard code that may need to compile
8935 against earlier releases:
8938 #ifdef LIBGCCJIT_HAVE_TIMING_API
8939 gcc_jit_timer *t = gcc_jit_timer_new ();
8940 gcc_jit_context_set_timer (ctxt, t);
8947 @geindex gcc_jit_timer (C type)
8948 @anchor{topics/performance gcc_jit_timer}@anchor{114}
8949 @deffn {C Type} gcc_jit_timer
8952 @geindex gcc_jit_timer_new (C function)
8953 @anchor{topics/performance gcc_jit_timer_new}@anchor{106}
8954 @deffn {C Function} gcc_jit_timer * gcc_jit_timer_new (void)
8956 Create a @pxref{114,,gcc_jit_timer} instance, and start timing:
8959 gcc_jit_timer *t = gcc_jit_timer_new ();
8964 This API entrypoint was added in @pxref{103,,LIBGCCJIT_ABI_4}; you can test
8965 for its presence using
8968 #ifdef LIBGCCJIT_HAVE_TIMING_API
8974 @geindex gcc_jit_timer_release (C function)
8975 @anchor{topics/performance gcc_jit_timer_release}@anchor{107}
8976 @deffn {C Function} void gcc_jit_timer_release (gcc_jit_timer@w{ }*timer)
8978 Release a @pxref{114,,gcc_jit_timer} instance:
8981 gcc_jit_timer_release (t);
8986 This should be called exactly once on a timer.
8988 This API entrypoint was added in @pxref{103,,LIBGCCJIT_ABI_4}; you can test
8989 for its presence using
8992 #ifdef LIBGCCJIT_HAVE_TIMING_API
8998 @geindex gcc_jit_context_set_timer (C function)
8999 @anchor{topics/performance gcc_jit_context_set_timer}@anchor{105}
9000 @deffn {C Function} void gcc_jit_context_set_timer (gcc_jit_context@w{ }*ctxt, gcc_jit_timer@w{ }*timer)
9002 Associate a @pxref{114,,gcc_jit_timer} instance with a context:
9005 gcc_jit_context_set_timer (ctxt, t);
9010 A timer instance can be shared between multiple
9011 @pxref{8,,gcc_jit_context} instances.
9013 Timers have no locking, so if you have a multithreaded program, you
9014 must provide your own locks if more than one thread could be working
9015 with the same timer via timer-associated contexts.
9017 This API entrypoint was added in @pxref{103,,LIBGCCJIT_ABI_4}; you can test
9018 for its presence using
9021 #ifdef LIBGCCJIT_HAVE_TIMING_API
9027 @geindex gcc_jit_context_get_timer (C function)
9028 @anchor{topics/performance gcc_jit_context_get_timer}@anchor{104}
9029 @deffn {C Function} gcc_jit_timer *gcc_jit_context_get_timer (gcc_jit_context@w{ }*ctxt)
9031 Get the timer associated with a context (if any).
9033 This API entrypoint was added in @pxref{103,,LIBGCCJIT_ABI_4}; you can test
9034 for its presence using
9037 #ifdef LIBGCCJIT_HAVE_TIMING_API
9043 @geindex gcc_jit_timer_push (C function)
9044 @anchor{topics/performance gcc_jit_timer_push}@anchor{108}
9045 @deffn {C Function} void gcc_jit_timer_push (gcc_jit_timer@w{ }*timer, const char@w{ }*item_name)
9047 Push the given item onto the timer's stack:
9050 gcc_jit_timer_push (t, "running code");
9051 run_the_code (ctxt, result);
9052 gcc_jit_timer_pop (t, "running code");
9057 This API entrypoint was added in @pxref{103,,LIBGCCJIT_ABI_4}; you can test
9058 for its presence using
9061 #ifdef LIBGCCJIT_HAVE_TIMING_API
9067 @geindex gcc_jit_timer_pop (C function)
9068 @anchor{topics/performance gcc_jit_timer_pop}@anchor{109}
9069 @deffn {C Function} void gcc_jit_timer_pop (gcc_jit_timer@w{ }*timer, const char@w{ }*item_name)
9071 Pop the top item from the timer's stack.
9073 If "item_name" is provided, it must match that of the top item.
9074 Alternatively, @code{NULL} can be passed in, to suppress checking.
9076 This API entrypoint was added in @pxref{103,,LIBGCCJIT_ABI_4}; you can test
9077 for its presence using
9080 #ifdef LIBGCCJIT_HAVE_TIMING_API
9086 @geindex gcc_jit_timer_print (C function)
9087 @anchor{topics/performance gcc_jit_timer_print}@anchor{10a}
9088 @deffn {C Function} void gcc_jit_timer_print (gcc_jit_timer@w{ }*timer, FILE@w{ }*f_out)
9090 Print timing information to the given stream about activity since
9091 the timer was started.
9093 This API entrypoint was added in @pxref{103,,LIBGCCJIT_ABI_4}; you can test
9094 for its presence using
9097 #ifdef LIBGCCJIT_HAVE_TIMING_API
9103 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
9104 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
9106 @c This is free software: you can redistribute it and/or modify it
9107 @c under the terms of the GNU General Public License as published by
9108 @c the Free Software Foundation, either version 3 of the License, or
9109 @c (at your option) any later version.
9111 @c This program is distributed in the hope that it will be useful, but
9112 @c WITHOUT ANY WARRANTY; without even the implied warranty of
9113 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
9114 @c General Public License for more details.
9116 @c You should have received a copy of the GNU General Public License
9117 @c along with this program. If not, see
9118 @c <http://www.gnu.org/licenses/>.
9120 @node C++ bindings for libgccjit,Internals,Topic Reference,Top
9121 @anchor{cp/index c-bindings-for-libgccjit}@anchor{116}@anchor{cp/index doc}@anchor{117}
9122 @chapter C++ bindings for libgccjit
9125 This document describes the C++ bindings to
9126 libgccjit@footnote{http://gcc.gnu.org/wiki/JIT}, an API for embedding GCC
9127 inside programs and libraries.
9129 The C++ bindings consist of a single header file @code{libgccjit++.h}.
9131 This is a collection of "thin" wrapper classes around the C API.
9132 Everything is an inline function, implemented in terms of the C API,
9133 so there is nothing extra to link against.
9135 Note that libgccjit is currently of "Alpha" quality;
9136 the APIs are not yet set in stone, and they shouldn't be used in
9141 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
9142 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
9144 @c This is free software: you can redistribute it and/or modify it
9145 @c under the terms of the GNU General Public License as published by
9146 @c the Free Software Foundation, either version 3 of the License, or
9147 @c (at your option) any later version.
9149 @c This program is distributed in the hope that it will be useful, but
9150 @c WITHOUT ANY WARRANTY; without even the implied warranty of
9151 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
9152 @c General Public License for more details.
9154 @c You should have received a copy of the GNU General Public License
9155 @c along with this program. If not, see
9156 @c <http://www.gnu.org/licenses/>.
9159 * Tutorial: Tutorial<2>.
9160 * Topic Reference: Topic Reference<2>.
9164 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world"<2>.
9165 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function<2>.
9166 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables<2>.
9167 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>.
9169 Tutorial part 2: Creating a trivial machine code function
9171 * Options: Options<3>.
9172 * Full example: Full example<3>.
9174 Tutorial part 3: Loops and variables
9176 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues<2>.
9177 * Control flow: Control flow<2>.
9178 * Visualizing the control flow graph: Visualizing the control flow graph<2>.
9179 * Full example: Full example<4>.
9181 Tutorial part 4: Adding JIT-compilation to a toy interpreter
9183 * Our toy interpreter: Our toy interpreter<2>.
9184 * Compiling to machine code: Compiling to machine code<2>.
9185 * Setting things up: Setting things up<2>.
9186 * Populating the function: Populating the function<2>.
9187 * Verifying the control flow graph: Verifying the control flow graph<2>.
9188 * Compiling the context: Compiling the context<2>.
9189 * Single-stepping through the generated code: Single-stepping through the generated code<2>.
9190 * Examining the generated code: Examining the generated code<2>.
9191 * Putting it all together: Putting it all together<2>.
9192 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?<2>.
9194 Behind the curtain: How does our code get optimized?
9196 * Optimizing away stack manipulation: Optimizing away stack manipulation<2>.
9197 * Elimination of tail recursion: Elimination of tail recursion<2>.
9201 * Compilation contexts: Compilation contexts<2>.
9202 * Objects: Objects<2>.
9204 * Expressions: Expressions<2>.
9205 * Creating and using functions: Creating and using functions<2>.
9206 * Source Locations: Source Locations<2>.
9207 * Compiling a context: Compiling a context<2>.
9209 Compilation contexts
9211 * Lifetime-management: Lifetime-management<2>.
9212 * Thread-safety: Thread-safety<2>.
9213 * Error-handling: Error-handling<3>.
9214 * Debugging: Debugging<2>.
9215 * Options: Options<4>.
9219 * String Options: String Options<2>.
9220 * Boolean options: Boolean options<2>.
9221 * Integer options: Integer options<2>.
9222 * Additional command-line options: Additional command-line options<2>.
9226 * Standard types: Standard types<2>.
9227 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile<2>.
9228 * Vector types: Vector types<2>.
9229 * Structures and unions: Structures and unions<2>.
9233 * Rvalues: Rvalues<2>.
9234 * Lvalues: Lvalues<2>.
9235 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions<2>.
9239 * Simple expressions: Simple expressions<2>.
9240 * Vector expressions: Vector expressions<2>.
9241 * Unary Operations: Unary Operations<2>.
9242 * Binary Operations: Binary Operations<2>.
9243 * Comparisons: Comparisons<2>.
9244 * Function calls: Function calls<2>.
9245 * Function pointers: Function pointers<3>.
9246 * Type-coercion: Type-coercion<2>.
9250 * Global variables: Global variables<2>.
9252 Creating and using functions
9254 * Params: Params<2>.
9255 * Functions: Functions<2>.
9256 * Blocks: Blocks<2>.
9257 * Statements: Statements<2>.
9261 * Faking it: Faking it<2>.
9265 * In-memory compilation: In-memory compilation<2>.
9266 * Ahead-of-time compilation: Ahead-of-time compilation<2>.
9271 @node Tutorial<2>,Topic Reference<2>,,C++ bindings for libgccjit
9272 @anchor{cp/intro/index doc}@anchor{118}@anchor{cp/intro/index tutorial}@anchor{119}
9276 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
9277 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
9279 @c This is free software: you can redistribute it and/or modify it
9280 @c under the terms of the GNU General Public License as published by
9281 @c the Free Software Foundation, either version 3 of the License, or
9282 @c (at your option) any later version.
9284 @c This program is distributed in the hope that it will be useful, but
9285 @c WITHOUT ANY WARRANTY; without even the implied warranty of
9286 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
9287 @c General Public License for more details.
9289 @c You should have received a copy of the GNU General Public License
9290 @c along with this program. If not, see
9291 @c <http://www.gnu.org/licenses/>.
9294 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world"<2>.
9295 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function<2>.
9296 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables<2>.
9297 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>.
9301 @node Tutorial part 1 "Hello world"<2>,Tutorial part 2 Creating a trivial machine code function<2>,,Tutorial<2>
9302 @anchor{cp/intro/tutorial01 doc}@anchor{11a}@anchor{cp/intro/tutorial01 tutorial-part-1-hello-world}@anchor{11b}
9303 @subsection Tutorial part 1: "Hello world"
9306 Before we look at the details of the API, let's look at building and
9307 running programs that use the library.
9309 Here's a toy "hello world" program that uses the library's C++ API to
9310 synthesize a call to @cite{printf} and uses it to write a message to stdout.
9312 Don't worry about the content of the program for now; we'll cover
9313 the details in later parts of this tutorial.
9318 /* Smoketest example for libgccjit.so C++ API
9319 Copyright (C) 2014-2019 Free Software Foundation, Inc.
9321 This file is part of GCC.
9323 GCC is free software; you can redistribute it and/or modify it
9324 under the terms of the GNU General Public License as published by
9325 the Free Software Foundation; either version 3, or (at your option)
9328 GCC is distributed in the hope that it will be useful, but
9329 WITHOUT ANY WARRANTY; without even the implied warranty of
9330 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
9331 General Public License for more details.
9333 You should have received a copy of the GNU General Public License
9334 along with GCC; see the file COPYING3. If not see
9335 <http://www.gnu.org/licenses/>. */
9337 #include <libgccjit++.h>
9343 create_code (gccjit::context ctxt)
9345 /* Let's try to inject the equivalent of this C code:
9347 greet (const char *name)
9349 printf ("hello %s\n", name);
9352 gccjit::type void_type = ctxt.get_type (GCC_JIT_TYPE_VOID);
9353 gccjit::type const_char_ptr_type =
9354 ctxt.get_type (GCC_JIT_TYPE_CONST_CHAR_PTR);
9355 gccjit::param param_name =
9356 ctxt.new_param (const_char_ptr_type, "name");
9357 std::vector<gccjit::param> func_params;
9358 func_params.push_back (param_name);
9359 gccjit::function func =
9360 ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
9365 gccjit::param param_format =
9366 ctxt.new_param (const_char_ptr_type, "format");
9367 std::vector<gccjit::param> printf_params;
9368 printf_params.push_back (param_format);
9369 gccjit::function printf_func =
9370 ctxt.new_function (GCC_JIT_FUNCTION_IMPORTED,
9371 ctxt.get_type (GCC_JIT_TYPE_INT),
9375 gccjit::block block = func.new_block ();
9376 block.add_eval (ctxt.new_call (printf_func,
9377 ctxt.new_rvalue ("hello %s\n"),
9379 block.end_with_return ();
9383 main (int argc, char **argv)
9385 gccjit::context ctxt;
9386 gcc_jit_result *result;
9388 /* Get a "context" object for working with the library. */
9389 ctxt = gccjit::context::acquire ();
9391 /* Set some options on the context.
9392 Turn this on to see the code being generated, in assembler form. */
9393 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE, 0);
9395 /* Populate the context. */
9398 /* Compile the code. */
9399 result = ctxt.compile ();
9402 fprintf (stderr, "NULL result");
9408 /* Extract the generated code from "result". */
9409 typedef void (*fn_type) (const char *);
9411 (fn_type)gcc_jit_result_get_code (result, "greet");
9414 fprintf (stderr, "NULL greet");
9418 /* Now call the generated function: */
9422 gcc_jit_result_release (result);
9431 Copy the above to @cite{tut01-hello-world.cc}.
9433 Assuming you have the jit library installed, build the test program
9438 tut01-hello-world.cc \
9439 -o tut01-hello-world \
9445 You should then be able to run the built program:
9448 $ ./tut01-hello-world
9454 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
9455 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
9457 @c This is free software: you can redistribute it and/or modify it
9458 @c under the terms of the GNU General Public License as published by
9459 @c the Free Software Foundation, either version 3 of the License, or
9460 @c (at your option) any later version.
9462 @c This program is distributed in the hope that it will be useful, but
9463 @c WITHOUT ANY WARRANTY; without even the implied warranty of
9464 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
9465 @c General Public License for more details.
9467 @c You should have received a copy of the GNU General Public License
9468 @c along with this program. If not, see
9469 @c <http://www.gnu.org/licenses/>.
9471 @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>
9472 @anchor{cp/intro/tutorial02 doc}@anchor{11c}@anchor{cp/intro/tutorial02 tutorial-part-2-creating-a-trivial-machine-code-function}@anchor{11d}
9473 @subsection Tutorial part 2: Creating a trivial machine code function
9476 Consider this C function:
9487 How can we construct this at run-time using libgccjit's C++ API?
9489 First we need to include the relevant header:
9492 #include <libgccjit++.h>
9497 All state associated with compilation is associated with a
9498 @code{gccjit::context}, which is a thin C++ wrapper around the C API's
9499 @pxref{8,,gcc_jit_context *}.
9501 Create one using @pxref{11e,,gccjit;;context;;acquire()}:
9504 gccjit::context ctxt;
9505 ctxt = gccjit::context::acquire ();
9510 The JIT library has a system of types. It is statically-typed: every
9511 expression is of a specific type, fixed at compile-time. In our example,
9512 all of the expressions are of the C @cite{int} type, so let's obtain this from
9513 the context, as a @code{gccjit::type}, using
9514 @pxref{11f,,gccjit;;context;;get_type()}:
9517 gccjit::type int_type = ctxt.get_type (GCC_JIT_TYPE_INT);
9522 @code{gccjit::type} is an example of a "contextual" object: every
9523 entity in the API is associated with a @code{gccjit::context}.
9525 Memory management is easy: all such "contextual" objects are automatically
9526 cleaned up for you when the context is released, using
9527 @pxref{120,,gccjit;;context;;release()}:
9535 so you don't need to manually track and cleanup all objects, just the
9538 All of the C++ classes in the API are thin wrappers around pointers to
9541 The C++ class hierarchy within the @code{gccjit} namespace looks like this:
9558 One thing you can do with a @code{gccjit::object} is
9559 to ask it for a human-readable description as a @code{std::string}, using
9560 @pxref{121,,gccjit;;object;;get_debug_string()}:
9563 printf ("obj: %s\n", obj.get_debug_string ().c_str ());
9568 giving this text on stdout:
9576 This is invaluable when debugging.
9578 Let's create the function. To do so, we first need to construct
9579 its single parameter, specifying its type and giving it a name,
9580 using @pxref{122,,gccjit;;context;;new_param()}:
9583 gccjit::param param_i = ctxt.new_param (int_type, "i");
9588 and we can then make a vector of all of the params of the function,
9589 in this case just one:
9592 std::vector<gccjit::param> params;
9593 params.push_back (param_i);
9598 Now we can create the function, using
9599 @code{gccjit::context::new_function()}:
9602 gccjit::function func =
9603 ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
9612 To define the code within the function, we must create basic blocks
9613 containing statements.
9615 Every basic block contains a list of statements, eventually terminated
9616 by a statement that either returns, or jumps to another basic block.
9618 Our function has no control-flow, so we just need one basic block:
9621 gccjit::block block = func.new_block ();
9626 Our basic block is relatively simple: it immediately terminates by
9627 returning the value of an expression.
9629 We can build the expression using @pxref{123,,gccjit;;context;;new_binary_op()}:
9632 gccjit::rvalue expr =
9633 ctxt.new_binary_op (
9634 GCC_JIT_BINARY_OP_MULT, int_type,
9640 A @code{gccjit::rvalue} is another example of a
9641 @code{gccjit::object} subclass. As before, we can print it with
9642 @pxref{121,,gccjit;;object;;get_debug_string()}.
9645 printf ("expr: %s\n", expr.get_debug_string ().c_str ());
9658 Note that @code{gccjit::rvalue} provides numerous overloaded operators
9659 which can be used to dramatically reduce the amount of typing needed.
9660 We can build the above binary operation more directly with this one-liner:
9663 gccjit::rvalue expr = param_i * param_i;
9668 Creating the expression in itself doesn't do anything; we have to add
9669 this expression to a statement within the block. In this case, we use it
9670 to build a return statement, which terminates the basic block:
9673 block.end_with_return (expr);
9678 OK, we've populated the context. We can now compile it using
9679 @pxref{124,,gccjit;;context;;compile()}:
9682 gcc_jit_result *result;
9683 result = ctxt.compile ();
9688 and get a @pxref{16,,gcc_jit_result *}.
9690 We can now use @pxref{17,,gcc_jit_result_get_code()} to look up a specific
9691 machine code routine within the result, in this case, the function we
9695 void *fn_ptr = gcc_jit_result_get_code (result, "square");
9698 fprintf (stderr, "NULL fn_ptr");
9705 We can now cast the pointer to an appropriate function pointer type, and
9709 typedef int (*fn_type) (int);
9710 fn_type square = (fn_type)fn_ptr;
9711 printf ("result: %d", square (5));
9723 * Options: Options<3>.
9724 * Full example: Full example<3>.
9728 @node Options<3>,Full example<3>,,Tutorial part 2 Creating a trivial machine code function<2>
9729 @anchor{cp/intro/tutorial02 options}@anchor{125}
9730 @subsubsection Options
9733 To get more information on what's going on, you can set debugging flags
9734 on the context using @pxref{126,,gccjit;;context;;set_bool_option()}.
9736 @c (I'm deliberately not mentioning
9737 @c :c:macro:`GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE` here since I think
9738 @c it's probably more of use to implementors than to users)
9740 Setting @pxref{1c,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE} will dump a
9741 C-like representation to stderr when you compile (GCC's "GIMPLE"
9745 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE, 1);
9746 result = ctxt.compile ();
9752 square (signed int i)
9764 We can see the generated machine code in assembler form (on stderr) by
9765 setting @pxref{1d,,GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE} on the context
9769 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE, 1);
9770 result = ctxt.compile ();
9779 .type square, @@function
9784 .cfi_def_cfa_offset 16
9787 .cfi_def_cfa_register 6
9791 imull -4(%rbp), %eax
9797 .size square, .-square
9798 .ident "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)"
9799 .section .note.GNU-stack,"",@@progbits
9804 By default, no optimizations are performed, the equivalent of GCC's
9805 @cite{-O0} option. We can turn things up to e.g. @cite{-O3} by calling
9806 @pxref{127,,gccjit;;context;;set_int_option()} with
9807 @pxref{1f,,GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}:
9810 ctxt.set_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL, 3);
9820 .type square, @@function
9830 .size square, .-square
9831 .ident "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)"
9832 .section .note.GNU-stack,"",@@progbits
9837 Naturally this has only a small effect on such a trivial function.
9839 @node Full example<3>,,Options<3>,Tutorial part 2 Creating a trivial machine code function<2>
9840 @anchor{cp/intro/tutorial02 full-example}@anchor{128}
9841 @subsubsection Full example
9844 Here's what the above looks like as a complete program:
9849 /* Usage example for libgccjit.so's C++ API
9850 Copyright (C) 2014-2019 Free Software Foundation, Inc.
9852 This file is part of GCC.
9854 GCC is free software; you can redistribute it and/or modify it
9855 under the terms of the GNU General Public License as published by
9856 the Free Software Foundation; either version 3, or (at your option)
9859 GCC is distributed in the hope that it will be useful, but
9860 WITHOUT ANY WARRANTY; without even the implied warranty of
9861 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
9862 General Public License for more details.
9864 You should have received a copy of the GNU General Public License
9865 along with GCC; see the file COPYING3. If not see
9866 <http://www.gnu.org/licenses/>. */
9868 #include <libgccjit++.h>
9874 create_code (gccjit::context ctxt)
9876 /* Let's try to inject the equivalent of this C code:
9883 gccjit::type int_type = ctxt.get_type (GCC_JIT_TYPE_INT);
9884 gccjit::param param_i = ctxt.new_param (int_type, "i");
9885 std::vector<gccjit::param> params;
9886 params.push_back (param_i);
9887 gccjit::function func = ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
9892 gccjit::block block = func.new_block ();
9894 gccjit::rvalue expr =
9895 ctxt.new_binary_op (GCC_JIT_BINARY_OP_MULT, int_type,
9898 block.end_with_return (expr);
9902 main (int argc, char **argv)
9904 /* Get a "context" object for working with the library. */
9905 gccjit::context ctxt = gccjit::context::acquire ();
9907 /* Set some options on the context.
9908 Turn this on to see the code being generated, in assembler form. */
9909 ctxt.set_bool_option (
9910 GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
9913 /* Populate the context. */
9916 /* Compile the code. */
9917 gcc_jit_result *result = ctxt.compile ();
9919 /* We're done with the context; we can release it: */
9924 fprintf (stderr, "NULL result");
9928 /* Extract the generated code from "result". */
9929 void *fn_ptr = gcc_jit_result_get_code (result, "square");
9932 fprintf (stderr, "NULL fn_ptr");
9933 gcc_jit_result_release (result);
9937 typedef int (*fn_type) (int);
9938 fn_type square = (fn_type)fn_ptr;
9939 printf ("result: %d\n", square (5));
9941 gcc_jit_result_release (result);
9950 Building and running it:
9958 # Run the built program:
9965 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
9966 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
9968 @c This is free software: you can redistribute it and/or modify it
9969 @c under the terms of the GNU General Public License as published by
9970 @c the Free Software Foundation, either version 3 of the License, or
9971 @c (at your option) any later version.
9973 @c This program is distributed in the hope that it will be useful, but
9974 @c WITHOUT ANY WARRANTY; without even the implied warranty of
9975 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
9976 @c General Public License for more details.
9978 @c You should have received a copy of the GNU General Public License
9979 @c along with this program. If not, see
9980 @c <http://www.gnu.org/licenses/>.
9982 @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>
9983 @anchor{cp/intro/tutorial03 tutorial-part-3-loops-and-variables}@anchor{129}@anchor{cp/intro/tutorial03 doc}@anchor{12a}
9984 @subsection Tutorial part 3: Loops and variables
9987 Consider this C function:
9992 int loop_test (int n)
9995 for (int i = 0; i < n; i++)
10004 This example demonstrates some more features of libgccjit, with local
10005 variables and a loop.
10007 To break this down into libgccjit terms, it's usually easier to reword
10008 the @cite{for} loop as a @cite{while} loop, giving:
10013 int loop_test (int n)
10029 Here's what the final control flow graph will look like:
10036 @image{sum-of-squares,,,image of a control flow graph,png}
10042 As before, we include the libgccjit++ header and make a
10043 @code{gccjit::context}.
10046 #include <libgccjit++.h>
10050 gccjit::context ctxt;
10051 ctxt = gccjit::context::acquire ();
10056 The function works with the C @cite{int} type.
10058 In the previous tutorial we acquired this via
10061 gccjit::type the_type = ctxt.get_type (ctxt, GCC_JIT_TYPE_INT);
10066 though we could equally well make it work on, say, @cite{double}:
10069 gccjit::type the_type = ctxt.get_type (ctxt, GCC_JIT_TYPE_DOUBLE);
10074 For integer types we can use @code{gccjit::context::get_int_type}
10075 to directly bind a specific type:
10078 gccjit::type the_type = ctxt.get_int_type <int> ();
10083 Let's build the function:
10086 gcc_jit_param n = ctxt.new_param (the_type, "n");
10087 std::vector<gccjit::param> params;
10088 params.push_back (n);
10089 gccjit::function func =
10090 ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
10099 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues<2>.
10100 * Control flow: Control flow<2>.
10101 * Visualizing the control flow graph: Visualizing the control flow graph<2>.
10102 * Full example: Full example<4>.
10106 @node Expressions lvalues and rvalues<2>,Control flow<2>,,Tutorial part 3 Loops and variables<2>
10107 @anchor{cp/intro/tutorial03 expressions-lvalues-and-rvalues}@anchor{12b}
10108 @subsubsection Expressions: lvalues and rvalues
10111 The base class of expression is the @code{gccjit::rvalue},
10112 representing an expression that can be on the @emph{right}-hand side of
10113 an assignment: a value that can be computed somehow, and assigned
10114 @emph{to} a storage area (such as a variable). It has a specific
10115 @code{gccjit::type}.
10117 Anothe important class is @code{gccjit::lvalue}.
10118 A @code{gccjit::lvalue}. is something that can of the @emph{left}-hand
10119 side of an assignment: a storage area (such as a variable).
10121 In other words, every assignment can be thought of as:
10129 Note that @code{gccjit::lvalue} is a subclass of
10130 @code{gccjit::rvalue}, where in an assignment of the form:
10133 LVALUE_A = LVALUE_B;
10138 the @cite{LVALUE_B} implies reading the current value of that storage
10139 area, assigning it into the @cite{LVALUE_A}.
10141 So far the only expressions we've seen are from the previous tutorial:
10147 the multiplication @cite{i * i}:
10153 gccjit::rvalue expr =
10154 ctxt.new_binary_op (
10155 GCC_JIT_BINARY_OP_MULT, int_type,
10158 /* Alternatively, using operator-overloading: */
10159 gccjit::rvalue expr = param_i * param_i;
10164 which is a @code{gccjit::rvalue}, and
10171 the various function parameters: @cite{param_i} and @cite{param_n}, instances of
10172 @code{gccjit::param}, which is a subclass of @code{gccjit::lvalue}
10173 (and, in turn, of @code{gccjit::rvalue}):
10174 we can both read from and write to function parameters within the
10175 body of a function.
10178 Our new example has a new kind of expression: we have two local
10179 variables. We create them by calling
10180 @pxref{12c,,gccjit;;function;;new_local()}, supplying a type and a name:
10183 /* Build locals: */
10184 gccjit::lvalue i = func.new_local (the_type, "i");
10185 gccjit::lvalue sum = func.new_local (the_type, "sum");
10190 These are instances of @code{gccjit::lvalue} - they can be read from
10193 Note that there is no precanned way to create @emph{and} initialize a variable
10202 Instead, having added the local to the function, we have to separately add
10203 an assignment of @cite{0} to @cite{local_i} at the beginning of the function.
10205 @node Control flow<2>,Visualizing the control flow graph<2>,Expressions lvalues and rvalues<2>,Tutorial part 3 Loops and variables<2>
10206 @anchor{cp/intro/tutorial03 control-flow}@anchor{12d}
10207 @subsubsection Control flow
10210 This function has a loop, so we need to build some basic blocks to
10211 handle the control flow. In this case, we need 4 blocks:
10217 before the loop (initializing the locals)
10220 the conditional at the top of the loop (comparing @cite{i < n})
10223 the body of the loop
10226 after the loop terminates (@cite{return sum})
10229 so we create these as @code{gccjit::block} instances within the
10230 @code{gccjit::function}:
10233 gccjit::block b_initial = func.new_block ("initial");
10234 gccjit::block b_loop_cond = func.new_block ("loop_cond");
10235 gccjit::block b_loop_body = func.new_block ("loop_body");
10236 gccjit::block b_after_loop = func.new_block ("after_loop");
10241 We now populate each block with statements.
10243 The entry block @cite{b_initial} consists of initializations followed by a jump
10244 to the conditional. We assign @cite{0} to @cite{i} and to @cite{sum}, using
10245 @pxref{12e,,gccjit;;block;;add_assignment()} to add
10246 an assignment statement, and using @pxref{12f,,gccjit;;context;;zero()} to get
10247 the constant value @cite{0} for the relevant type for the right-hand side of
10252 b_initial.add_assignment (sum, ctxt.zero (the_type));
10255 b_initial.add_assignment (i, ctxt.zero (the_type));
10260 We can then terminate the entry block by jumping to the conditional:
10263 b_initial.end_with_jump (b_loop_cond);
10268 The conditional block is equivalent to the line @cite{while (i < n)} from our
10269 C example. It contains a single statement: a conditional, which jumps to
10270 one of two destination blocks depending on a boolean
10271 @code{gccjit::rvalue}, in this case the comparison of @cite{i} and @cite{n}.
10273 We could build the comparison using @pxref{130,,gccjit;;context;;new_comparison()}:
10276 gccjit::rvalue guard =
10277 ctxt.new_comparison (GCC_JIT_COMPARISON_GE,
10283 and can then use this to add @cite{b_loop_cond}'s sole statement, via
10284 @pxref{131,,gccjit;;block;;end_with_conditional()}:
10287 b_loop_cond.end_with_conditional (guard,
10288 b_after_loop, // on_true
10289 b_loop_body); // on_false
10294 However @code{gccjit::rvalue} has overloaded operators for this, so we
10295 express the conditional as
10298 gccjit::rvalue guard = (i >= n);
10303 and hence we can write the block more concisely as:
10306 b_loop_cond.end_with_conditional (
10308 b_after_loop, // on_true
10309 b_loop_body); // on_false
10314 Next, we populate the body of the loop.
10316 The C statement @cite{sum += i * i;} is an assignment operation, where an
10317 lvalue is modified "in-place". We use
10318 @pxref{132,,gccjit;;block;;add_assignment_op()} to handle these operations:
10322 b_loop_body.add_assignment_op (sum,
10323 GCC_JIT_BINARY_OP_PLUS,
10329 The @cite{i++} can be thought of as @cite{i += 1}, and can thus be handled in
10330 a similar way. We use @pxref{2f,,gcc_jit_context_one()} to get the constant
10331 value @cite{1} (for the relevant type) for the right-hand side
10336 b_loop_body.add_assignment_op (i,
10337 GCC_JIT_BINARY_OP_PLUS,
10338 ctxt.one (the_type));
10345 For numeric constants other than 0 or 1, we could use
10346 @pxref{133,,gccjit;;context;;new_rvalue()}, which has overloads
10347 for both @code{int} and @code{double}.
10351 The loop body completes by jumping back to the conditional:
10354 b_loop_body.end_with_jump (b_loop_cond);
10359 Finally, we populate the @cite{b_after_loop} block, reached when the loop
10360 conditional is false. We want to generate the equivalent of:
10368 so the block is just one statement:
10372 b_after_loop.end_with_return (sum);
10379 You can intermingle block creation with statement creation,
10380 but given that the terminator statements generally include references
10381 to other blocks, I find it's clearer to create all the blocks,
10382 @emph{then} all the statements.
10386 We've finished populating the function. As before, we can now compile it
10390 gcc_jit_result *result;
10391 result = ctxt.compile ();
10397 fprintf (stderr, "NULL result");
10401 typedef int (*loop_test_fn_type) (int);
10402 loop_test_fn_type loop_test =
10403 (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
10406 fprintf (stderr, "NULL loop_test");
10407 gcc_jit_result_release (result);
10410 printf ("result: %d", loop_test (10));
10421 @node Visualizing the control flow graph<2>,Full example<4>,Control flow<2>,Tutorial part 3 Loops and variables<2>
10422 @anchor{cp/intro/tutorial03 visualizing-the-control-flow-graph}@anchor{134}
10423 @subsubsection Visualizing the control flow graph
10426 You can see the control flow graph of a function using
10427 @pxref{135,,gccjit;;function;;dump_to_dot()}:
10430 func.dump_to_dot ("/tmp/sum-of-squares.dot");
10435 giving a .dot file in GraphViz format.
10437 You can convert this to an image using @cite{dot}:
10440 $ dot -Tpng /tmp/sum-of-squares.dot -o /tmp/sum-of-squares.png
10445 or use a viewer (my preferred one is xdot.py; see
10446 @indicateurl{https://github.com/jrfonseca/xdot.py}; on Fedora you can
10447 install it with @cite{yum install python-xdot}):
10454 @image{sum-of-squares,,,image of a control flow graph,png}
10460 @node Full example<4>,,Visualizing the control flow graph<2>,Tutorial part 3 Loops and variables<2>
10461 @anchor{cp/intro/tutorial03 full-example}@anchor{136}
10462 @subsubsection Full example
10468 /* Usage example for libgccjit.so's C++ API
10469 Copyright (C) 2014-2019 Free Software Foundation, Inc.
10471 This file is part of GCC.
10473 GCC is free software; you can redistribute it and/or modify it
10474 under the terms of the GNU General Public License as published by
10475 the Free Software Foundation; either version 3, or (at your option)
10478 GCC is distributed in the hope that it will be useful, but
10479 WITHOUT ANY WARRANTY; without even the implied warranty of
10480 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10481 General Public License for more details.
10483 You should have received a copy of the GNU General Public License
10484 along with GCC; see the file COPYING3. If not see
10485 <http://www.gnu.org/licenses/>. */
10487 #include <libgccjit++.h>
10489 #include <stdlib.h>
10493 create_code (gccjit::context ctxt)
10496 Simple sum-of-squares, to test conditionals and looping
10498 int loop_test (int n)
10502 for (i = 0; i < n ; i ++)
10508 gccjit::type the_type = ctxt.get_int_type <int> ();
10509 gccjit::type return_type = the_type;
10511 gccjit::param n = ctxt.new_param (the_type, "n");
10512 std::vector<gccjit::param> params;
10513 params.push_back (n);
10514 gccjit::function func =
10515 ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
10520 /* Build locals: */
10521 gccjit::lvalue i = func.new_local (the_type, "i");
10522 gccjit::lvalue sum = func.new_local (the_type, "sum");
10524 gccjit::block b_initial = func.new_block ("initial");
10525 gccjit::block b_loop_cond = func.new_block ("loop_cond");
10526 gccjit::block b_loop_body = func.new_block ("loop_body");
10527 gccjit::block b_after_loop = func.new_block ("after_loop");
10530 b_initial.add_assignment (sum, ctxt.zero (the_type));
10533 b_initial.add_assignment (i, ctxt.zero (the_type));
10535 b_initial.end_with_jump (b_loop_cond);
10538 b_loop_cond.end_with_conditional (
10544 b_loop_body.add_assignment_op (sum,
10545 GCC_JIT_BINARY_OP_PLUS,
10549 b_loop_body.add_assignment_op (i,
10550 GCC_JIT_BINARY_OP_PLUS,
10551 ctxt.one (the_type));
10553 b_loop_body.end_with_jump (b_loop_cond);
10556 b_after_loop.end_with_return (sum);
10560 main (int argc, char **argv)
10562 gccjit::context ctxt;
10563 gcc_jit_result *result = NULL;
10565 /* Get a "context" object for working with the library. */
10566 ctxt = gccjit::context::acquire ();
10568 /* Set some options on the context.
10569 Turn this on to see the code being generated, in assembler form. */
10570 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
10573 /* Populate the context. */
10574 create_code (ctxt);
10576 /* Compile the code. */
10577 result = ctxt.compile ();
10583 fprintf (stderr, "NULL result");
10587 /* Extract the generated code from "result". */
10588 typedef int (*loop_test_fn_type) (int);
10589 loop_test_fn_type loop_test =
10590 (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
10593 fprintf (stderr, "NULL loop_test");
10594 gcc_jit_result_release (result);
10598 /* Run the generated code. */
10599 int val = loop_test (10);
10600 printf("loop_test returned: %d\n", val);
10602 gcc_jit_result_release (result);
10611 Building and running it:
10615 tut03-sum-of-squares.cc \
10616 -o tut03-sum-of-squares \
10619 # Run the built program:
10620 $ ./tut03-sum-of-squares
10621 loop_test returned: 285
10626 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
10627 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
10629 @c This is free software: you can redistribute it and/or modify it
10630 @c under the terms of the GNU General Public License as published by
10631 @c the Free Software Foundation, either version 3 of the License, or
10632 @c (at your option) any later version.
10634 @c This program is distributed in the hope that it will be useful, but
10635 @c WITHOUT ANY WARRANTY; without even the implied warranty of
10636 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10637 @c General Public License for more details.
10639 @c You should have received a copy of the GNU General Public License
10640 @c along with this program. If not, see
10641 @c <http://www.gnu.org/licenses/>.
10643 @node Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>,,Tutorial part 3 Loops and variables<2>,Tutorial<2>
10644 @anchor{cp/intro/tutorial04 tutorial-part-4-adding-jit-compilation-to-a-toy-interpreter}@anchor{137}@anchor{cp/intro/tutorial04 doc}@anchor{138}
10645 @subsection Tutorial part 4: Adding JIT-compilation to a toy interpreter
10648 In this example we construct a "toy" interpreter, and add JIT-compilation
10652 * Our toy interpreter: Our toy interpreter<2>.
10653 * Compiling to machine code: Compiling to machine code<2>.
10654 * Setting things up: Setting things up<2>.
10655 * Populating the function: Populating the function<2>.
10656 * Verifying the control flow graph: Verifying the control flow graph<2>.
10657 * Compiling the context: Compiling the context<2>.
10658 * Single-stepping through the generated code: Single-stepping through the generated code<2>.
10659 * Examining the generated code: Examining the generated code<2>.
10660 * Putting it all together: Putting it all together<2>.
10661 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?<2>.
10665 @node Our toy interpreter<2>,Compiling to machine code<2>,,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
10666 @anchor{cp/intro/tutorial04 our-toy-interpreter}@anchor{139}
10667 @subsubsection Our toy interpreter
10670 It's a stack-based interpreter, and is intended as a (very simple) example
10671 of the kind of bytecode interpreter seen in dynamic languages such as
10674 For the sake of simplicity, our toy virtual machine is very limited:
10682 The only data type is @cite{int}
10685 It can only work on one function at a time (so that the only
10686 function call that can be made is to recurse).
10689 Functions can only take one parameter.
10692 Functions have a stack of @cite{int} values.
10695 We'll implement function call within the interpreter by calling a
10696 function in our implementation, rather than implementing our own
10700 The parser is only good enough to get the examples to work.
10704 Naturally, a real interpreter would be much more complicated that this.
10706 The following operations are supported:
10709 @multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxx}
10732 Duplicate top of stack.
10748 Swap top two elements
10765 Add the top two elements
10774 @code{[..., (x+y)]}
10782 Likewise, but subtract.
10790 @code{[..., (x-y)]}
10798 Likewise, but multiply.
10806 @code{[..., (x*y)]}
10814 Compare the top two
10815 elements on the stack
10816 and push a nonzero/zero
10825 @code{[..., (x<y)]}
10833 Recurse, passing the top
10835 popping the result.
10843 @code{[..., fn(x)]}
10851 Return the top of the
10864 PUSH_CONST @cite{arg}
10880 JUMP_ABS_IF_TRUE @cite{arg}
10884 Pop; if top of stack was
10899 Programs can be interpreted, disassembled, and compiled to machine code.
10901 The interpreter reads @code{.toy} scripts. Here's what a simple recursive
10902 factorial program looks like, the script @code{factorial.toy}.
10903 The parser ignores lines beginning with a @cite{#}.
10908 # Simple recursive factorial implementation, roughly equivalent to:
10910 # int factorial (int arg)
10914 # return arg * factorial (arg - 1)
10922 # stack: [arg, arg]
10926 # stack: [arg, arg, 2]
10930 # stack: [arg, (arg < 2)]
10938 # stack: [arg, arg]
10942 # stack: [arg, arg, 1]
10946 # stack: [arg, (arg - 1)
10950 # stack: [arg, factorial(arg - 1)]
10954 # stack: [arg * factorial(arg - 1)]
10964 The interpreter is a simple infinite loop with a big @code{switch} statement
10965 based on what the next opcode is:
10972 toyvm_function::interpret (int arg, FILE *trace)
10975 #define PUSH(ARG) (frame.push (ARG))
10976 #define POP(ARG) (frame.pop ())
10978 frame.frm_function = this;
10980 frame.frm_cur_depth = 0;
10988 assert (frame.frm_pc < fn_num_ops);
10989 op = &fn_ops[frame.frm_pc++];
10993 frame.dump_stack (trace);
10994 disassemble_op (op, frame.frm_pc, trace);
10997 switch (op->op_opcode)
10999 /* Ops taking no operand. */
11019 case BINARY_SUBTRACT:
11031 case BINARY_COMPARE_LT:
11039 x = interpret (x, trace);
11046 /* Ops taking an operand. */
11048 PUSH (op->op_operand);
11051 case JUMP_ABS_IF_TRUE:
11054 frame.frm_pc = op->op_operand;
11058 assert (0); /* unknown opcode */
11060 @} /* end of switch on opcode */
11061 @} /* end of while loop */
11073 @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>
11074 @anchor{cp/intro/tutorial04 compiling-to-machine-code}@anchor{13a}
11075 @subsubsection Compiling to machine code
11078 We want to generate machine code that can be cast to this type and
11079 then directly executed in-process:
11084 typedef int (*toyvm_compiled_func) (int);
11092 Our compiler isn't very sophisticated; it takes the implementation of
11093 each opcode above, and maps it directly to the operations supported by
11096 How should we handle the stack? In theory we could calculate what the
11097 stack depth will be at each opcode, and optimize away the stack
11098 manipulation "by hand". We'll see below that libgccjit is able to do
11099 this for us, so we'll implement stack manipulation
11100 in a direct way, by creating a @code{stack} array and @code{stack_depth}
11101 variables, local within the generated function, equivalent to this C code:
11105 int stack[MAX_STACK_DEPTH];
11110 We'll also have local variables @code{x} and @code{y} for use when implementing
11111 the opcodes, equivalent to this:
11120 This means our compiler has the following state:
11126 toyvm_function &toyvmfn;
11128 gccjit::context ctxt;
11130 gccjit::type int_type;
11131 gccjit::type bool_type;
11132 gccjit::type stack_type; /* int[MAX_STACK_DEPTH] */
11134 gccjit::rvalue const_one;
11136 gccjit::function fn;
11137 gccjit::param param_arg;
11138 gccjit::lvalue stack;
11139 gccjit::lvalue stack_depth;
11143 gccjit::location op_locs[MAX_OPS];
11144 gccjit::block initial_block;
11145 gccjit::block op_blocks[MAX_OPS];
11153 @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>
11154 @anchor{cp/intro/tutorial04 setting-things-up}@anchor{13b}
11155 @subsubsection Setting things up
11158 First we create our types:
11165 compilation_state::create_types ()
11167 /* Create types. */
11168 int_type = ctxt.get_type (GCC_JIT_TYPE_INT);
11169 bool_type = ctxt.get_type (GCC_JIT_TYPE_BOOL);
11170 stack_type = ctxt.new_array_type (int_type, MAX_STACK_DEPTH);
11178 along with extracting a useful @cite{int} constant:
11183 const_one = ctxt.one (int_type);
11193 We'll implement push and pop in terms of the @code{stack} array and
11194 @code{stack_depth}. Here are helper functions for adding statements to
11195 a block, implementing pushing and popping values:
11202 compilation_state::add_push (gccjit::block block,
11203 gccjit::rvalue rvalue,
11204 gccjit::location loc)
11206 /* stack[stack_depth] = RVALUE */
11207 block.add_assignment (
11208 /* stack[stack_depth] */
11209 ctxt.new_array_access (
11216 /* "stack_depth++;". */
11217 block.add_assignment_op (
11219 GCC_JIT_BINARY_OP_PLUS,
11225 compilation_state::add_pop (gccjit::block block,
11226 gccjit::lvalue lvalue,
11227 gccjit::location loc)
11229 /* "--stack_depth;". */
11230 block.add_assignment_op (
11232 GCC_JIT_BINARY_OP_MINUS,
11236 /* "LVALUE = stack[stack_depth];". */
11237 block.add_assignment (
11239 /* stack[stack_depth] */
11240 ctxt.new_array_access (stack,
11252 We will support single-stepping through the generated code in the
11253 debugger, so we need to create @code{gccjit::location} instances, one
11254 per operation in the source code. These will reference the lines of
11255 e.g. @code{factorial.toy}.
11262 compilation_state::create_locations ()
11264 for (int pc = 0; pc < toyvmfn.fn_num_ops; pc++)
11266 toyvm_op *op = &toyvmfn.fn_ops[pc];
11268 op_locs[pc] = ctxt.new_location (toyvmfn.fn_filename,
11280 Let's create the function itself. As usual, we create its parameter
11281 first, then use the parameter to create the function:
11288 compilation_state::create_function (const char *funcname)
11290 std::vector <gccjit::param> params;
11291 param_arg = ctxt.new_param (int_type, "arg", op_locs[0]);
11292 params.push_back (param_arg);
11293 fn = ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
11305 We create the locals within the function.
11310 stack = fn.new_local (stack_type, "stack");
11311 stack_depth = fn.new_local (int_type, "stack_depth");
11312 x = fn.new_local (int_type, "x");
11313 y = fn.new_local (int_type, "y");
11321 @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>
11322 @anchor{cp/intro/tutorial04 populating-the-function}@anchor{13c}
11323 @subsubsection Populating the function
11326 There's some one-time initialization, and the API treats the first block
11327 you create as the entrypoint of the function, so we need to create that
11333 initial_block = fn.new_block ("initial");
11341 We can now create blocks for each of the operations. Most of these will
11342 be consolidated into larger blocks when the optimizer runs.
11347 for (int pc = 0; pc < toyvmfn.fn_num_ops; pc++)
11350 sprintf (buf, "instr%i", pc);
11351 op_blocks[pc] = fn.new_block (buf);
11360 Now that we have a block it can jump to when it's done, we can populate
11367 /* "stack_depth = 0;". */
11368 initial_block.add_assignment (stack_depth,
11369 ctxt.zero (int_type),
11372 /* "PUSH (arg);". */
11373 add_push (initial_block,
11377 /* ...and jump to insn 0. */
11378 initial_block.end_with_jump (op_blocks[0],
11387 We can now populate the blocks for the individual operations. We loop
11388 through them, adding instructions to their blocks:
11393 for (int pc = 0; pc < toyvmfn.fn_num_ops; pc++)
11395 gccjit::location loc = op_locs[pc];
11397 gccjit::block block = op_blocks[pc];
11398 gccjit::block next_block = (pc < toyvmfn.fn_num_ops
11399 ? op_blocks[pc + 1]
11403 op = &toyvmfn.fn_ops[pc];
11411 We're going to have another big @code{switch} statement for implementing
11412 the opcodes, this time for compiling them, rather than interpreting
11413 them. It's helpful to have macros for implementing push and pop, so that
11414 we can make the @code{switch} statement that's coming up look as much as
11415 possible like the one above within the interpreter:
11419 #define X_EQUALS_POP()\
11420 add_pop (block, x, loc)
11421 #define Y_EQUALS_POP()\
11422 add_pop (block, y, loc)
11423 #define PUSH_RVALUE(RVALUE)\
11424 add_push (block, (RVALUE), loc)
11437 A particularly clever implementation would have an @emph{identical}
11438 @code{switch} statement shared by the interpreter and the compiler, with
11439 some preprocessor "magic". We're not doing that here, for the sake
11444 When I first implemented this compiler, I accidentally missed an edit
11445 when copying and pasting the @code{Y_EQUALS_POP} macro, so that popping the
11446 stack into @code{y} instead erroneously assigned it to @code{x}, leaving @code{y}
11449 To track this kind of thing down, we can use
11450 @pxref{13d,,gccjit;;block;;add_comment()} to add descriptive comments
11451 to the internal representation. This is invaluable when looking through
11452 the generated IR for, say @code{factorial}:
11458 block.add_comment (opcode_names[op->op_opcode], loc);
11466 We can now write the big @code{switch} statement that implements the
11467 individual opcodes, populating the relevant block with statements:
11473 switch (op->op_opcode)
11492 ctxt.new_binary_op (
11493 GCC_JIT_BINARY_OP_PLUS,
11499 case BINARY_SUBTRACT:
11503 ctxt.new_binary_op (
11504 GCC_JIT_BINARY_OP_MINUS,
11514 ctxt.new_binary_op (
11515 GCC_JIT_BINARY_OP_MULT,
11521 case BINARY_COMPARE_LT:
11525 /* cast of bool to int */
11527 /* (x < y) as a bool */
11528 ctxt.new_comparison (
11529 GCC_JIT_COMPARISON_LT,
11549 block.end_with_return (x, loc);
11552 /* Ops taking an operand. */
11555 ctxt.new_rvalue (int_type, op->op_operand));
11558 case JUMP_ABS_IF_TRUE:
11560 block.end_with_conditional (
11562 ctxt.new_cast (x, bool_type, loc),
11563 op_blocks[op->op_operand], /* on_true */
11564 next_block, /* on_false */
11570 @} /* end of switch on opcode */
11578 Every block must be terminated, via a call to one of the
11579 @code{gccjit::block::end_with_} entrypoints. This has been done for two
11580 of the opcodes, but we need to do it for the other ones, by jumping
11586 if (op->op_opcode != JUMP_ABS_IF_TRUE
11587 && op->op_opcode != RETURN)
11588 block.end_with_jump (next_block, loc);
11596 This is analogous to simply incrementing the program counter.
11598 @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>
11599 @anchor{cp/intro/tutorial04 verifying-the-control-flow-graph}@anchor{13e}
11600 @subsubsection Verifying the control flow graph
11603 Having finished looping over the blocks, the context is complete.
11605 As before, we can verify that the control flow and statements are sane by
11606 using @pxref{135,,gccjit;;function;;dump_to_dot()}:
11609 fn.dump_to_dot ("/tmp/factorial.dot");
11614 and viewing the result. Note how the label names, comments, and
11615 variable names show up in the dump, to make it easier to spot
11616 errors in our compiler.
11623 @image{factorial,,,image of a control flow graph,png}
11629 @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>
11630 @anchor{cp/intro/tutorial04 compiling-the-context}@anchor{13f}
11631 @subsubsection Compiling the context
11634 Having finished looping over the blocks and populating them with
11635 statements, the context is complete.
11637 We can now compile it, extract machine code from the result, and
11644 class compilation_result
11647 compilation_result (gcc_jit_result *result) :
11651 ~compilation_result ()
11653 gcc_jit_result_release (m_result);
11656 void *get_code (const char *funcname)
11658 return gcc_jit_result_get_code (m_result, funcname);
11662 gcc_jit_result *m_result;
11671 compilation_result compiler_result = fn->compile ();
11673 const char *funcname = fn->get_function_name ();
11674 toyvm_compiled_func code
11675 = (toyvm_compiled_func)compiler_result.get_code (funcname);
11677 printf ("compiler result: %d\n",
11678 code (atoi (argv[2])));
11686 @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>
11687 @anchor{cp/intro/tutorial04 single-stepping-through-the-generated-code}@anchor{140}
11688 @subsubsection Single-stepping through the generated code
11691 It's possible to debug the generated code. To do this we need to both:
11699 Set up source code locations for our statements, so that we can
11700 meaningfully step through the code. We did this above by
11701 calling @pxref{141,,gccjit;;context;;new_location()} and using the
11705 Enable the generation of debugging information, by setting
11706 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} on the
11707 @code{gccjit::context} via
11708 @pxref{126,,gccjit;;context;;set_bool_option()}:
11711 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DEBUGINFO, 1);
11718 Having done this, we can put a breakpoint on the generated function:
11721 $ gdb --args ./toyvm factorial.toy 10
11722 (gdb) break factorial
11723 Function "factorial" not defined.
11724 Make breakpoint pending on future shared library load? (y or [n]) y
11725 Breakpoint 1 (factorial) pending.
11727 Breakpoint 1, factorial (arg=10) at factorial.toy:14
11733 We've set up location information, which references @code{factorial.toy}.
11734 This allows us to use e.g. @code{list} to see where we are in the script:
11739 10 # Initial state:
11744 15 # stack: [arg, arg]
11752 and to step through the function, examining the data:
11758 22 BINARY_COMPARE_LT
11760 $5 = @{10, 10, 2, 0, -7152, 32767, 0, 0@}
11761 (gdb) print stack_depth
11767 You'll see that the parts of the @code{stack} array that haven't been
11768 touched yet are uninitialized.
11772 Turning on optimizations may lead to unpredictable results when
11773 stepping through the generated code: the execution may appear to
11774 "jump around" the source code. This is analogous to turning up the
11775 optimization level in a regular compiler.
11779 @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>
11780 @anchor{cp/intro/tutorial04 examining-the-generated-code}@anchor{142}
11781 @subsubsection Examining the generated code
11784 How good is the optimized code?
11786 We can turn up optimizations, by calling
11787 @pxref{127,,gccjit;;context;;set_int_option()} with
11788 @pxref{1f,,GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}:
11791 ctxt.set_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL, 3);
11796 One of GCC's internal representations is called "gimple". A dump of the
11797 initial gimple representation of the code can be seen by setting:
11800 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE, 1);
11805 With optimization on and source locations displayed, this gives:
11807 @c We'll use "c" for gimple dumps
11810 factorial (signed int arg)
11812 <unnamed type> D.80;
11820 signed int stack_depth;
11821 signed int stack[8];
11827 stack[stack_depth] = arg;
11828 stack_depth = stack_depth + 1;
11832 stack_depth = stack_depth + -1;
11833 x = stack[stack_depth];
11834 stack[stack_depth] = x;
11835 stack_depth = stack_depth + 1;
11836 stack[stack_depth] = x;
11837 stack_depth = stack_depth + 1;
11841 stack[stack_depth] = 2;
11842 stack_depth = stack_depth + 1;
11850 You can see the generated machine code in assembly form via:
11853 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE, 1);
11854 result = ctxt.compile ();
11859 which shows that (on this x86_64 box) the compiler has unrolled the loop
11860 and is using MMX instructions to perform several multiplications
11869 .type factorial, @@function
11872 .file 1 "factorial.toy"
11880 leal -1(%rdi), %edx
11883 leal 0(,%rcx,4), %esi
11888 leal -2(%rdi), %eax
11889 movl %eax, -16(%rsp)
11890 leal -3(%rdi), %eax
11891 movd -16(%rsp), %xmm0
11892 movl %edi, -16(%rsp)
11893 movl %eax, -12(%rsp)
11894 movd -16(%rsp), %xmm1
11896 movl %edx, -16(%rsp)
11897 movd -12(%rsp), %xmm4
11898 movd -16(%rsp), %xmm6
11899 punpckldq %xmm4, %xmm0
11900 movdqa .LC1(%rip), %xmm4
11901 punpckldq %xmm6, %xmm1
11902 punpcklqdq %xmm0, %xmm1
11903 movdqa .LC0(%rip), %xmm0
11905 # etc - edited for brevity
11910 This is clearly overkill for a function that will likely overflow the
11911 @code{int} type before the vectorization is worthwhile - but then again, this
11914 Turning down the optimization level to 2:
11917 ctxt.set_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL, 2);
11922 yields this code, which is simple enough to quote in its entirety:
11929 .type factorial, @@function
11944 leal -1(%rdi), %eax
11958 .size factorial, .-factorial
11959 .ident "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-%@{gcc_release@})"
11960 .section .note.GNU-stack,"",@@progbits
11965 Note that the stack pushing and popping have been eliminated, as has the
11966 recursive call (in favor of an iteration).
11968 @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>
11969 @anchor{cp/intro/tutorial04 putting-it-all-together}@anchor{143}
11970 @subsubsection Putting it all together
11973 The complete example can be seen in the source tree at
11974 @code{gcc/jit/docs/examples/tut04-toyvm/toyvm.cc}
11976 along with a Makefile and a couple of sample .toy scripts:
11980 drwxrwxr-x. 2 david david 4096 Sep 19 17:46 .
11981 drwxrwxr-x. 3 david david 4096 Sep 19 15:26 ..
11982 -rw-rw-r--. 1 david david 615 Sep 19 12:43 factorial.toy
11983 -rw-rw-r--. 1 david david 834 Sep 19 13:08 fibonacci.toy
11984 -rw-rw-r--. 1 david david 238 Sep 19 14:22 Makefile
11985 -rw-rw-r--. 1 david david 16457 Sep 19 17:07 toyvm.cc
11988 g++ -Wall -g -o toyvm toyvm.cc -lgccjit
11990 $ ./toyvm factorial.toy 10
11991 interpreter result: 3628800
11992 compiler result: 3628800
11994 $ ./toyvm fibonacci.toy 10
11995 interpreter result: 55
11996 compiler result: 55
12001 @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>
12002 @anchor{cp/intro/tutorial04 behind-the-curtain-how-does-our-code-get-optimized}@anchor{144}
12003 @subsubsection Behind the curtain: How does our code get optimized?
12006 Our example is done, but you may be wondering about exactly how the
12007 compiler turned what we gave it into the machine code seen above.
12009 We can examine what the compiler is doing in detail by setting:
12012 state.ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING, 1);
12013 state.ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES, 1);
12018 This will dump detailed information about the compiler's state to a
12019 directory under @code{/tmp}, and keep it from being cleaned up.
12021 The precise names and their formats of these files is subject to change.
12022 Higher optimization levels lead to more files.
12023 Here's what I saw (edited for brevity; there were almost 200 files):
12026 intermediate files written to /tmp/libgccjit-KPQbGw
12027 $ ls /tmp/libgccjit-KPQbGw/
12029 fake.c.000i.type-inheritance
12031 fake.c.007t.omplower
12035 fake.c.014i.visibility
12036 fake.c.015i.early_local_cleanups
12043 The gimple code is converted into Static Single Assignment form,
12044 with annotations for use when generating the debuginfo:
12047 $ less /tmp/libgccjit-KPQbGw/fake.c.016t.ssa
12053 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
12055 factorial (signed int arg)
12057 signed int stack[8];
12058 signed int stack_depth;
12061 <unnamed type> _20;
12070 # DEBUG stack_depth => stack_depth_3
12071 stack[stack_depth_3] = arg_5(D);
12072 stack_depth_7 = stack_depth_3 + 1;
12073 # DEBUG stack_depth => stack_depth_7
12074 # DEBUG instr0 => NULL
12075 # DEBUG /* DUP */ => NULL
12076 stack_depth_8 = stack_depth_7 + -1;
12077 # DEBUG stack_depth => stack_depth_8
12078 x_9 = stack[stack_depth_8];
12080 stack[stack_depth_8] = x_9;
12081 stack_depth_11 = stack_depth_8 + 1;
12082 # DEBUG stack_depth => stack_depth_11
12083 stack[stack_depth_11] = x_9;
12084 stack_depth_13 = stack_depth_11 + 1;
12085 # DEBUG stack_depth => stack_depth_13
12086 # DEBUG instr1 => NULL
12087 # DEBUG /* PUSH_CONST */ => NULL
12088 stack[stack_depth_13] = 2;
12090 /* etc; edited for brevity */
12095 We can perhaps better see the code by turning off
12096 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} to suppress all those @code{DEBUG}
12097 statements, giving:
12100 $ less /tmp/libgccjit-1Hywc0/fake.c.016t.ssa
12106 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
12108 factorial (signed int arg)
12110 signed int stack[8];
12111 signed int stack_depth;
12114 <unnamed type> _20;
12123 stack[stack_depth_3] = arg_5(D);
12124 stack_depth_7 = stack_depth_3 + 1;
12125 stack_depth_8 = stack_depth_7 + -1;
12126 x_9 = stack[stack_depth_8];
12127 stack[stack_depth_8] = x_9;
12128 stack_depth_11 = stack_depth_8 + 1;
12129 stack[stack_depth_11] = x_9;
12130 stack_depth_13 = stack_depth_11 + 1;
12131 stack[stack_depth_13] = 2;
12132 stack_depth_15 = stack_depth_13 + 1;
12133 stack_depth_16 = stack_depth_15 + -1;
12134 y_17 = stack[stack_depth_16];
12135 stack_depth_18 = stack_depth_16 + -1;
12136 x_19 = stack[stack_depth_18];
12138 _21 = (signed int) _20;
12139 stack[stack_depth_18] = _21;
12140 stack_depth_23 = stack_depth_18 + 1;
12141 stack_depth_24 = stack_depth_23 + -1;
12142 x_25 = stack[stack_depth_24];
12144 goto <bb 4> (instr9);
12146 goto <bb 3> (instr4);
12150 stack_depth_26 = stack_depth_24 + -1;
12151 x_27 = stack[stack_depth_26];
12152 stack[stack_depth_26] = x_27;
12153 stack_depth_29 = stack_depth_26 + 1;
12154 stack[stack_depth_29] = x_27;
12155 stack_depth_31 = stack_depth_29 + 1;
12156 stack[stack_depth_31] = 1;
12157 stack_depth_33 = stack_depth_31 + 1;
12158 stack_depth_34 = stack_depth_33 + -1;
12159 y_35 = stack[stack_depth_34];
12160 stack_depth_36 = stack_depth_34 + -1;
12161 x_37 = stack[stack_depth_36];
12163 stack[stack_depth_36] = _38;
12164 stack_depth_40 = stack_depth_36 + 1;
12165 stack_depth_41 = stack_depth_40 + -1;
12166 x_42 = stack[stack_depth_41];
12167 _44 = factorial (x_42);
12168 stack[stack_depth_41] = _44;
12169 stack_depth_46 = stack_depth_41 + 1;
12170 stack_depth_47 = stack_depth_46 + -1;
12171 y_48 = stack[stack_depth_47];
12172 stack_depth_49 = stack_depth_47 + -1;
12173 x_50 = stack[stack_depth_49];
12175 stack[stack_depth_49] = _51;
12176 stack_depth_53 = stack_depth_49 + 1;
12178 # stack_depth_1 = PHI <stack_depth_24(2), stack_depth_53(3)>
12181 stack_depth_54 = stack_depth_1 + -1;
12182 x_55 = stack[stack_depth_54];
12184 stack =@{v@} @{CLOBBER@};
12192 Note in the above how all the @code{gccjit::block} instances we
12193 created have been consolidated into just 3 blocks in GCC's internal
12194 representation: @code{initial}, @code{instr4} and @code{instr9}.
12197 * Optimizing away stack manipulation: Optimizing away stack manipulation<2>.
12198 * Elimination of tail recursion: Elimination of tail recursion<2>.
12202 @node Optimizing away stack manipulation<2>,Elimination of tail recursion<2>,,Behind the curtain How does our code get optimized?<2>
12203 @anchor{cp/intro/tutorial04 optimizing-away-stack-manipulation}@anchor{145}
12204 @subsubsection Optimizing away stack manipulation
12207 Recall our simple implementation of stack operations. Let's examine
12208 how the stack operations are optimized away.
12210 After a pass of constant-propagation, the depth of the stack at each
12211 opcode can be determined at compile-time:
12214 $ less /tmp/libgccjit-1Hywc0/fake.c.021t.ccp1
12220 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
12222 factorial (signed int arg)
12224 signed int stack[8];
12225 signed int stack_depth;
12228 <unnamed type> _20;
12235 stack[0] = arg_5(D);
12243 _21 = (signed int) _20;
12247 goto <bb 4> (instr9);
12249 goto <bb 3> (instr4);
12262 _44 = factorial (x_42);
12273 stack =@{v@} @{CLOBBER@};
12281 Note how, in the above, all those @code{stack_depth} values are now just
12282 constants: we're accessing specific stack locations at each opcode.
12284 The "esra" pass ("Early Scalar Replacement of Aggregates") breaks
12285 out our "stack" array into individual elements:
12288 $ less /tmp/libgccjit-1Hywc0/fake.c.024t.esra
12294 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
12296 Created a replacement for stack offset: 0, size: 32: stack$0
12297 Created a replacement for stack offset: 32, size: 32: stack$1
12298 Created a replacement for stack offset: 64, size: 32: stack$2
12300 Symbols to be put in SSA form
12301 @{ D.89 D.90 D.91 @}
12302 Incremental SSA update started at block: 0
12303 Number of blocks in CFG: 5
12304 Number of blocks to update: 4 ( 80%)
12307 factorial (signed int arg)
12309 signed int stack$2;
12310 signed int stack$1;
12311 signed int stack$0;
12312 signed int stack[8];
12313 signed int stack_depth;
12316 <unnamed type> _20;
12323 stack$0_45 = arg_5(D);
12331 _21 = (signed int) _20;
12335 goto <bb 4> (instr9);
12337 goto <bb 3> (instr4);
12350 _44 = factorial (x_42);
12357 # stack$0_52 = PHI <stack$0_39(2), stack$0_1(3)>
12362 stack =@{v@} @{CLOBBER@};
12370 Hence at this point, all those pushes and pops of the stack are now
12371 simply assignments to specific temporary variables.
12373 After some copy propagation, the stack manipulation has been completely
12377 $ less /tmp/libgccjit-1Hywc0/fake.c.026t.copyprop1
12383 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
12385 factorial (signed int arg)
12387 signed int stack$2;
12388 signed int stack$1;
12389 signed int stack$0;
12390 signed int stack[8];
12391 signed int stack_depth;
12394 <unnamed type> _20;
12401 stack$0_39 = arg_5(D);
12402 _20 = arg_5(D) <= 1;
12403 _21 = (signed int) _20;
12405 goto <bb 4> (instr9);
12407 goto <bb 3> (instr4);
12411 _38 = arg_5(D) + -1;
12412 _44 = factorial (_38);
12413 _51 = arg_5(D) * _44;
12416 # stack$0_52 = PHI <arg_5(D)(2), _51(3)>
12419 stack =@{v@} @{CLOBBER@};
12427 Later on, another pass finally eliminated @code{stack_depth} local and the
12428 unused parts of the @cite{stack`} array altogether:
12431 $ less /tmp/libgccjit-1Hywc0/fake.c.036t.release_ssa
12437 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
12439 Released 44 names, 314.29%, removed 44 holes
12440 factorial (signed int arg)
12442 signed int stack$0;
12443 signed int mult_acc_1;
12447 signed int mul_tmp_10;
12448 signed int mult_acc_11;
12449 signed int mult_acc_13;
12451 # arg_9 = PHI <arg_8(D)(0)>
12452 # mult_acc_13 = PHI <1(0)>
12456 # arg_4 = PHI <arg_9(2), _7(3)>
12457 # mult_acc_1 = PHI <mult_acc_13(2), mult_acc_11(3)>
12459 _6 = (signed int) _5;
12461 goto <bb 4> (instr9);
12463 goto <bb 3> (instr4);
12468 mult_acc_11 = mult_acc_1 * arg_4;
12471 # stack$0_12 = PHI <arg_4(5)>
12474 mul_tmp_10 = mult_acc_1 * stack$0_12;
12482 @node Elimination of tail recursion<2>,,Optimizing away stack manipulation<2>,Behind the curtain How does our code get optimized?<2>
12483 @anchor{cp/intro/tutorial04 elimination-of-tail-recursion}@anchor{146}
12484 @subsubsection Elimination of tail recursion
12487 Another significant optimization is the detection that the call to
12488 @code{factorial} is tail recursion, which can be eliminated in favor of
12492 $ less /tmp/libgccjit-1Hywc0/fake.c.030t.tailr1
12498 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
12501 Symbols to be put in SSA form
12503 Incremental SSA update started at block: 0
12504 Number of blocks in CFG: 5
12505 Number of blocks to update: 4 ( 80%)
12508 factorial (signed int arg)
12510 signed int stack$2;
12511 signed int stack$1;
12512 signed int stack$0;
12513 signed int stack[8];
12514 signed int stack_depth;
12517 signed int mult_acc_1;
12518 <unnamed type> _20;
12521 signed int mul_tmp_44;
12522 signed int mult_acc_51;
12524 # arg_5 = PHI <arg_39(D)(0), _38(3)>
12525 # mult_acc_1 = PHI <1(0), mult_acc_51(3)>
12528 _21 = (signed int) _20;
12530 goto <bb 4> (instr9);
12532 goto <bb 3> (instr4);
12537 mult_acc_51 = mult_acc_1 * arg_5;
12538 goto <bb 2> (initial);
12540 # stack$0_52 = PHI <arg_5(2)>
12543 stack =@{v@} @{CLOBBER@};
12544 mul_tmp_44 = mult_acc_1 * stack$0_52;
12552 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
12553 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
12555 @c This is free software: you can redistribute it and/or modify it
12556 @c under the terms of the GNU General Public License as published by
12557 @c the Free Software Foundation, either version 3 of the License, or
12558 @c (at your option) any later version.
12560 @c This program is distributed in the hope that it will be useful, but
12561 @c WITHOUT ANY WARRANTY; without even the implied warranty of
12562 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12563 @c General Public License for more details.
12565 @c You should have received a copy of the GNU General Public License
12566 @c along with this program. If not, see
12567 @c <http://www.gnu.org/licenses/>.
12569 @node Topic Reference<2>,,Tutorial<2>,C++ bindings for libgccjit
12570 @anchor{cp/topics/index doc}@anchor{147}@anchor{cp/topics/index topic-reference}@anchor{148}
12571 @section Topic Reference
12574 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
12575 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
12577 @c This is free software: you can redistribute it and/or modify it
12578 @c under the terms of the GNU General Public License as published by
12579 @c the Free Software Foundation, either version 3 of the License, or
12580 @c (at your option) any later version.
12582 @c This program is distributed in the hope that it will be useful, but
12583 @c WITHOUT ANY WARRANTY; without even the implied warranty of
12584 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12585 @c General Public License for more details.
12587 @c You should have received a copy of the GNU General Public License
12588 @c along with this program. If not, see
12589 @c <http://www.gnu.org/licenses/>.
12592 * Compilation contexts: Compilation contexts<2>.
12593 * Objects: Objects<2>.
12595 * Expressions: Expressions<2>.
12596 * Creating and using functions: Creating and using functions<2>.
12597 * Source Locations: Source Locations<2>.
12598 * Compiling a context: Compiling a context<2>.
12600 Compilation contexts
12602 * Lifetime-management: Lifetime-management<2>.
12603 * Thread-safety: Thread-safety<2>.
12604 * Error-handling: Error-handling<3>.
12605 * Debugging: Debugging<2>.
12606 * Options: Options<4>.
12610 * String Options: String Options<2>.
12611 * Boolean options: Boolean options<2>.
12612 * Integer options: Integer options<2>.
12613 * Additional command-line options: Additional command-line options<2>.
12617 * Standard types: Standard types<2>.
12618 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile<2>.
12619 * Vector types: Vector types<2>.
12620 * Structures and unions: Structures and unions<2>.
12624 * Rvalues: Rvalues<2>.
12625 * Lvalues: Lvalues<2>.
12626 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions<2>.
12630 * Simple expressions: Simple expressions<2>.
12631 * Vector expressions: Vector expressions<2>.
12632 * Unary Operations: Unary Operations<2>.
12633 * Binary Operations: Binary Operations<2>.
12634 * Comparisons: Comparisons<2>.
12635 * Function calls: Function calls<2>.
12636 * Function pointers: Function pointers<3>.
12637 * Type-coercion: Type-coercion<2>.
12641 * Global variables: Global variables<2>.
12643 Creating and using functions
12645 * Params: Params<2>.
12646 * Functions: Functions<2>.
12647 * Blocks: Blocks<2>.
12648 * Statements: Statements<2>.
12652 * Faking it: Faking it<2>.
12654 Compiling a context
12656 * In-memory compilation: In-memory compilation<2>.
12657 * Ahead-of-time compilation: Ahead-of-time compilation<2>.
12662 @node Compilation contexts<2>,Objects<2>,,Topic Reference<2>
12663 @anchor{cp/topics/contexts compilation-contexts}@anchor{149}@anchor{cp/topics/contexts doc}@anchor{14a}
12664 @subsection Compilation contexts
12667 @geindex gccjit;;context (C++ class)
12668 @anchor{cp/topics/contexts gccjit context}@anchor{14b}
12669 @deffn {C++ Class} gccjit::context
12672 The top-level of the C++ API is the @pxref{14b,,gccjit;;context} type.
12674 A @pxref{14b,,gccjit;;context} instance encapsulates the state of a
12677 You can set up options on it, and add types, functions and code.
12678 Invoking @pxref{124,,gccjit;;context;;compile()} on it gives you a
12679 @pxref{16,,gcc_jit_result *}.
12681 It is a thin wrapper around the C API's @pxref{8,,gcc_jit_context *}.
12684 * Lifetime-management: Lifetime-management<2>.
12685 * Thread-safety: Thread-safety<2>.
12686 * Error-handling: Error-handling<3>.
12687 * Debugging: Debugging<2>.
12688 * Options: Options<4>.
12692 @node Lifetime-management<2>,Thread-safety<2>,,Compilation contexts<2>
12693 @anchor{cp/topics/contexts lifetime-management}@anchor{14c}
12694 @subsubsection Lifetime-management
12697 Contexts are the unit of lifetime-management within the API: objects
12698 have their lifetime bounded by the context they are created within, and
12699 cleanup of such objects is done for you when the context is released.
12701 @geindex gccjit;;context;;acquire (C++ function)
12702 @anchor{cp/topics/contexts gccjit context acquire}@anchor{11e}
12703 @deffn {C++ Function} gccjit::context gccjit::context::acquire ()
12705 This function acquires a new @pxref{14b,,gccjit;;context} instance,
12706 which is independent of any others that may be present within this
12710 @geindex gccjit;;context;;release (C++ function)
12711 @anchor{cp/topics/contexts gccjit context release}@anchor{120}
12712 @deffn {C++ Function} void gccjit::context::release ()
12714 This function releases all resources associated with the given context.
12715 Both the context itself and all of its @code{gccjit::object *}
12716 instances are cleaned up. It should be called exactly once on a given
12719 It is invalid to use the context or any of its "contextual" objects
12720 after calling this.
12729 @geindex gccjit;;context;;new_child_context (C++ function)
12730 @anchor{cp/topics/contexts gccjit context new_child_context}@anchor{14d}
12731 @deffn {C++ Function} gccjit::context gccjit::context::new_child_context ()
12733 Given an existing JIT context, create a child context.
12735 The child inherits a copy of all option-settings from the parent.
12737 The child can reference objects created within the parent, but not
12740 The lifetime of the child context must be bounded by that of the
12741 parent: you should release a child context before releasing the parent
12744 If you use a function from a parent context within a child context,
12745 you have to compile the parent context before you can compile the
12746 child context, and the gccjit::result of the parent context must
12747 outlive the gccjit::result of the child context.
12749 This allows caching of shared initializations. For example, you could
12750 create types and declarations of global functions in a parent context
12751 once within a process, and then create child contexts whenever a
12752 function or loop becomes hot. Each such child context can be used for
12753 JIT-compiling just one function or loop, but can reference types
12754 and helper functions created within the parent context.
12756 Contexts can be arbitrarily nested, provided the above rules are
12757 followed, but it's probably not worth going above 2 or 3 levels, and
12758 there will likely be a performance hit for such nesting.
12761 @node Thread-safety<2>,Error-handling<3>,Lifetime-management<2>,Compilation contexts<2>
12762 @anchor{cp/topics/contexts thread-safety}@anchor{14e}
12763 @subsubsection Thread-safety
12766 Instances of @pxref{14b,,gccjit;;context} created via
12767 @pxref{11e,,gccjit;;context;;acquire()} are independent from each other:
12768 only one thread may use a given context at once, but multiple threads
12769 could each have their own contexts without needing locks.
12771 Contexts created via @pxref{14d,,gccjit;;context;;new_child_context()} are
12772 related to their parent context. They can be partitioned by their
12773 ultimate ancestor into independent "family trees". Only one thread
12774 within a process may use a given "family tree" of such contexts at once,
12775 and if you're using multiple threads you should provide your own locking
12776 around entire such context partitions.
12778 @node Error-handling<3>,Debugging<2>,Thread-safety<2>,Compilation contexts<2>
12779 @anchor{cp/topics/contexts error-handling}@anchor{14f}
12780 @subsubsection Error-handling
12783 @c FIXME: How does error-handling work for C++ API?
12785 You can only compile and get code from a context if no errors occur.
12787 In general, if an error occurs when using an API entrypoint, it returns
12788 NULL. You don't have to check everywhere for NULL results, since the
12789 API gracefully handles a NULL being passed in for any argument.
12791 Errors are printed on stderr and can be queried using
12792 @pxref{150,,gccjit;;context;;get_first_error()}.
12794 @geindex gccjit;;context;;get_first_error (C++ function)
12795 @anchor{cp/topics/contexts gccjit context get_first_error__gccjit contextP}@anchor{150}
12796 @deffn {C++ Function} const char* gccjit::context::get_first_error (gccjit::context* ctxt)
12798 Returns the first error message that occurred on the context.
12800 The returned string is valid for the rest of the lifetime of the
12803 If no errors occurred, this will be NULL.
12806 @node Debugging<2>,Options<4>,Error-handling<3>,Compilation contexts<2>
12807 @anchor{cp/topics/contexts debugging}@anchor{151}
12808 @subsubsection Debugging
12811 @geindex gccjit;;context;;dump_to_file (C++ function)
12812 @anchor{cp/topics/contexts gccjit context dump_to_file__ssCR i}@anchor{152}
12813 @deffn {C++ Function} void gccjit::context::dump_to_file (const std::string& path, int update_locations)
12815 To help with debugging: dump a C-like representation to the given path,
12816 describing what's been set up on the context.
12818 If "update_locations" is true, then also set up @pxref{153,,gccjit;;location}
12819 information throughout the context, pointing at the dump file as if it
12820 were a source file. This may be of use in conjunction with
12821 @code{GCCJIT::BOOL_OPTION_DEBUGINFO} to allow stepping through the
12822 code in a debugger.
12825 @geindex gccjit;;context;;dump_reproducer_to_file (C++ function)
12826 @anchor{cp/topics/contexts gccjit context dump_reproducer_to_file__gcc_jit_contextP cCP}@anchor{154}
12827 @deffn {C++ Function} void gccjit::context::dump_reproducer_to_file (gcc_jit_context* ctxt, const char* path)
12829 This is a thin wrapper around the C API
12830 @pxref{5d,,gcc_jit_context_dump_reproducer_to_file()}, and hence works the
12833 Note that the generated source is C code, not C++; this might be of use
12834 for seeing what the C++ bindings are doing at the C level.
12837 @node Options<4>,,Debugging<2>,Compilation contexts<2>
12838 @anchor{cp/topics/contexts options}@anchor{155}
12839 @subsubsection Options
12843 * String Options: String Options<2>.
12844 * Boolean options: Boolean options<2>.
12845 * Integer options: Integer options<2>.
12846 * Additional command-line options: Additional command-line options<2>.
12850 @node String Options<2>,Boolean options<2>,,Options<4>
12851 @anchor{cp/topics/contexts string-options}@anchor{156}
12852 @subsubsection String Options
12855 @geindex gccjit;;context;;set_str_option (C++ function)
12856 @anchor{cp/topics/contexts gccjit context set_str_option__enum cCP}@anchor{157}
12857 @deffn {C++ Function} void gccjit::context::set_str_option (enum gcc_jit_str_option, const char* value)
12859 Set a string option of the context.
12861 This is a thin wrapper around the C API
12862 @pxref{61,,gcc_jit_context_set_str_option()}; the options have the same
12866 @node Boolean options<2>,Integer options<2>,String Options<2>,Options<4>
12867 @anchor{cp/topics/contexts boolean-options}@anchor{158}
12868 @subsubsection Boolean options
12871 @geindex gccjit;;context;;set_bool_option (C++ function)
12872 @anchor{cp/topics/contexts gccjit context set_bool_option__enum i}@anchor{126}
12873 @deffn {C++ Function} void gccjit::context::set_bool_option (enum gcc_jit_bool_option, int value)
12875 Set a boolean option of the context.
12877 This is a thin wrapper around the C API
12878 @pxref{1b,,gcc_jit_context_set_bool_option()}; the options have the same
12882 @geindex gccjit;;context;;set_bool_allow_unreachable_blocks (C++ function)
12883 @anchor{cp/topics/contexts gccjit context set_bool_allow_unreachable_blocks__i}@anchor{159}
12884 @deffn {C++ Function} void gccjit::context::set_bool_allow_unreachable_blocks (int bool_value)
12886 By default, libgccjit will issue an error about unreachable blocks
12889 This entrypoint can be used to disable that error; it is a thin wrapper
12891 @pxref{6b,,gcc_jit_context_set_bool_allow_unreachable_blocks()}.
12893 This entrypoint was added in @pxref{6c,,LIBGCCJIT_ABI_2}; you can test for
12897 #ifdef LIBGCCJIT_HAVE_gcc_jit_context_set_bool_allow_unreachable_blocks
12903 @geindex gccjit;;context;;set_bool_use_external_driver (C++ function)
12904 @anchor{cp/topics/contexts gccjit context set_bool_use_external_driver__i}@anchor{15a}
12905 @deffn {C++ Function} void gccjit::context::set_bool_use_external_driver (int bool_value)
12907 libgccjit internally generates assembler, and uses "driver" code
12908 for converting it to other formats (e.g. shared libraries).
12910 By default, libgccjit will use an embedded copy of the driver
12913 This option can be used to instead invoke an external driver executable
12914 as a subprocess; it is a thin wrapper around the C API
12915 @pxref{6d,,gcc_jit_context_set_bool_use_external_driver()}.
12917 This entrypoint was added in @pxref{6e,,LIBGCCJIT_ABI_5}; you can test for
12921 #ifdef LIBGCCJIT_HAVE_gcc_jit_context_set_bool_use_external_driver
12927 @node Integer options<2>,Additional command-line options<2>,Boolean options<2>,Options<4>
12928 @anchor{cp/topics/contexts integer-options}@anchor{15b}
12929 @subsubsection Integer options
12932 @geindex gccjit;;context;;set_int_option (C++ function)
12933 @anchor{cp/topics/contexts gccjit context set_int_option__enum i}@anchor{127}
12934 @deffn {C++ Function} void gccjit::context::set_int_option (enum gcc_jit_int_option, int value)
12936 Set an integer option of the context.
12938 This is a thin wrapper around the C API
12939 @pxref{1e,,gcc_jit_context_set_int_option()}; the options have the same
12943 @node Additional command-line options<2>,,Integer options<2>,Options<4>
12944 @anchor{cp/topics/contexts additional-command-line-options}@anchor{15c}
12945 @subsubsection Additional command-line options
12948 @geindex gccjit;;context;;add_command_line_option (C++ function)
12949 @anchor{cp/topics/contexts gccjit context add_command_line_option__cCP}@anchor{15d}
12950 @deffn {C++ Function} void gccjit::context::add_command_line_option (const char* optname)
12952 Add an arbitrary gcc command-line option to the context for use
12955 This is a thin wrapper around the C API
12956 @pxref{72,,gcc_jit_context_add_command_line_option()}.
12958 This entrypoint was added in @pxref{73,,LIBGCCJIT_ABI_1}; you can test for
12962 #ifdef LIBGCCJIT_HAVE_gcc_jit_context_add_command_line_option
12968 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
12969 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
12971 @c This is free software: you can redistribute it and/or modify it
12972 @c under the terms of the GNU General Public License as published by
12973 @c the Free Software Foundation, either version 3 of the License, or
12974 @c (at your option) any later version.
12976 @c This program is distributed in the hope that it will be useful, but
12977 @c WITHOUT ANY WARRANTY; without even the implied warranty of
12978 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12979 @c General Public License for more details.
12981 @c You should have received a copy of the GNU General Public License
12982 @c along with this program. If not, see
12983 @c <http://www.gnu.org/licenses/>.
12985 @node Objects<2>,Types<2>,Compilation contexts<2>,Topic Reference<2>
12986 @anchor{cp/topics/objects objects}@anchor{15e}@anchor{cp/topics/objects doc}@anchor{15f}
12987 @subsection Objects
12990 @geindex gccjit;;object (C++ class)
12991 @anchor{cp/topics/objects gccjit object}@anchor{160}
12992 @deffn {C++ Class} gccjit::object
12995 Almost every entity in the API (with the exception of
12996 @pxref{14b,,gccjit;;context} and @pxref{16,,gcc_jit_result *}) is a
12997 "contextual" object, a @pxref{160,,gccjit;;object}.
13007 is associated with a @pxref{14b,,gccjit;;context}.
13010 is automatically cleaned up for you when its context is released so
13011 you don't need to manually track and cleanup all objects, just the
13016 The C++ class hierarchy within the @code{gccjit} namespace looks like this:
13034 The @pxref{160,,gccjit;;object} base class has the following operations:
13036 @geindex gccjit;;object;;get_context (C++ function)
13037 @anchor{cp/topics/objects gccjit object get_contextC}@anchor{161}
13038 @deffn {C++ Function} gccjit::context gccjit::object::get_context () const
13040 Which context is the obj within?
13043 @geindex gccjit;;object;;get_debug_string (C++ function)
13044 @anchor{cp/topics/objects gccjit object get_debug_stringC}@anchor{121}
13045 @deffn {C++ Function} std::string gccjit::object::get_debug_string () const
13047 Generate a human-readable description for the given object.
13052 printf ("obj: %s\n", obj.get_debug_string ().c_str ());
13057 might give this text on stdout:
13060 obj: 4.0 * (float)i
13066 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
13067 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
13069 @c This is free software: you can redistribute it and/or modify it
13070 @c under the terms of the GNU General Public License as published by
13071 @c the Free Software Foundation, either version 3 of the License, or
13072 @c (at your option) any later version.
13074 @c This program is distributed in the hope that it will be useful, but
13075 @c WITHOUT ANY WARRANTY; without even the implied warranty of
13076 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13077 @c General Public License for more details.
13079 @c You should have received a copy of the GNU General Public License
13080 @c along with this program. If not, see
13081 @c <http://www.gnu.org/licenses/>.
13083 @node Types<2>,Expressions<2>,Objects<2>,Topic Reference<2>
13084 @anchor{cp/topics/types doc}@anchor{162}@anchor{cp/topics/types types}@anchor{163}
13088 @geindex gccjit;;type (C++ class)
13089 @anchor{cp/topics/types gccjit type}@anchor{164}
13090 @deffn {C++ Class} gccjit::type
13092 gccjit::type represents a type within the library. It is a subclass
13093 of @pxref{160,,gccjit;;object}.
13096 Types can be created in several ways:
13102 fundamental types can be accessed using
13103 @pxref{11f,,gccjit;;context;;get_type()}:
13106 gccjit::type int_type = ctxt.get_type (GCC_JIT_TYPE_INT);
13111 or using the @code{gccjit::context::get_int_type} template:
13114 gccjit::type t = ctxt.get_int_type <unsigned short> ();
13119 See @pxref{b,,gcc_jit_context_get_type()} for the available types.
13122 derived types can be accessed by using functions such as
13123 @pxref{165,,gccjit;;type;;get_pointer()} and @pxref{166,,gccjit;;type;;get_const()}:
13126 gccjit::type const_int_star = int_type.get_const ().get_pointer ();
13127 gccjit::type int_const_star = int_type.get_pointer ().get_const ();
13133 by creating structures (see below).
13137 * Standard types: Standard types<2>.
13138 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile<2>.
13139 * Vector types: Vector types<2>.
13140 * Structures and unions: Structures and unions<2>.
13144 @node Standard types<2>,Pointers const and volatile<2>,,Types<2>
13145 @anchor{cp/topics/types standard-types}@anchor{167}
13146 @subsubsection Standard types
13149 @geindex gccjit;;context;;get_type (C++ function)
13150 @anchor{cp/topics/types gccjit context get_type__enum}@anchor{11f}
13151 @deffn {C++ Function} gccjit::type gccjit::context::get_type (enum gcc_jit_types)
13153 Access a specific type. This is a thin wrapper around
13154 @pxref{b,,gcc_jit_context_get_type()}; the parameter has the same meaning.
13157 @geindex gccjit;;context;;get_int_type (C++ function)
13158 @anchor{cp/topics/types gccjit context get_int_type__s i}@anchor{168}
13159 @deffn {C++ Function} gccjit::type gccjit::context::get_int_type (size_t num_bytes, int is_signed)
13161 Access the integer type of the given size.
13164 @geindex gccjit;;context;;get_int_type<T> (C++ function)
13165 @anchor{cp/topics/types gccjit context get_int_type T}@anchor{169}
13166 @deffn {C++ Function} gccjit::type gccjit::context::get_int_type<T> ()
13168 Access the given integer type. For example, you could map the
13169 @code{unsigned short} type into a gccjit::type via:
13172 gccjit::type t = ctxt.get_int_type <unsigned short> ();
13178 @node Pointers const and volatile<2>,Vector types<2>,Standard types<2>,Types<2>
13179 @anchor{cp/topics/types pointers-const-and-volatile}@anchor{16a}
13180 @subsubsection Pointers, @cite{const}, and @cite{volatile}
13183 @geindex gccjit;;type;;get_pointer (C++ function)
13184 @anchor{cp/topics/types gccjit type get_pointer}@anchor{165}
13185 @deffn {C++ Function} gccjit::type gccjit::type::get_pointer ()
13187 Given type "T", get type "T*".
13190 @geindex gccjit;;type;;get_const (C++ function)
13191 @anchor{cp/topics/types gccjit type get_const}@anchor{166}
13192 @deffn {C++ Function} gccjit::type gccjit::type::get_const ()
13194 Given type "T", get type "const T".
13197 @geindex gccjit;;type;;get_volatile (C++ function)
13198 @anchor{cp/topics/types gccjit type get_volatile}@anchor{16b}
13199 @deffn {C++ Function} gccjit::type gccjit::type::get_volatile ()
13201 Given type "T", get type "volatile T".
13204 @geindex gccjit;;type;;get_aligned (C++ function)
13205 @anchor{cp/topics/types gccjit type get_aligned__s}@anchor{16c}
13206 @deffn {C++ Function} gccjit::type gccjit::type::get_aligned (size_t alignment_in_bytes)
13208 Given type "T", get type:
13211 T __attribute__ ((aligned (ALIGNMENT_IN_BYTES)))
13216 The alignment must be a power of two.
13219 @geindex gccjit;;context;;new_array_type (C++ function)
13220 @anchor{cp/topics/types gccjit context new_array_type__gccjit type i gccjit location}@anchor{16d}
13221 @deffn {C++ Function} gccjit::type gccjit::context::new_array_type (gccjit::type element_type, int num_elements, gccjit::location loc)
13223 Given type "T", get type "T[N]" (for a constant N).
13224 Param "loc" is optional.
13227 @node Vector types<2>,Structures and unions<2>,Pointers const and volatile<2>,Types<2>
13228 @anchor{cp/topics/types vector-types}@anchor{16e}
13229 @subsubsection Vector types
13232 @geindex gccjit;;type;;get_vector (C++ function)
13233 @anchor{cp/topics/types gccjit type get_vector__s}@anchor{16f}
13234 @deffn {C++ Function} gccjit::type gccjit::type::get_vector (size_t num_units)
13236 Given type "T", get type:
13239 T __attribute__ ((vector_size (sizeof(T) * num_units))
13244 T must be integral or floating point; num_units must be a power of two.
13247 @node Structures and unions<2>,,Vector types<2>,Types<2>
13248 @anchor{cp/topics/types structures-and-unions}@anchor{170}
13249 @subsubsection Structures and unions
13252 @geindex gccjit;;struct_ (C++ class)
13253 @anchor{cp/topics/types gccjit struct_}@anchor{171}
13254 @deffn {C++ Class} gccjit::struct_
13257 A compound type analagous to a C @cite{struct}.
13259 @pxref{171,,gccjit;;struct_} is a subclass of @pxref{164,,gccjit;;type} (and thus
13260 of @pxref{160,,gccjit;;object} in turn).
13262 @geindex gccjit;;field (C++ class)
13263 @anchor{cp/topics/types gccjit field}@anchor{172}
13264 @deffn {C++ Class} gccjit::field
13267 A field within a @pxref{171,,gccjit;;struct_}.
13269 @pxref{172,,gccjit;;field} is a subclass of @pxref{160,,gccjit;;object}.
13271 You can model C @cite{struct} types by creating @pxref{171,,gccjit;;struct_} and
13272 @pxref{172,,gccjit;;field} instances, in either order:
13278 by creating the fields, then the structure. For example, to model:
13281 struct coord @{double x; double y; @};
13289 gccjit::field field_x = ctxt.new_field (double_type, "x");
13290 gccjit::field field_y = ctxt.new_field (double_type, "y");
13291 std::vector fields;
13292 fields.push_back (field_x);
13293 fields.push_back (field_y);
13294 gccjit::struct_ coord = ctxt.new_struct_type ("coord", fields);
13300 by creating the structure, then populating it with fields, typically
13301 to allow modelling self-referential structs such as:
13304 struct node @{ int m_hash; struct node *m_next; @};
13312 gccjit::struct_ node = ctxt.new_opaque_struct_type ("node");
13313 gccjit::type node_ptr = node.get_pointer ();
13314 gccjit::field field_hash = ctxt.new_field (int_type, "m_hash");
13315 gccjit::field field_next = ctxt.new_field (node_ptr, "m_next");
13316 std::vector fields;
13317 fields.push_back (field_hash);
13318 fields.push_back (field_next);
13319 node.set_fields (fields);
13325 @c FIXME: the above API doesn't seem to exist yet
13327 @geindex gccjit;;context;;new_field (C++ function)
13328 @anchor{cp/topics/types gccjit context new_field__gccjit type cCP gccjit location}@anchor{173}
13329 @deffn {C++ Function} gccjit::field gccjit::context::new_field (gccjit::type type, const char* name, gccjit::location loc)
13331 Construct a new field, with the given type and name.
13334 @geindex gccjit;;context;;new_struct_type (C++ function)
13335 @anchor{cp/topics/types gccjit context new_struct_type__ssCR std vector field R gccjit location}@anchor{174}
13336 @deffn {C++ Function} gccjit::struct_ gccjit::context::new_struct_type (const std::string& name, std::vector<field>& fields, gccjit::location loc)
13340 Construct a new struct type, with the given name and fields.
13344 @geindex gccjit;;context;;new_opaque_struct (C++ function)
13345 @anchor{cp/topics/types gccjit context new_opaque_struct__ssCR gccjit location}@anchor{175}
13346 @deffn {C++ Function} gccjit::struct_ gccjit::context::new_opaque_struct (const std::string& name, gccjit::location loc)
13348 Construct a new struct type, with the given name, but without
13349 specifying the fields. The fields can be omitted (in which case the
13350 size of the struct is not known), or later specified using
13351 @pxref{8d,,gcc_jit_struct_set_fields()}.
13354 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
13355 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
13357 @c This is free software: you can redistribute it and/or modify it
13358 @c under the terms of the GNU General Public License as published by
13359 @c the Free Software Foundation, either version 3 of the License, or
13360 @c (at your option) any later version.
13362 @c This program is distributed in the hope that it will be useful, but
13363 @c WITHOUT ANY WARRANTY; without even the implied warranty of
13364 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13365 @c General Public License for more details.
13367 @c You should have received a copy of the GNU General Public License
13368 @c along with this program. If not, see
13369 @c <http://www.gnu.org/licenses/>.
13371 @node Expressions<2>,Creating and using functions<2>,Types<2>,Topic Reference<2>
13372 @anchor{cp/topics/expressions expressions}@anchor{176}@anchor{cp/topics/expressions doc}@anchor{177}
13373 @subsection Expressions
13377 * Rvalues: Rvalues<2>.
13378 * Lvalues: Lvalues<2>.
13379 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions<2>.
13383 * Simple expressions: Simple expressions<2>.
13384 * Vector expressions: Vector expressions<2>.
13385 * Unary Operations: Unary Operations<2>.
13386 * Binary Operations: Binary Operations<2>.
13387 * Comparisons: Comparisons<2>.
13388 * Function calls: Function calls<2>.
13389 * Function pointers: Function pointers<3>.
13390 * Type-coercion: Type-coercion<2>.
13394 * Global variables: Global variables<2>.
13399 @node Rvalues<2>,Lvalues<2>,,Expressions<2>
13400 @anchor{cp/topics/expressions rvalues}@anchor{178}
13401 @subsubsection Rvalues
13404 @geindex gccjit;;rvalue (C++ class)
13405 @anchor{cp/topics/expressions gccjit rvalue}@anchor{179}
13406 @deffn {C++ Class} gccjit::rvalue
13409 A @pxref{179,,gccjit;;rvalue} is an expression that can be computed. It is a
13410 subclass of @pxref{160,,gccjit;;object}, and is a thin wrapper around
13411 @pxref{13,,gcc_jit_rvalue *} from the C API.
13413 It can be simple, e.g.:
13421 an integer value e.g. @cite{0} or @cite{42}
13424 a string literal e.g. @cite{"Hello world"}
13427 a variable e.g. @cite{i}. These are also lvalues (see below).
13439 a unary expression e.g. @cite{!cond}
13442 a binary expression e.g. @cite{(a + b)}
13445 a function call e.g. @cite{get_distance (&player_ship@comma{} &target)}
13452 Every rvalue has an associated type, and the API will check to ensure
13453 that types match up correctly (otherwise the context will emit an error).
13455 @geindex gccjit;;rvalue;;get_type (C++ function)
13456 @anchor{cp/topics/expressions gccjit rvalue get_type}@anchor{17a}
13457 @deffn {C++ Function} gccjit::type gccjit::rvalue::get_type ()
13459 Get the type of this rvalue.
13463 * Simple expressions: Simple expressions<2>.
13464 * Vector expressions: Vector expressions<2>.
13465 * Unary Operations: Unary Operations<2>.
13466 * Binary Operations: Binary Operations<2>.
13467 * Comparisons: Comparisons<2>.
13468 * Function calls: Function calls<2>.
13469 * Function pointers: Function pointers<3>.
13470 * Type-coercion: Type-coercion<2>.
13474 @node Simple expressions<2>,Vector expressions<2>,,Rvalues<2>
13475 @anchor{cp/topics/expressions simple-expressions}@anchor{17b}
13476 @subsubsection Simple expressions
13479 @geindex gccjit;;context;;new_rvalue (C++ function)
13480 @anchor{cp/topics/expressions gccjit context new_rvalue__gccjit type iC}@anchor{133}
13481 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (gccjit::type numeric_type, int value) const
13483 Given a numeric type (integer or floating point), build an rvalue for
13484 the given constant @code{int} value.
13487 @geindex gccjit;;context;;new_rvalue (C++ function)
13488 @anchor{cp/topics/expressions gccjit context new_rvalue__gccjit type lC}@anchor{17c}
13489 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (gccjit::type numeric_type, long value) const
13491 Given a numeric type (integer or floating point), build an rvalue for
13492 the given constant @code{long} value.
13495 @geindex gccjit;;context;;zero (C++ function)
13496 @anchor{cp/topics/expressions gccjit context zero__gccjit typeC}@anchor{12f}
13497 @deffn {C++ Function} gccjit::rvalue gccjit::context::zero (gccjit::type numeric_type) const
13499 Given a numeric type (integer or floating point), get the rvalue for
13500 zero. Essentially this is just a shortcut for:
13503 ctxt.new_rvalue (numeric_type, 0)
13509 @geindex gccjit;;context;;one (C++ function)
13510 @anchor{cp/topics/expressions gccjit context one__gccjit typeC}@anchor{17d}
13511 @deffn {C++ Function} gccjit::rvalue gccjit::context::one (gccjit::type numeric_type) const
13513 Given a numeric type (integer or floating point), get the rvalue for
13514 one. Essentially this is just a shortcut for:
13517 ctxt.new_rvalue (numeric_type, 1)
13523 @geindex gccjit;;context;;new_rvalue (C++ function)
13524 @anchor{cp/topics/expressions gccjit context new_rvalue__gccjit type doubleC}@anchor{17e}
13525 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (gccjit::type numeric_type, double value) const
13527 Given a numeric type (integer or floating point), build an rvalue for
13528 the given constant @code{double} value.
13531 @geindex gccjit;;context;;new_rvalue (C++ function)
13532 @anchor{cp/topics/expressions gccjit context new_rvalue__gccjit type voidPC}@anchor{17f}
13533 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (gccjit::type pointer_type, void* value) const
13535 Given a pointer type, build an rvalue for the given address.
13538 @geindex gccjit;;context;;new_rvalue (C++ function)
13539 @anchor{cp/topics/expressions gccjit context new_rvalue__ssCRC}@anchor{180}
13540 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (const std::string& value) const
13542 Generate an rvalue of type @code{GCC_JIT_TYPE_CONST_CHAR_PTR} for
13543 the given string. This is akin to a string literal.
13546 @node Vector expressions<2>,Unary Operations<2>,Simple expressions<2>,Rvalues<2>
13547 @anchor{cp/topics/expressions vector-expressions}@anchor{181}
13548 @subsubsection Vector expressions
13551 @geindex gccjit;;context;;new_rvalue (C++ function)
13552 @anchor{cp/topics/expressions gccjit context new_rvalue__gccjit type std vector gccjit rvalue C}@anchor{182}
13553 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (gccjit::type vector_type, std::vector<gccjit::rvalue> elements) const
13555 Given a vector type, and a vector of scalar rvalue elements, generate a
13558 The number of elements needs to match that of the vector type.
13561 @node Unary Operations<2>,Binary Operations<2>,Vector expressions<2>,Rvalues<2>
13562 @anchor{cp/topics/expressions unary-operations}@anchor{183}
13563 @subsubsection Unary Operations
13566 @geindex gccjit;;context;;new_unary_op (C++ function)
13567 @anchor{cp/topics/expressions gccjit context new_unary_op__enum gccjit type gccjit rvalue gccjit location}@anchor{184}
13568 @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)
13570 Build a unary operation out of an input rvalue.
13572 Parameter @code{loc} is optional.
13574 This is a thin wrapper around the C API's
13575 @pxref{9e,,gcc_jit_context_new_unary_op()} and the available unary
13576 operations are documented there.
13579 There are shorter ways to spell the various specific kinds of unary
13582 @geindex gccjit;;context;;new_minus (C++ function)
13583 @anchor{cp/topics/expressions gccjit context new_minus__gccjit type gccjit rvalue gccjit location}@anchor{185}
13584 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_minus (gccjit::type result_type, gccjit::rvalue a, gccjit::location loc)
13586 Negate an arithmetic value; for example:
13589 gccjit::rvalue negpi = ctxt.new_minus (t_double, pi);
13594 builds the equivalent of this C expression:
13603 @geindex new_bitwise_negate (C++ function)
13604 @anchor{cp/topics/expressions new_bitwise_negate__gccjit type gccjit rvalue gccjit location}@anchor{186}
13605 @deffn {C++ Function} gccjit::rvalue new_bitwise_negate (gccjit::type result_type, gccjit::rvalue a, gccjit::location loc)
13607 Bitwise negation of an integer value (one's complement); for example:
13610 gccjit::rvalue mask = ctxt.new_bitwise_negate (t_int, a);
13615 builds the equivalent of this C expression:
13624 @geindex new_logical_negate (C++ function)
13625 @anchor{cp/topics/expressions new_logical_negate__gccjit type gccjit rvalue gccjit location}@anchor{187}
13626 @deffn {C++ Function} gccjit::rvalue new_logical_negate (gccjit::type result_type, gccjit::rvalue a, gccjit::location loc)
13628 Logical negation of an arithmetic or pointer value; for example:
13631 gccjit::rvalue guard = ctxt.new_logical_negate (t_bool, cond);
13636 builds the equivalent of this C expression:
13645 The most concise way to spell them is with overloaded operators:
13647 @geindex operator- (C++ function)
13648 @anchor{cp/topics/expressions sub-operator__gccjit rvalue}@anchor{188}
13649 @deffn {C++ Function} gccjit::rvalue operator- (gccjit::rvalue a)
13652 gccjit::rvalue negpi = -pi;
13658 @geindex operator~ (C++ function)
13659 @anchor{cp/topics/expressions inv-operator__gccjit rvalue}@anchor{189}
13660 @deffn {C++ Function} gccjit::rvalue operator~ (gccjit::rvalue a)
13663 gccjit::rvalue mask = ~a;
13669 @geindex operator! (C++ function)
13670 @anchor{cp/topics/expressions not-operator__gccjit rvalue}@anchor{18a}
13671 @deffn {C++ Function} gccjit::rvalue operator! (gccjit::rvalue a)
13674 gccjit::rvalue guard = !cond;
13680 @node Binary Operations<2>,Comparisons<2>,Unary Operations<2>,Rvalues<2>
13681 @anchor{cp/topics/expressions binary-operations}@anchor{18b}
13682 @subsubsection Binary Operations
13685 @geindex gccjit;;context;;new_binary_op (C++ function)
13686 @anchor{cp/topics/expressions gccjit context new_binary_op__enum gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{123}
13687 @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)
13689 Build a binary operation out of two constituent rvalues.
13691 Parameter @code{loc} is optional.
13693 This is a thin wrapper around the C API's
13694 @pxref{12,,gcc_jit_context_new_binary_op()} and the available binary
13695 operations are documented there.
13698 There are shorter ways to spell the various specific kinds of binary
13701 @geindex gccjit;;context;;new_plus (C++ function)
13702 @anchor{cp/topics/expressions gccjit context new_plus__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{18c}
13703 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_plus (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
13706 @geindex gccjit;;context;;new_minus (C++ function)
13707 @anchor{cp/topics/expressions gccjit context new_minus__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{18d}
13708 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_minus (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
13711 @geindex gccjit;;context;;new_mult (C++ function)
13712 @anchor{cp/topics/expressions gccjit context new_mult__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{18e}
13713 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_mult (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
13716 @geindex gccjit;;context;;new_divide (C++ function)
13717 @anchor{cp/topics/expressions gccjit context new_divide__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{18f}
13718 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_divide (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
13721 @geindex gccjit;;context;;new_modulo (C++ function)
13722 @anchor{cp/topics/expressions gccjit context new_modulo__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{190}
13723 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_modulo (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
13726 @geindex gccjit;;context;;new_bitwise_and (C++ function)
13727 @anchor{cp/topics/expressions gccjit context new_bitwise_and__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{191}
13728 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_bitwise_and (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
13731 @geindex gccjit;;context;;new_bitwise_xor (C++ function)
13732 @anchor{cp/topics/expressions gccjit context new_bitwise_xor__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{192}
13733 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_bitwise_xor (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
13736 @geindex gccjit;;context;;new_bitwise_or (C++ function)
13737 @anchor{cp/topics/expressions gccjit context new_bitwise_or__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{193}
13738 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_bitwise_or (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
13741 @geindex gccjit;;context;;new_logical_and (C++ function)
13742 @anchor{cp/topics/expressions gccjit context new_logical_and__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{194}
13743 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_logical_and (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
13746 @geindex gccjit;;context;;new_logical_or (C++ function)
13747 @anchor{cp/topics/expressions gccjit context new_logical_or__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{195}
13748 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_logical_or (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
13751 The most concise way to spell them is with overloaded operators:
13753 @geindex operator+ (C++ function)
13754 @anchor{cp/topics/expressions add-operator__gccjit rvalue gccjit rvalue}@anchor{196}
13755 @deffn {C++ Function} gccjit::rvalue operator+ (gccjit::rvalue a, gccjit::rvalue b)
13758 gccjit::rvalue sum = a + b;
13764 @geindex operator- (C++ function)
13765 @anchor{cp/topics/expressions sub-operator__gccjit rvalue gccjit rvalue}@anchor{197}
13766 @deffn {C++ Function} gccjit::rvalue operator- (gccjit::rvalue a, gccjit::rvalue b)
13769 gccjit::rvalue diff = a - b;
13775 @geindex operator* (C++ function)
13776 @anchor{cp/topics/expressions mul-operator__gccjit rvalue gccjit rvalue}@anchor{198}
13777 @deffn {C++ Function} gccjit::rvalue operator* (gccjit::rvalue a, gccjit::rvalue b)
13780 gccjit::rvalue prod = a * b;
13786 @geindex operator/ (C++ function)
13787 @anchor{cp/topics/expressions div-operator__gccjit rvalue gccjit rvalue}@anchor{199}
13788 @deffn {C++ Function} gccjit::rvalue operator/ (gccjit::rvalue a, gccjit::rvalue b)
13791 gccjit::rvalue result = a / b;
13797 @geindex operator% (C++ function)
13798 @anchor{cp/topics/expressions mod-operator__gccjit rvalue gccjit rvalue}@anchor{19a}
13799 @deffn {C++ Function} gccjit::rvalue operator% (gccjit::rvalue a, gccjit::rvalue b)
13802 gccjit::rvalue mod = a % b;
13808 @geindex operator& (C++ function)
13809 @anchor{cp/topics/expressions and-operator__gccjit rvalue gccjit rvalue}@anchor{19b}
13810 @deffn {C++ Function} gccjit::rvalue operator& (gccjit::rvalue a, gccjit::rvalue b)
13813 gccjit::rvalue x = a & b;
13819 @geindex operator^ (C++ function)
13820 @anchor{cp/topics/expressions xor-operator__gccjit rvalue gccjit rvalue}@anchor{19c}
13821 @deffn {C++ Function} gccjit::rvalue operator^ (gccjit::rvalue a, gccjit::rvalue b)
13824 gccjit::rvalue x = a ^ b;
13830 @geindex operator| (C++ function)
13831 @anchor{cp/topics/expressions or-operator__gccjit rvalue gccjit rvalue}@anchor{19d}
13832 @deffn {C++ Function} gccjit::rvalue operator| (gccjit::rvalue a, gccjit::rvalue b)
13835 gccjit::rvalue x = a | b;
13841 @geindex operator&& (C++ function)
13842 @anchor{cp/topics/expressions sand-operator__gccjit rvalue gccjit rvalue}@anchor{19e}
13843 @deffn {C++ Function} gccjit::rvalue operator&& (gccjit::rvalue a, gccjit::rvalue b)
13846 gccjit::rvalue cond = a && b;
13852 @geindex operator|| (C++ function)
13853 @anchor{cp/topics/expressions sor-operator__gccjit rvalue gccjit rvalue}@anchor{19f}
13854 @deffn {C++ Function} gccjit::rvalue operator|| (gccjit::rvalue a, gccjit::rvalue b)
13857 gccjit::rvalue cond = a || b;
13863 These can of course be combined, giving a terse way to build compound
13869 gccjit::rvalue discriminant = (b * b) - (four * a * c);
13875 @node Comparisons<2>,Function calls<2>,Binary Operations<2>,Rvalues<2>
13876 @anchor{cp/topics/expressions comparisons}@anchor{1a0}
13877 @subsubsection Comparisons
13880 @geindex gccjit;;context;;new_comparison (C++ function)
13881 @anchor{cp/topics/expressions gccjit context new_comparison__enum gccjit rvalue gccjit rvalue gccjit location}@anchor{130}
13882 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_comparison (enum gcc_jit_comparison, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
13884 Build a boolean rvalue out of the comparison of two other rvalues.
13886 Parameter @code{loc} is optional.
13888 This is a thin wrapper around the C API's
13889 @pxref{2c,,gcc_jit_context_new_comparison()} and the available kinds
13890 of comparison are documented there.
13893 There are shorter ways to spell the various specific kinds of binary
13896 @geindex gccjit;;context;;new_eq (C++ function)
13897 @anchor{cp/topics/expressions gccjit context new_eq__gccjit rvalue gccjit rvalue gccjit location}@anchor{1a1}
13898 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_eq (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
13901 @geindex gccjit;;context;;new_ne (C++ function)
13902 @anchor{cp/topics/expressions gccjit context new_ne__gccjit rvalue gccjit rvalue gccjit location}@anchor{1a2}
13903 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_ne (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
13906 @geindex gccjit;;context;;new_lt (C++ function)
13907 @anchor{cp/topics/expressions gccjit context new_lt__gccjit rvalue gccjit rvalue gccjit location}@anchor{1a3}
13908 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_lt (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
13911 @geindex gccjit;;context;;new_le (C++ function)
13912 @anchor{cp/topics/expressions gccjit context new_le__gccjit rvalue gccjit rvalue gccjit location}@anchor{1a4}
13913 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_le (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
13916 @geindex gccjit;;context;;new_gt (C++ function)
13917 @anchor{cp/topics/expressions gccjit context new_gt__gccjit rvalue gccjit rvalue gccjit location}@anchor{1a5}
13918 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_gt (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
13921 @geindex gccjit;;context;;new_ge (C++ function)
13922 @anchor{cp/topics/expressions gccjit context new_ge__gccjit rvalue gccjit rvalue gccjit location}@anchor{1a6}
13923 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_ge (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
13926 The most concise way to spell them is with overloaded operators:
13928 @geindex operator== (C++ function)
13929 @anchor{cp/topics/expressions eq-operator__gccjit rvalue gccjit rvalue}@anchor{1a7}
13930 @deffn {C++ Function} gccjit::rvalue operator== (gccjit::rvalue a, gccjit::rvalue b)
13933 gccjit::rvalue cond = (a == ctxt.zero (t_int));
13939 @geindex operator!= (C++ function)
13940 @anchor{cp/topics/expressions neq-operator__gccjit rvalue gccjit rvalue}@anchor{1a8}
13941 @deffn {C++ Function} gccjit::rvalue operator!= (gccjit::rvalue a, gccjit::rvalue b)
13944 gccjit::rvalue cond = (i != j);
13950 @geindex operator< (C++ function)
13951 @anchor{cp/topics/expressions lt-operator__gccjit rvalue gccjit rvalue}@anchor{1a9}
13952 @deffn {C++ Function} gccjit::rvalue operator< (gccjit::rvalue a, gccjit::rvalue b)
13955 gccjit::rvalue cond = i < n;
13961 @geindex operator<= (C++ function)
13962 @anchor{cp/topics/expressions lte-operator__gccjit rvalue gccjit rvalue}@anchor{1aa}
13963 @deffn {C++ Function} gccjit::rvalue operator<= (gccjit::rvalue a, gccjit::rvalue b)
13966 gccjit::rvalue cond = i <= n;
13972 @geindex operator> (C++ function)
13973 @anchor{cp/topics/expressions gt-operator__gccjit rvalue gccjit rvalue}@anchor{1ab}
13974 @deffn {C++ Function} gccjit::rvalue operator> (gccjit::rvalue a, gccjit::rvalue b)
13977 gccjit::rvalue cond = (ch > limit);
13983 @geindex operator>= (C++ function)
13984 @anchor{cp/topics/expressions gte-operator__gccjit rvalue gccjit rvalue}@anchor{1ac}
13985 @deffn {C++ Function} gccjit::rvalue operator>= (gccjit::rvalue a, gccjit::rvalue b)
13988 gccjit::rvalue cond = (score >= ctxt.new_rvalue (t_int, 100));
13994 @c TODO: beyond this point
13996 @node Function calls<2>,Function pointers<3>,Comparisons<2>,Rvalues<2>
13997 @anchor{cp/topics/expressions function-calls}@anchor{1ad}
13998 @subsubsection Function calls
14001 @geindex gcc_jit_context_new_call (C++ function)
14002 @anchor{cp/topics/expressions gcc_jit_context_new_call__gcc_jit_contextP gcc_jit_locationP gcc_jit_functionP i gcc_jit_rvaluePP}@anchor{1ae}
14003 @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)
14005 Given a function and the given table of argument rvalues, construct a
14006 call to the function, with the result as an rvalue.
14010 @code{gccjit::context::new_call()} merely builds a
14011 @pxref{179,,gccjit;;rvalue} i.e. an expression that can be evaluated,
14012 perhaps as part of a more complicated expression.
14013 The call @emph{won't} happen unless you add a statement to a function
14014 that evaluates the expression.
14016 For example, if you want to call a function and discard the result
14017 (or to call a function with @code{void} return type), use
14018 @pxref{1af,,gccjit;;block;;add_eval()}:
14021 /* Add "(void)printf (arg0, arg1);". */
14022 block.add_eval (ctxt.new_call (printf_func, arg0, arg1));
14030 @node Function pointers<3>,Type-coercion<2>,Function calls<2>,Rvalues<2>
14031 @anchor{cp/topics/expressions function-pointers}@anchor{1b0}
14032 @subsubsection Function pointers
14035 @geindex gccjit;;function;;get_address (C++ function)
14036 @anchor{cp/topics/expressions gccjit function get_address__gccjit location}@anchor{1b1}
14037 @deffn {C++ Function} gccjit::rvalue gccjit::function::get_address (gccjit::location loc)
14039 Get the address of a function as an rvalue, of function pointer
14043 @node Type-coercion<2>,,Function pointers<3>,Rvalues<2>
14044 @anchor{cp/topics/expressions type-coercion}@anchor{1b2}
14045 @subsubsection Type-coercion
14048 @geindex gccjit;;context;;new_cast (C++ function)
14049 @anchor{cp/topics/expressions gccjit context new_cast__gccjit rvalue gccjit type gccjit location}@anchor{1b3}
14050 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_cast (gccjit::rvalue rvalue, gccjit::type type, gccjit::location loc)
14052 Given an rvalue of T, construct another rvalue of another type.
14054 Currently only a limited set of conversions are possible:
14068 P* <-> Q*, for pointer types P and Q
14073 @node Lvalues<2>,Working with pointers structs and unions<2>,Rvalues<2>,Expressions<2>
14074 @anchor{cp/topics/expressions lvalues}@anchor{1b4}
14075 @subsubsection Lvalues
14078 @geindex gccjit;;lvalue (C++ class)
14079 @anchor{cp/topics/expressions gccjit lvalue}@anchor{1b5}
14080 @deffn {C++ Class} gccjit::lvalue
14083 An lvalue is something that can of the @emph{left}-hand side of an assignment:
14084 a storage area (such as a variable). It is a subclass of
14085 @pxref{179,,gccjit;;rvalue}, where the rvalue is computed by reading from the
14088 It iss a thin wrapper around @pxref{24,,gcc_jit_lvalue *} from the C API.
14090 @geindex gccjit;;lvalue;;get_address (C++ function)
14091 @anchor{cp/topics/expressions gccjit lvalue get_address__gccjit location}@anchor{1b6}
14092 @deffn {C++ Function} gccjit::rvalue gccjit::lvalue::get_address (gccjit::location loc)
14094 Take the address of an lvalue; analogous to:
14104 Parameter "loc" is optional.
14108 * Global variables: Global variables<2>.
14112 @node Global variables<2>,,,Lvalues<2>
14113 @anchor{cp/topics/expressions global-variables}@anchor{1b7}
14114 @subsubsection Global variables
14117 @geindex gccjit;;context;;new_global (C++ function)
14118 @anchor{cp/topics/expressions gccjit context new_global__enum gccjit type cCP gccjit location}@anchor{1b8}
14119 @deffn {C++ Function} gccjit::lvalue gccjit::context::new_global (enum gcc_jit_global_kind, gccjit::type type, const char* name, gccjit::location loc)
14121 Add a new global variable of the given type and name to the context.
14123 This is a thin wrapper around @pxref{c4,,gcc_jit_context_new_global()} from
14124 the C API; the "kind" parameter has the same meaning as there.
14127 @node Working with pointers structs and unions<2>,,Lvalues<2>,Expressions<2>
14128 @anchor{cp/topics/expressions working-with-pointers-structs-and-unions}@anchor{1b9}
14129 @subsubsection Working with pointers, structs and unions
14132 @geindex gccjit;;rvalue;;dereference (C++ function)
14133 @anchor{cp/topics/expressions gccjit rvalue dereference__gccjit location}@anchor{1ba}
14134 @deffn {C++ Function} gccjit::lvalue gccjit::rvalue::dereference (gccjit::location loc)
14136 Given an rvalue of pointer type @code{T *}, dereferencing the pointer,
14137 getting an lvalue of type @code{T}. Analogous to:
14147 Parameter "loc" is optional.
14150 If you don't need to specify the location, this can also be expressed using
14151 an overloaded operator:
14153 @geindex gccjit;;rvalue;;operator* (C++ function)
14154 @anchor{cp/topics/expressions gccjit rvalue mul-operator}@anchor{1bb}
14155 @deffn {C++ Function} gccjit::lvalue gccjit::rvalue::operator* ()
14158 gccjit::lvalue content = *ptr;
14164 Field access is provided separately for both lvalues and rvalues:
14166 @geindex gccjit;;lvalue;;access_field (C++ function)
14167 @anchor{cp/topics/expressions gccjit lvalue access_field__gccjit field gccjit location}@anchor{1bc}
14168 @deffn {C++ Function} gccjit::lvalue gccjit::lvalue::access_field (gccjit::field field, gccjit::location loc)
14170 Given an lvalue of struct or union type, access the given field,
14171 getting an lvalue of the field's type. Analogous to:
14174 (EXPR).field = ...;
14182 @geindex gccjit;;rvalue;;access_field (C++ function)
14183 @anchor{cp/topics/expressions gccjit rvalue access_field__gccjit field gccjit location}@anchor{1bd}
14184 @deffn {C++ Function} gccjit::rvalue gccjit::rvalue::access_field (gccjit::field field, gccjit::location loc)
14186 Given an rvalue of struct or union type, access the given field
14187 as an rvalue. Analogous to:
14198 @geindex gccjit;;rvalue;;dereference_field (C++ function)
14199 @anchor{cp/topics/expressions gccjit rvalue dereference_field__gccjit field gccjit location}@anchor{1be}
14200 @deffn {C++ Function} gccjit::lvalue gccjit::rvalue::dereference_field (gccjit::field field, gccjit::location loc)
14202 Given an rvalue of pointer type @code{T *} where T is of struct or union
14203 type, access the given field as an lvalue. Analogous to:
14211 in C, itself equivalent to @code{(*EXPR).FIELD}.
14214 @geindex gccjit;;context;;new_array_access (C++ function)
14215 @anchor{cp/topics/expressions gccjit context new_array_access__gccjit rvalue gccjit rvalue gccjit location}@anchor{1bf}
14216 @deffn {C++ Function} gccjit::lvalue gccjit::context::new_array_access (gccjit::rvalue ptr, gccjit::rvalue index, gccjit::location loc)
14218 Given an rvalue of pointer type @code{T *}, get at the element @cite{T} at
14219 the given index, using standard C array indexing rules i.e. each
14220 increment of @code{index} corresponds to @code{sizeof(T)} bytes.
14229 in C (or, indeed, to @code{PTR + INDEX}).
14231 Parameter "loc" is optional.
14234 For array accesses where you don't need to specify a @pxref{153,,gccjit;;location},
14235 two overloaded operators are available:
14239 gccjit::lvalue gccjit::rvalue::operator[] (gccjit::rvalue index)
14242 gccjit::lvalue element = array[idx];
14247 gccjit::lvalue gccjit::rvalue::operator[] (int index)
14250 gccjit::lvalue element = array[0];
14256 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
14257 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
14259 @c This is free software: you can redistribute it and/or modify it
14260 @c under the terms of the GNU General Public License as published by
14261 @c the Free Software Foundation, either version 3 of the License, or
14262 @c (at your option) any later version.
14264 @c This program is distributed in the hope that it will be useful, but
14265 @c WITHOUT ANY WARRANTY; without even the implied warranty of
14266 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14267 @c General Public License for more details.
14269 @c You should have received a copy of the GNU General Public License
14270 @c along with this program. If not, see
14271 @c <http://www.gnu.org/licenses/>.
14273 @node Creating and using functions<2>,Source Locations<2>,Expressions<2>,Topic Reference<2>
14274 @anchor{cp/topics/functions doc}@anchor{1c0}@anchor{cp/topics/functions creating-and-using-functions}@anchor{1c1}
14275 @subsection Creating and using functions
14279 * Params: Params<2>.
14280 * Functions: Functions<2>.
14281 * Blocks: Blocks<2>.
14282 * Statements: Statements<2>.
14286 @node Params<2>,Functions<2>,,Creating and using functions<2>
14287 @anchor{cp/topics/functions params}@anchor{1c2}
14288 @subsubsection Params
14291 @geindex gccjit;;param (C++ class)
14292 @anchor{cp/topics/functions gccjit param}@anchor{1c3}
14293 @deffn {C++ Class} gccjit::param
14295 A @cite{gccjit::param} represents a parameter to a function.
14298 @geindex gccjit;;context;;new_param (C++ function)
14299 @anchor{cp/topics/functions gccjit context new_param__gccjit type cCP gccjit location}@anchor{122}
14300 @deffn {C++ Function} gccjit::param gccjit::context::new_param (gccjit::type type, const char* name, gccjit::location loc)
14302 In preparation for creating a function, create a new parameter of the
14303 given type and name.
14306 @pxref{1c3,,gccjit;;param} is a subclass of @pxref{1b5,,gccjit;;lvalue} (and thus
14307 of @pxref{179,,gccjit;;rvalue} and @pxref{160,,gccjit;;object}). It is a thin
14308 wrapper around the C API's @pxref{25,,gcc_jit_param *}.
14310 @node Functions<2>,Blocks<2>,Params<2>,Creating and using functions<2>
14311 @anchor{cp/topics/functions functions}@anchor{1c4}
14312 @subsubsection Functions
14315 @geindex gccjit;;function (C++ class)
14316 @anchor{cp/topics/functions gccjit function}@anchor{1c5}
14317 @deffn {C++ Class} gccjit::function
14319 A @cite{gccjit::function} represents a function - either one that we're
14320 creating ourselves, or one that we're referencing.
14323 @geindex gccjit;;context;;new_function (C++ function)
14324 @anchor{cp/topics/functions gccjit context new_function__enum gccjit type cCP std vector param R i gccjit location}@anchor{1c6}
14325 @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)
14327 Create a gcc_jit_function with the given name and parameters.
14329 Parameters "is_variadic" and "loc" are optional.
14331 This is a wrapper around the C API's @pxref{11,,gcc_jit_context_new_function()}.
14334 @geindex gccjit;;context;;get_builtin_function (C++ function)
14335 @anchor{cp/topics/functions gccjit context get_builtin_function__cCP}@anchor{1c7}
14336 @deffn {C++ Function} gccjit::function gccjit::context::get_builtin_function (const char* name)
14338 This is a wrapper around the C API's
14339 @pxref{db,,gcc_jit_context_get_builtin_function()}.
14342 @geindex gccjit;;function;;get_param (C++ function)
14343 @anchor{cp/topics/functions gccjit function get_param__iC}@anchor{1c8}
14344 @deffn {C++ Function} gccjit::param gccjit::function::get_param (int index) const
14346 Get the param of the given index (0-based).
14349 @geindex gccjit;;function;;dump_to_dot (C++ function)
14350 @anchor{cp/topics/functions gccjit function dump_to_dot__cCP}@anchor{135}
14351 @deffn {C++ Function} void gccjit::function::dump_to_dot (const char* path)
14353 Emit the function in graphviz format to the given path.
14356 @geindex gccjit;;function;;new_local (C++ function)
14357 @anchor{cp/topics/functions gccjit function new_local__gccjit type cCP gccjit location}@anchor{12c}
14358 @deffn {C++ Function} gccjit::lvalue gccjit::function::new_local (gccjit::type type, const char* name, gccjit::location loc)
14360 Create a new local variable within the function, of the given type and
14364 @node Blocks<2>,Statements<2>,Functions<2>,Creating and using functions<2>
14365 @anchor{cp/topics/functions blocks}@anchor{1c9}
14366 @subsubsection Blocks
14369 @geindex gccjit;;block (C++ class)
14370 @anchor{cp/topics/functions gccjit block}@anchor{1ca}
14371 @deffn {C++ Class} gccjit::block
14373 A @cite{gccjit::block} represents a basic block within a function i.e. a
14374 sequence of statements with a single entry point and a single exit
14377 @pxref{1ca,,gccjit;;block} is a subclass of @pxref{160,,gccjit;;object}.
14379 The first basic block that you create within a function will
14382 Each basic block that you create within a function must be
14383 terminated, either with a conditional, a jump, a return, or
14386 It's legal to have multiple basic blocks that return within
14390 @geindex gccjit;;function;;new_block (C++ function)
14391 @anchor{cp/topics/functions gccjit function new_block__cCP}@anchor{1cb}
14392 @deffn {C++ Function} gccjit::block gccjit::function::new_block (const char* name)
14394 Create a basic block of the given name. The name may be NULL, but
14395 providing meaningful names is often helpful when debugging: it may
14396 show up in dumps of the internal representation, and in error
14400 @node Statements<2>,,Blocks<2>,Creating and using functions<2>
14401 @anchor{cp/topics/functions statements}@anchor{1cc}
14402 @subsubsection Statements
14405 @geindex gccjit;;block;;add_eval (C++ function)
14406 @anchor{cp/topics/functions gccjit block add_eval__gccjit rvalue gccjit location}@anchor{1af}
14407 @deffn {C++ Function} void gccjit::block::add_eval (gccjit::rvalue rvalue, gccjit::location loc)
14409 Add evaluation of an rvalue, discarding the result
14410 (e.g. a function call that "returns" void).
14412 This is equivalent to this C code:
14421 @geindex gccjit;;block;;add_assignment (C++ function)
14422 @anchor{cp/topics/functions gccjit block add_assignment__gccjit lvalue gccjit rvalue gccjit location}@anchor{12e}
14423 @deffn {C++ Function} void gccjit::block::add_assignment (gccjit::lvalue lvalue, gccjit::rvalue rvalue, gccjit::location loc)
14425 Add evaluation of an rvalue, assigning the result to the given
14428 This is roughly equivalent to this C code:
14437 @geindex gccjit;;block;;add_assignment_op (C++ function)
14438 @anchor{cp/topics/functions gccjit block add_assignment_op__gccjit lvalue enum gccjit rvalue gccjit location}@anchor{132}
14439 @deffn {C++ Function} void gccjit::block::add_assignment_op (gccjit::lvalue lvalue, enum gcc_jit_binary_op, gccjit::rvalue rvalue, gccjit::location loc)
14441 Add evaluation of an rvalue, using the result to modify an
14444 This is analogous to "+=" and friends:
14458 loop_body.add_assignment_op (
14460 GCC_JIT_BINARY_OP_PLUS,
14461 ctxt.one (int_type));
14467 @geindex gccjit;;block;;add_comment (C++ function)
14468 @anchor{cp/topics/functions gccjit block add_comment__cCP gccjit location}@anchor{13d}
14469 @deffn {C++ Function} void gccjit::block::add_comment (const char* text, gccjit::location loc)
14471 Add a no-op textual comment to the internal representation of the
14472 code. It will be optimized away, but will be visible in the dumps
14473 seen via @pxref{66,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE}
14474 and @pxref{1c,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE},
14475 and thus may be of use when debugging how your project's internal
14476 representation gets converted to the libgccjit IR.
14478 Parameter "loc" is optional.
14481 @geindex gccjit;;block;;end_with_conditional (C++ function)
14482 @anchor{cp/topics/functions gccjit block end_with_conditional__gccjit rvalue gccjit block gccjit block gccjit location}@anchor{131}
14483 @deffn {C++ Function} void gccjit::block::end_with_conditional (gccjit::rvalue boolval, gccjit::block on_true, gccjit::block on_false, gccjit::location loc)
14485 Terminate a block by adding evaluation of an rvalue, branching on the
14486 result to the appropriate successor block.
14488 This is roughly equivalent to this C code:
14499 block, boolval, on_true, and on_false must be non-NULL.
14502 @geindex gccjit;;block;;end_with_jump (C++ function)
14503 @anchor{cp/topics/functions gccjit block end_with_jump__gccjit block gccjit location}@anchor{1cd}
14504 @deffn {C++ Function} void gccjit::block::end_with_jump (gccjit::block target, gccjit::location loc)
14506 Terminate a block by adding a jump to the given target block.
14508 This is roughly equivalent to this C code:
14517 @geindex gccjit;;block;;end_with_return (C++ function)
14518 @anchor{cp/topics/functions gccjit block end_with_return__gccjit rvalue gccjit location}@anchor{1ce}
14519 @deffn {C++ Function} void gccjit::block::end_with_return (gccjit::rvalue rvalue, gccjit::location loc)
14523 Both params are optional.
14525 An rvalue must be provided for a function returning non-void, and
14526 must not be provided by a function "returning" @cite{void}.
14528 If an rvalue is provided, the block is terminated by evaluating the
14529 rvalue and returning the value.
14531 This is roughly equivalent to this C code:
14539 If an rvalue is not provided, the block is terminated by adding a
14540 valueless return, for use within a function with "void" return type.
14542 This is equivalent to this C code:
14551 @geindex gccjit;;block;;end_with_switch (C++ function)
14552 @anchor{cp/topics/functions gccjit block end_with_switch__gccjit rvalue gccjit block std vector gccjit case_ gccjit location}@anchor{1cf}
14553 @deffn {C++ Function} void gccjit::block::end_with_switch (gccjit::rvalue expr, gccjit::block default_block, std::vector<gccjit::case_> cases, gccjit::location loc)
14555 Terminate a block by adding evalation of an rvalue, then performing
14558 This is roughly equivalent to this C code:
14564 goto default_block;
14566 case C0.min_value ... C0.max_value:
14567 goto C0.dest_block;
14569 case C1.min_value ... C1.max_value:
14570 goto C1.dest_block;
14574 case C[N - 1].min_value ... C[N - 1].max_value:
14575 goto C[N - 1].dest_block;
14581 @code{expr} must be of the same integer type as all of the @code{min_value}
14582 and @code{max_value} within the cases.
14584 The ranges of the cases must not overlap (or have duplicate
14587 The API entrypoints relating to switch statements and cases:
14595 @pxref{1cf,,gccjit;;block;;end_with_switch()}
14598 @pxref{1d0,,gccjit;;context;;new_case()}
14602 were added in @pxref{e9,,LIBGCCJIT_ABI_3}; you can test for their presence
14606 #ifdef LIBGCCJIT_HAVE_SWITCH_STATEMENTS
14611 @geindex gccjit;;block;;end_with_switch;;gccjit;;case_ (C++ class)
14612 @anchor{cp/topics/functions gccjit block end_with_switch gccjit case_}@anchor{1d1}
14613 @deffn {C++ Class} gccjit::case_
14616 A @cite{gccjit::case_} represents a case within a switch statement, and
14617 is created within a particular @pxref{14b,,gccjit;;context} using
14618 @pxref{1d0,,gccjit;;context;;new_case()}. It is a subclass of
14619 @pxref{160,,gccjit;;object}.
14621 Each case expresses a multivalued range of integer values. You
14622 can express single-valued cases by passing in the same value for
14623 both @cite{min_value} and @cite{max_value}.
14625 @geindex gccjit;;block;;end_with_switch;;gccjit;;context;;new_case (C++ function)
14626 @anchor{cp/topics/functions gccjit block end_with_switch gccjit context new_case__gccjit rvalue gccjit rvalue gccjit block}@anchor{1d0}
14627 @deffn {C++ Function} gccjit::case_* gccjit::context::new_case (gccjit::rvalue min_value, gccjit::rvalue max_value, gccjit::block dest_block)
14629 Create a new gccjit::case for use in a switch statement.
14630 @cite{min_value} and @cite{max_value} must be constants of an integer type,
14631 which must match that of the expression of the switch statement.
14633 @cite{dest_block} must be within the same function as the switch
14637 Here's an example of creating a switch statement:
14644 create_code (gcc_jit_context *c_ctxt, void *user_data)
14646 /* Let's try to inject the equivalent of:
14648 test_switch (int x)
14669 gccjit::context ctxt (c_ctxt);
14670 gccjit::type t_int = ctxt.get_type (GCC_JIT_TYPE_INT);
14671 gccjit::type return_type = t_int;
14672 gccjit::param x = ctxt.new_param (t_int, "x");
14673 std::vector <gccjit::param> params;
14674 params.push_back (x);
14675 gccjit::function func = ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
14680 gccjit::block b_initial = func.new_block ("initial");
14682 gccjit::block b_default = func.new_block ("default");
14683 gccjit::block b_case_0_5 = func.new_block ("case_0_5");
14684 gccjit::block b_case_25_27 = func.new_block ("case_25_27");
14685 gccjit::block b_case_m42_m17 = func.new_block ("case_m42_m17");
14686 gccjit::block b_case_40 = func.new_block ("case_40");
14688 std::vector <gccjit::case_> cases;
14689 cases.push_back (ctxt.new_case (ctxt.new_rvalue (t_int, 0),
14690 ctxt.new_rvalue (t_int, 5),
14692 cases.push_back (ctxt.new_case (ctxt.new_rvalue (t_int, 25),
14693 ctxt.new_rvalue (t_int, 27),
14695 cases.push_back (ctxt.new_case (ctxt.new_rvalue (t_int, -42),
14696 ctxt.new_rvalue (t_int, -17),
14698 cases.push_back (ctxt.new_case (ctxt.new_rvalue (t_int, 40),
14699 ctxt.new_rvalue (t_int, 40),
14701 b_initial.end_with_switch (x,
14705 b_case_0_5.end_with_return (ctxt.new_rvalue (t_int, 3));
14706 b_case_25_27.end_with_return (ctxt.new_rvalue (t_int, 4));
14707 b_case_m42_m17.end_with_return (ctxt.new_rvalue (t_int, 83));
14708 b_case_40.end_with_return (ctxt.new_rvalue (t_int, 8));
14709 b_default.end_with_return (ctxt.new_rvalue (t_int, 10));
14719 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
14720 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
14722 @c This is free software: you can redistribute it and/or modify it
14723 @c under the terms of the GNU General Public License as published by
14724 @c the Free Software Foundation, either version 3 of the License, or
14725 @c (at your option) any later version.
14727 @c This program is distributed in the hope that it will be useful, but
14728 @c WITHOUT ANY WARRANTY; without even the implied warranty of
14729 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14730 @c General Public License for more details.
14732 @c You should have received a copy of the GNU General Public License
14733 @c along with this program. If not, see
14734 @c <http://www.gnu.org/licenses/>.
14736 @node Source Locations<2>,Compiling a context<2>,Creating and using functions<2>,Topic Reference<2>
14737 @anchor{cp/topics/locations source-locations}@anchor{1d2}@anchor{cp/topics/locations doc}@anchor{1d3}
14738 @subsection Source Locations
14741 @geindex gccjit;;location (C++ class)
14742 @anchor{cp/topics/locations gccjit location}@anchor{153}
14743 @deffn {C++ Class} gccjit::location
14745 A @cite{gccjit::location} encapsulates a source code location, so that
14746 you can (optionally) associate locations in your language with
14747 statements in the JIT-compiled code, allowing the debugger to
14748 single-step through your language.
14750 @cite{gccjit::location} instances are optional: you can always omit them
14751 from any C++ API entrypoint accepting one.
14753 You can construct them using @pxref{141,,gccjit;;context;;new_location()}.
14755 You need to enable @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} on the
14756 @pxref{14b,,gccjit;;context} for these locations to actually be usable by
14760 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DEBUGINFO, 1);
14766 @geindex gccjit;;context;;new_location (C++ function)
14767 @anchor{cp/topics/locations gccjit context new_location__cCP i i}@anchor{141}
14768 @deffn {C++ Function} gccjit::location gccjit::context::new_location (const char* filename, int line, int column)
14770 Create a @cite{gccjit::location} instance representing the given source
14775 * Faking it: Faking it<2>.
14779 @node Faking it<2>,,,Source Locations<2>
14780 @anchor{cp/topics/locations faking-it}@anchor{1d4}
14781 @subsubsection Faking it
14784 If you don't have source code for your internal representation, but need
14785 to debug, you can generate a C-like representation of the functions in
14786 your context using @pxref{152,,gccjit;;context;;dump_to_file()}:
14789 ctxt.dump_to_file ("/tmp/something.c",
14790 1 /* update_locations */);
14795 This will dump C-like code to the given path. If the @cite{update_locations}
14796 argument is true, this will also set up @cite{gccjit::location} information
14797 throughout the context, pointing at the dump file as if it were a source
14798 file, giving you @emph{something} you can step through in the debugger.
14800 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
14801 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
14803 @c This is free software: you can redistribute it and/or modify it
14804 @c under the terms of the GNU General Public License as published by
14805 @c the Free Software Foundation, either version 3 of the License, or
14806 @c (at your option) any later version.
14808 @c This program is distributed in the hope that it will be useful, but
14809 @c WITHOUT ANY WARRANTY; without even the implied warranty of
14810 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14811 @c General Public License for more details.
14813 @c You should have received a copy of the GNU General Public License
14814 @c along with this program. If not, see
14815 @c <http://www.gnu.org/licenses/>.
14817 @node Compiling a context<2>,,Source Locations<2>,Topic Reference<2>
14818 @anchor{cp/topics/compilation compiling-a-context}@anchor{1d5}@anchor{cp/topics/compilation doc}@anchor{1d6}
14819 @subsection Compiling a context
14822 Once populated, a @pxref{14b,,gccjit;;context} can be compiled to
14823 machine code, either in-memory via @pxref{124,,gccjit;;context;;compile()} or
14824 to disk via @pxref{1d7,,gccjit;;context;;compile_to_file()}.
14826 You can compile a context multiple times (using either form of
14827 compilation), although any errors that occur on the context will
14828 prevent any future compilation of that context.
14831 * In-memory compilation: In-memory compilation<2>.
14832 * Ahead-of-time compilation: Ahead-of-time compilation<2>.
14836 @node In-memory compilation<2>,Ahead-of-time compilation<2>,,Compiling a context<2>
14837 @anchor{cp/topics/compilation in-memory-compilation}@anchor{1d8}
14838 @subsubsection In-memory compilation
14841 @geindex gccjit;;context;;compile (C++ function)
14842 @anchor{cp/topics/compilation gccjit context compile}@anchor{124}
14843 @deffn {C++ Function} gcc_jit_result* gccjit::context::compile ()
14845 This calls into GCC and builds the code, returning a
14846 @cite{gcc_jit_result *}.
14848 This is a thin wrapper around the
14849 @pxref{15,,gcc_jit_context_compile()} API entrypoint.
14852 @node Ahead-of-time compilation<2>,,In-memory compilation<2>,Compiling a context<2>
14853 @anchor{cp/topics/compilation ahead-of-time-compilation}@anchor{1d9}
14854 @subsubsection Ahead-of-time compilation
14857 Although libgccjit is primarily aimed at just-in-time compilation, it
14858 can also be used for implementing more traditional ahead-of-time
14859 compilers, via the @pxref{1d7,,gccjit;;context;;compile_to_file()} method.
14861 @geindex gccjit;;context;;compile_to_file (C++ function)
14862 @anchor{cp/topics/compilation gccjit context compile_to_file__enum cCP}@anchor{1d7}
14863 @deffn {C++ Function} void gccjit::context::compile_to_file (enum gcc_jit_output_kind, const char* output_path)
14865 Compile the @pxref{14b,,gccjit;;context} to a file of the given
14868 This is a thin wrapper around the
14869 @pxref{4a,,gcc_jit_context_compile_to_file()} API entrypoint.
14872 @c Copyright (C) 2014-2019 Free Software Foundation, Inc.
14873 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
14875 @c This is free software: you can redistribute it and/or modify it
14876 @c under the terms of the GNU General Public License as published by
14877 @c the Free Software Foundation, either version 3 of the License, or
14878 @c (at your option) any later version.
14880 @c This program is distributed in the hope that it will be useful, but
14881 @c WITHOUT ANY WARRANTY; without even the implied warranty of
14882 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14883 @c General Public License for more details.
14885 @c You should have received a copy of the GNU General Public License
14886 @c along with this program. If not, see
14887 @c <http://www.gnu.org/licenses/>.
14889 @node Internals,Indices and tables,C++ bindings for libgccjit,Top
14890 @anchor{internals/index internals}@anchor{1da}@anchor{internals/index doc}@anchor{1db}
14895 * Working on the JIT library::
14896 * Running the test suite::
14897 * Environment variables::
14898 * Packaging notes::
14899 * Overview of code structure::
14901 * Submitting patches::
14905 @node Working on the JIT library,Running the test suite,,Internals
14906 @anchor{internals/index working-on-the-jit-library}@anchor{1dc}
14907 @section Working on the JIT library
14910 Having checked out the source code (to "src"), you can configure and build
14911 the JIT library like this:
14916 PREFIX=$(pwd)/install
14919 --enable-host-shared \
14920 --enable-languages=jit,c++ \
14921 --disable-bootstrap \
14922 --enable-checking=release \
14924 nice make -j4 # altering the "4" to however many cores you have
14929 This should build a libgccjit.so within jit/build/gcc:
14932 [build] $ file gcc/libgccjit.so*
14933 gcc/libgccjit.so: symbolic link to `libgccjit.so.0'
14934 gcc/libgccjit.so.0: symbolic link to `libgccjit.so.0.0.1'
14935 gcc/libgccjit.so.0.0.1: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, not stripped
14940 Here's what those configuration options mean:
14942 @geindex command line option; --enable-host-shared
14943 @anchor{internals/index cmdoption--enable-host-shared}@anchor{1dd}
14944 @deffn {Option} --enable-host-shared
14946 Configuring with this option means that the compiler is built as
14947 position-independent code, which incurs a slight performance hit,
14948 but it necessary for a shared library.
14951 @geindex command line option; --enable-languages=jit@comma{}c++
14952 @anchor{internals/index cmdoption--enable-languages}@anchor{1de}
14953 @deffn {Option} --enable-languages=jit,c++
14955 This specifies which frontends to build. The JIT library looks like
14956 a frontend to the rest of the code.
14958 The C++ portion of the JIT test suite requires the C++ frontend to be
14959 enabled at configure-time, or you may see errors like this when
14960 running the test suite:
14963 xgcc: error: /home/david/jit/src/gcc/testsuite/jit.dg/test-quadratic.cc: C++ compiler not installed on this system
14964 c++: error trying to exec 'cc1plus': execvp: No such file or directory
14970 @geindex command line option; --disable-bootstrap
14971 @anchor{internals/index cmdoption--disable-bootstrap}@anchor{1df}
14972 @deffn {Option} --disable-bootstrap
14974 For hacking on the "jit" subdirectory, performing a full
14975 bootstrap can be overkill, since it's unused by a bootstrap. However,
14976 when submitting patches, you should remove this option, to ensure that
14977 the compiler can still bootstrap itself.
14980 @geindex command line option; --enable-checking=release
14981 @anchor{internals/index cmdoption--enable-checking}@anchor{1e0}
14982 @deffn {Option} --enable-checking=release
14984 The compile can perform extensive self-checking as it runs, useful when
14985 debugging, but slowing things down.
14987 For maximum speed, configure with @code{--enable-checking=release} to
14988 disable this self-checking.
14991 @node Running the test suite,Environment variables,Working on the JIT library,Internals
14992 @anchor{internals/index running-the-test-suite}@anchor{1e1}
14993 @section Running the test suite
14998 [gcc] $ make check-jit RUNTESTFLAGS="-v -v -v"
15003 A summary of the tests can then be seen in:
15006 jit/build/gcc/testsuite/jit/jit.sum
15011 and detailed logs in:
15014 jit/build/gcc/testsuite/jit/jit.log
15019 The test executables are normally deleted after each test is run. For
15020 debugging, they can be preserved by setting
15021 @geindex PRESERVE_EXECUTABLES
15022 @geindex environment variable; PRESERVE_EXECUTABLES
15023 @code{PRESERVE_EXECUTABLES}
15024 in the environment. If so, they can then be seen as:
15027 jit/build/gcc/testsuite/jit/*.exe
15032 which can be run independently.
15034 You can compile and run individual tests by passing "jit.exp=TESTNAME" to RUNTESTFLAGS e.g.:
15037 [gcc] $ PRESERVE_EXECUTABLES= \
15039 RUNTESTFLAGS="-v -v -v jit.exp=test-factorial.c"
15044 and once a test has been compiled, you can debug it directly:
15047 [gcc] $ PATH=.:$PATH \
15048 LD_LIBRARY_PATH=. \
15051 testsuite/jit/test-factorial.c.exe
15057 * Running under valgrind::
15061 @node Running under valgrind,,,Running the test suite
15062 @anchor{internals/index running-under-valgrind}@anchor{1e2}
15063 @subsection Running under valgrind
15066 The jit testsuite detects if
15067 @geindex RUN_UNDER_VALGRIND
15068 @geindex environment variable; RUN_UNDER_VALGRIND
15069 @code{RUN_UNDER_VALGRIND} is present in the
15070 environment (with any value). If it is present, it runs the test client
15071 code under valgrind@footnote{http://valgrind.org},
15072 specifcally, the default
15073 memcheck@footnote{http://valgrind.org/docs/manual/mc-manual.html}
15075 --leak-check=full@footnote{http://valgrind.org/docs/manual/mc-manual.html#opt.leak-check}.
15077 It automatically parses the output from valgrind, injecting XFAIL results if
15078 any issues are found, or PASS results if the output is clean. The output
15079 is saved to @code{TESTNAME.exe.valgrind.txt}.
15081 For example, the following invocation verbosely runs the testcase
15082 @code{test-sum-of-squares.c} under valgrind, showing an issue:
15085 $ RUN_UNDER_VALGRIND= \
15087 RUNTESTFLAGS="-v -v -v jit.exp=test-sum-of-squares.c"
15089 (...verbose log contains detailed valgrind errors, if any...)
15091 === jit Summary ===
15093 # of expected passes 28
15094 # of expected failures 2
15096 $ less testsuite/jit/jit.sum
15097 (...other results...)
15098 XFAIL: jit.dg/test-sum-of-squares.c: test-sum-of-squares.c.exe.valgrind.txt: definitely lost: 8 bytes in 1 blocks
15099 XFAIL: jit.dg/test-sum-of-squares.c: test-sum-of-squares.c.exe.valgrind.txt: unsuppressed errors: 1
15100 (...other results...)
15102 $ less testsuite/jit/test-sum-of-squares.c.exe.valgrind.txt
15103 (...shows full valgrind report for this test case...)
15108 When running under valgrind, it's best to have configured gcc with
15109 @code{--enable-valgrind-annotations}, which automatically suppresses
15110 various known false positives.
15112 @node Environment variables,Packaging notes,Running the test suite,Internals
15113 @anchor{internals/index environment-variables}@anchor{1e3}
15114 @section Environment variables
15117 When running client code against a locally-built libgccjit, three
15118 environment variables need to be set up:
15120 @geindex environment variable; LD_LIBRARY_PATH
15121 @anchor{internals/index envvar-LD_LIBRARY_PATH}@anchor{1e4}
15122 @deffn {Environment Variable} LD_LIBRARY_PATH
15126 @cite{libgccjit.so} is dynamically linked into client code, so if running
15127 against a locally-built library, @code{LD_LIBRARY_PATH} needs to be set
15128 up appropriately. The library can be found within the "gcc"
15129 subdirectory of the build tree:
15133 $ file libgccjit.so*
15134 libgccjit.so: symbolic link to `libgccjit.so.0'
15135 libgccjit.so.0: symbolic link to `libgccjit.so.0.0.1'
15136 libgccjit.so.0.0.1: ELF 64-bit LSB shared object, x86-64, version 1 (GNU/Linux), dynamically linked, not stripped
15142 @geindex environment variable; PATH
15143 @anchor{internals/index envvar-PATH}@anchor{1e5}
15144 @deffn {Environment Variable} PATH
15146 The library uses a driver executable for converting from .s assembler
15147 files to .so shared libraries. Specifically, it looks for a name
15149 @code{$@{target_noncanonical@}-gcc-$@{gcc_BASEVER@}$@{exeext@}}
15150 such as @code{x86_64-unknown-linux-gnu-gcc-5.0.0}.
15152 Hence @code{PATH} needs to include a directory where the library can
15153 locate this executable.
15155 The executable is normally installed to the installation bindir
15156 (e.g. /usr/bin), but a copy is also created within the "gcc"
15157 subdirectory of the build tree for running the testsuite, and for ease
15161 @geindex environment variable; LIBRARY_PATH
15162 @anchor{internals/index envvar-LIBRARY_PATH}@anchor{1e6}
15163 @deffn {Environment Variable} LIBRARY_PATH
15165 The driver executable invokes the linker, and the latter needs to locate
15166 support libraries needed by the generated code, or you will see errors
15170 ld: cannot find crtbeginS.o: No such file or directory
15171 ld: cannot find -lgcc
15172 ld: cannot find -lgcc_s
15177 Hence if running directly from a locally-built copy (without installing),
15178 @code{LIBRARY_PATH} needs to contain the "gcc" subdirectory of the build
15182 For example, to run a binary that uses the library against a non-installed
15183 build of the library in LIBGCCJIT_BUILD_DIR you need an invocation of the
15184 client code like this, to preprend the dir to each of the environment
15188 $ LD_LIBRARY_PATH=$(LIBGCCJIT_BUILD_DIR):$(LD_LIBRARY_PATH) \
15189 PATH=$(LIBGCCJIT_BUILD_DIR):$(PATH) \
15190 LIBRARY_PATH=$(LIBGCCJIT_BUILD_DIR):$(LIBRARY_PATH) \
15197 @node Packaging notes,Overview of code structure,Environment variables,Internals
15198 @anchor{internals/index packaging-notes}@anchor{1e7}
15199 @section Packaging notes
15202 The configure-time option @pxref{1dd,,--enable-host-shared} is needed when
15203 building the jit in order to get position-independent code. This will
15204 slow down the regular compiler by a few percent. Hence when packaging gcc
15205 with libgccjit, please configure and build twice:
15213 once without @pxref{1dd,,--enable-host-shared} for most languages, and
15216 once with @pxref{1dd,,--enable-host-shared} for the jit
15223 # Configure and build with --enable-host-shared
15225 mkdir configuration-for-jit
15226 pushd configuration-for-jit
15227 $(SRCDIR)/configure \
15228 --enable-host-shared \
15229 --enable-languages=jit \
15230 --prefix=$(DESTDIR)
15234 # Configure and build *without* --enable-host-shared
15235 # for maximum speed:
15236 mkdir standard-configuration
15237 pushd standard-configuration
15238 $(SRCDIR)/configure \
15239 --enable-languages=all \
15240 --prefix=$(DESTDIR)
15244 # Both of the above are configured to install to $(DESTDIR)
15245 # Install the configuration with --enable-host-shared first
15246 # *then* the one without, so that the faster build
15247 # of "cc1" et al overwrites the slower build.
15248 pushd configuration-for-jit
15252 pushd standard-configuration
15259 @node Overview of code structure,Design notes,Packaging notes,Internals
15260 @anchor{internals/index overview-of-code-structure}@anchor{1e8}
15261 @section Overview of code structure
15264 The library is implemented in C++. The source files have the @code{.c}
15265 extension for legacy reasons.
15271 @code{libgccjit.c} implements the API entrypoints. It performs error
15272 checking, then calls into classes of the gcc::jit::recording namespace
15273 within @code{jit-recording.c} and @code{jit-recording.h}.
15276 The gcc::jit::recording classes (within @code{jit-recording.c} and
15277 @code{jit-recording.h}) record the API calls that are made:
15283 /* Indentation indicates inheritance: */
15289 class function_type;
15290 class compound_type;
15304 class function_pointer;
15315 When the context is compiled, the gcc::jit::playback classes (within
15316 @code{jit-playback.c} and @code{jit-playback.h}) replay the API calls
15317 within langhook:parse_file:
15323 /* Indentation indicates inheritance: */
15327 class compound_type;
15345 Client Code . Generated . libgccjit.so
15347 . . JIT API . JIT "Frontend". (libbackend.a)
15348 ....................................................................................
15350 ──────────────────────────> . .
15353 . . ──> libgccjit.c .
15354 . . │ (error-checking).
15356 . . ──> jit-recording.c
15357 . . (record API calls)
15358 . . <─────── .
15360 <─────────────────────────── . .
15363 V . . gcc_jit_context_compile .
15364 ──────────────────────────> . .
15365 . . │ start of recording::context::compile ()
15367 . . │ start of playback::context::compile ()
15368 . . │ (create tempdir) .
15370 . . │ ACQUIRE MUTEX .
15372 . . V───────────────────────> toplev::main (for now)
15374 . . . . (various code)
15377 . . . <───────────────── langhook:parse_file
15379 . . . │ (jit_langhook_parse_file)
15381 ..........................................│..................VVVVVVVVVVVVV...
15382 . . . │ . No GC in here
15383 . . . │ jit-playback.c
15384 . . . │ (playback of API calls)
15385 . . . ───────────────> creation of functions,
15386 . . . . types, expression trees
15387 . . . <──────────────── etc
15388 . . . │(handle_locations: add locations to
15389 . . . │ linemap and associate them with trees)
15391 . . . │ . No GC in here
15392 ..........................................│..................AAAAAAAAAAAAA...
15393 . . . │ for each function
15394 . . . ──> postprocess
15396 . . . ────────────> cgraph_finalize_function
15397 . . . <────────────
15400 . . . ──────────────────> (end of
15401 . . . . │ langhook_parse_file)
15403 . . . . (various code)
15406 . . . <───────────────── langhook:write_globals
15408 . . . │ (jit_langhook_write_globals)
15411 . . . ──────────────────> finalize_compilation_unit
15413 . . . . (the middle─end and backend)
15415 . . <───────────────────────────── end of toplev::main
15417 . . V───────────────────────> toplev::finalize
15418 . . . . │ (purge internal state)
15419 . . <──────────────────────── end of toplev::finalize
15421 . . V─> playback::context::postprocess:
15423 . . │ (assuming an in-memory compile):
15425 . . --> Convert assembler to DSO, via embedded
15426 . . copy of driver:
15427 . . driver::main ()
15428 . . invocation of "as"
15429 . . invocation of "ld"
15430 . . driver::finalize ()
15433 . . │ . Load DSO (dlopen "fake.so")
15435 . . │ . Bundle it up in a jit::result
15438 . . │ RELEASE MUTEX .
15440 . . │ end of playback::context::compile ()
15442 . . │ playback::context dtor
15444 . . │ Normally we cleanup the tempdir here:
15445 . . │ ("fake.so" is unlinked from the
15446 . . │ filesystem at this point)
15447 . . │ If the client code requested debuginfo, the
15448 . . │ cleanup happens later (in gcc_jit_result_release)
15449 . . │ to make it easier on the debugger (see PR jit/64206)
15452 . . │ end of recording::context::compile ()
15453 <─────────────────────────── . .
15455 V . . gcc_jit_result_get_code .
15456 ──────────────────────────> . .
15457 . . │ dlsym () within loaded DSO
15458 <─────────────────────────── . .
15461 │ Call it . . . .
15462 ───────────────> . . .
15465 <─────────────── . . .
15469 V . . gcc_jit_result_release .
15470 ──────────────────────────> . .
15471 . . │ dlclose () the loaded DSO
15472 . . │ (code becomes uncallable)
15474 . . │ If the client code requested debuginfo, then
15475 . . │ cleanup of the tempdir was delayed.
15476 . . │ If that was the case, clean it up now.
15477 <─────────────────────────── . .
15486 Here is a high-level summary from @code{jit-common.h}:
15490 In order to allow jit objects to be usable outside of a compile
15491 whilst working with the existing structure of GCC's code the
15492 C API is implemented in terms of a gcc::jit::recording::context,
15493 which records the calls made to it.
15495 When a gcc_jit_context is compiled, the recording context creates a
15496 playback context. The playback context invokes the bulk of the GCC
15497 code, and within the "frontend" parsing hook, plays back the recorded
15498 API calls, creating GCC tree objects.
15500 So there are two parallel families of classes: those relating to
15501 recording, and those relating to playback:
15507 Visibility: recording objects are exposed back to client code,
15508 whereas playback objects are internal to the library.
15511 Lifetime: recording objects have a lifetime equal to that of the
15512 recording context that created them, whereas playback objects only
15513 exist within the frontend hook.
15516 Memory allocation: recording objects are allocated by the recording
15517 context, and automatically freed by it when the context is released,
15518 whereas playback objects are allocated within the GC heap, and
15519 garbage-collected; they can own GC-references.
15522 Integration with rest of GCC: recording objects are unrelated to the
15523 rest of GCC, whereas playback objects are wrappers around "tree"
15524 instances. Hence you can't ask a recording rvalue or lvalue what its
15525 type is, whereas you can for a playback rvalue of lvalue (since it
15526 can work with the underlying GCC tree nodes).
15529 Instancing: There can be multiple recording contexts "alive" at once
15530 (albeit it only one compiling at once), whereas there can only be one
15531 playback context alive at one time (since it interacts with the GC).
15534 Ultimately if GCC could support multiple GC heaps and contexts, and
15535 finer-grained initialization, then this recording vs playback
15536 distinction could be eliminated.
15538 During a playback, we associate objects from the recording with
15539 their counterparts during this playback. For simplicity, we store this
15540 within the recording objects, as @code{void *m_playback_obj}, casting it to
15541 the appropriate playback object subclass. For these casts to make
15542 sense, the two class hierarchies need to have the same structure.
15544 Note that the playback objects that @code{m_playback_obj} points to are
15545 GC-allocated, but the recording objects don't own references:
15546 these associations only exist within a part of the code where
15547 the GC doesn't collect, and are set back to NULL before the GC can
15550 @anchor{internals/index example-of-log-file}@anchor{5c}
15551 Another way to understand the structure of the code is to enable logging,
15552 via @pxref{5b,,gcc_jit_context_set_logfile()}. Here is an example of a log
15553 generated via this call:
15556 JIT: libgccjit (GCC) version 6.0.0 20150803 (experimental) (x86_64-pc-linux-gnu)
15557 JIT: compiled by GNU C version 4.8.3 20140911 (Red Hat 4.8.3-7), GMP version 5.1.2, MPFR version 3.1.2, MPC version 1.0.1
15558 JIT: entering: gcc_jit_context_set_str_option
15559 JIT: GCC_JIT_STR_OPTION_PROGNAME: "./test-hello-world.c.exe"
15560 JIT: exiting: gcc_jit_context_set_str_option
15561 JIT: entering: gcc_jit_context_set_int_option
15562 JIT: GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL: 3
15563 JIT: exiting: gcc_jit_context_set_int_option
15564 JIT: entering: gcc_jit_context_set_bool_option
15565 JIT: GCC_JIT_BOOL_OPTION_DEBUGINFO: true
15566 JIT: exiting: gcc_jit_context_set_bool_option
15567 JIT: entering: gcc_jit_context_set_bool_option
15568 JIT: GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE: false
15569 JIT: exiting: gcc_jit_context_set_bool_option
15570 JIT: entering: gcc_jit_context_set_bool_option
15571 JIT: GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE: false
15572 JIT: exiting: gcc_jit_context_set_bool_option
15573 JIT: entering: gcc_jit_context_set_bool_option
15574 JIT: GCC_JIT_BOOL_OPTION_SELFCHECK_GC: true
15575 JIT: exiting: gcc_jit_context_set_bool_option
15576 JIT: entering: gcc_jit_context_set_bool_option
15577 JIT: GCC_JIT_BOOL_OPTION_DUMP_SUMMARY: false
15578 JIT: exiting: gcc_jit_context_set_bool_option
15579 JIT: entering: gcc_jit_context_get_type
15580 JIT: exiting: gcc_jit_context_get_type
15581 JIT: entering: gcc_jit_context_get_type
15582 JIT: exiting: gcc_jit_context_get_type
15583 JIT: entering: gcc_jit_context_new_param
15584 JIT: exiting: gcc_jit_context_new_param
15585 JIT: entering: gcc_jit_context_new_function
15586 JIT: exiting: gcc_jit_context_new_function
15587 JIT: entering: gcc_jit_context_new_param
15588 JIT: exiting: gcc_jit_context_new_param
15589 JIT: entering: gcc_jit_context_get_type
15590 JIT: exiting: gcc_jit_context_get_type
15591 JIT: entering: gcc_jit_context_new_function
15592 JIT: exiting: gcc_jit_context_new_function
15593 JIT: entering: gcc_jit_context_new_string_literal
15594 JIT: exiting: gcc_jit_context_new_string_literal
15595 JIT: entering: gcc_jit_function_new_block
15596 JIT: exiting: gcc_jit_function_new_block
15597 JIT: entering: gcc_jit_block_add_comment
15598 JIT: exiting: gcc_jit_block_add_comment
15599 JIT: entering: gcc_jit_context_new_call
15600 JIT: exiting: gcc_jit_context_new_call
15601 JIT: entering: gcc_jit_block_add_eval
15602 JIT: exiting: gcc_jit_block_add_eval
15603 JIT: entering: gcc_jit_block_end_with_void_return
15604 JIT: exiting: gcc_jit_block_end_with_void_return
15605 JIT: entering: gcc_jit_context_dump_reproducer_to_file
15606 JIT: entering: void gcc::jit::recording::context::dump_reproducer_to_file(const char*)
15607 JIT: exiting: void gcc::jit::recording::context::dump_reproducer_to_file(const char*)
15608 JIT: exiting: gcc_jit_context_dump_reproducer_to_file
15609 JIT: entering: gcc_jit_context_compile
15610 JIT: in-memory compile of ctxt: 0x1283e20
15611 JIT: entering: gcc::jit::result* gcc::jit::recording::context::compile()
15612 JIT: GCC_JIT_STR_OPTION_PROGNAME: "./test-hello-world.c.exe"
15613 JIT: GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL: 3
15614 JIT: GCC_JIT_BOOL_OPTION_DEBUGINFO: true
15615 JIT: GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE: false
15616 JIT: GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE: false
15617 JIT: GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE: false
15618 JIT: GCC_JIT_BOOL_OPTION_DUMP_SUMMARY: false
15619 JIT: GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING: false
15620 JIT: GCC_JIT_BOOL_OPTION_SELFCHECK_GC: true
15621 JIT: GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES: false
15622 JIT: gcc_jit_context_set_bool_allow_unreachable_blocks: false
15623 JIT: gcc_jit_context_set_bool_use_external_driver: false
15624 JIT: entering: void gcc::jit::recording::context::validate()
15625 JIT: exiting: void gcc::jit::recording::context::validate()
15626 JIT: entering: gcc::jit::playback::context::context(gcc::jit::recording::context*)
15627 JIT: exiting: gcc::jit::playback::context::context(gcc::jit::recording::context*)
15628 JIT: entering: gcc::jit::playback::compile_to_memory::compile_to_memory(gcc::jit::recording::context*)
15629 JIT: exiting: gcc::jit::playback::compile_to_memory::compile_to_memory(gcc::jit::recording::context*)
15630 JIT: entering: void gcc::jit::playback::context::compile()
15631 JIT: entering: gcc::jit::tempdir::tempdir(gcc::jit::logger*, int)
15632 JIT: exiting: gcc::jit::tempdir::tempdir(gcc::jit::logger*, int)
15633 JIT: entering: bool gcc::jit::tempdir::create()
15634 JIT: m_path_template: /tmp/libgccjit-XXXXXX
15635 JIT: m_path_tempdir: /tmp/libgccjit-CKq1M9
15636 JIT: exiting: bool gcc::jit::tempdir::create()
15637 JIT: entering: void gcc::jit::playback::context::acquire_mutex()
15638 JIT: exiting: void gcc::jit::playback::context::acquire_mutex()
15639 JIT: entering: void gcc::jit::playback::context::make_fake_args(vec<char*>*, const char*, vec<gcc::jit::recording::requested_dump>*)
15640 JIT: reusing cached configure-time options
15641 JIT: configure_time_options[0]: -mtune=generic
15642 JIT: configure_time_options[1]: -march=x86-64
15643 JIT: exiting: void gcc::jit::playback::context::make_fake_args(vec<char*>*, const char*, vec<gcc::jit::recording::requested_dump>*)
15644 JIT: entering: toplev::main
15645 JIT: argv[0]: ./test-hello-world.c.exe
15646 JIT: argv[1]: /tmp/libgccjit-CKq1M9/fake.c
15647 JIT: argv[2]: -fPIC
15650 JIT: argv[5]: -quiet
15651 JIT: argv[6]: --param
15652 JIT: argv[7]: ggc-min-expand=0
15653 JIT: argv[8]: --param
15654 JIT: argv[9]: ggc-min-heapsize=0
15655 JIT: argv[10]: -mtune=generic
15656 JIT: argv[11]: -march=x86-64
15657 JIT: entering: bool jit_langhook_init()
15658 JIT: exiting: bool jit_langhook_init()
15659 JIT: entering: void gcc::jit::playback::context::replay()
15660 JIT: entering: void gcc::jit::recording::context::replay_into(gcc::jit::replayer*)
15661 JIT: exiting: void gcc::jit::recording::context::replay_into(gcc::jit::replayer*)
15662 JIT: entering: void gcc::jit::recording::context::disassociate_from_playback()
15663 JIT: exiting: void gcc::jit::recording::context::disassociate_from_playback()
15664 JIT: entering: void gcc::jit::playback::context::handle_locations()
15665 JIT: exiting: void gcc::jit::playback::context::handle_locations()
15666 JIT: entering: void gcc::jit::playback::function::build_stmt_list()
15667 JIT: exiting: void gcc::jit::playback::function::build_stmt_list()
15668 JIT: entering: void gcc::jit::playback::function::build_stmt_list()
15669 JIT: exiting: void gcc::jit::playback::function::build_stmt_list()
15670 JIT: entering: void gcc::jit::playback::function::postprocess()
15671 JIT: exiting: void gcc::jit::playback::function::postprocess()
15672 JIT: entering: void gcc::jit::playback::function::postprocess()
15673 JIT: exiting: void gcc::jit::playback::function::postprocess()
15674 JIT: exiting: void gcc::jit::playback::context::replay()
15675 JIT: exiting: toplev::main
15676 JIT: entering: void gcc::jit::playback::context::extract_any_requested_dumps(vec<gcc::jit::recording::requested_dump>*)
15677 JIT: exiting: void gcc::jit::playback::context::extract_any_requested_dumps(vec<gcc::jit::recording::requested_dump>*)
15678 JIT: entering: toplev::finalize
15679 JIT: exiting: toplev::finalize
15680 JIT: entering: virtual void gcc::jit::playback::compile_to_memory::postprocess(const char*)
15681 JIT: entering: void gcc::jit::playback::context::convert_to_dso(const char*)
15682 JIT: entering: void gcc::jit::playback::context::invoke_driver(const char*, const char*, const char*, timevar_id_t, bool, bool)
15683 JIT: entering: void gcc::jit::playback::context::add_multilib_driver_arguments(vec<char*>*)
15684 JIT: exiting: void gcc::jit::playback::context::add_multilib_driver_arguments(vec<char*>*)
15685 JIT: argv[0]: x86_64-unknown-linux-gnu-gcc-6.0.0
15687 JIT: argv[2]: -shared
15688 JIT: argv[3]: /tmp/libgccjit-CKq1M9/fake.s
15690 JIT: argv[5]: /tmp/libgccjit-CKq1M9/fake.so
15691 JIT: argv[6]: -fno-use-linker-plugin
15692 JIT: entering: void gcc::jit::playback::context::invoke_embedded_driver(const vec<char*>*)
15693 JIT: exiting: void gcc::jit::playback::context::invoke_embedded_driver(const vec<char*>*)
15694 JIT: exiting: void gcc::jit::playback::context::invoke_driver(const char*, const char*, const char*, timevar_id_t, bool, bool)
15695 JIT: exiting: void gcc::jit::playback::context::convert_to_dso(const char*)
15696 JIT: entering: gcc::jit::result* gcc::jit::playback::context::dlopen_built_dso()
15697 JIT: GCC_JIT_BOOL_OPTION_DEBUGINFO was set: handing over tempdir to jit::result
15698 JIT: entering: gcc::jit::result::result(gcc::jit::logger*, void*, gcc::jit::tempdir*)
15699 JIT: exiting: gcc::jit::result::result(gcc::jit::logger*, void*, gcc::jit::tempdir*)
15700 JIT: exiting: gcc::jit::result* gcc::jit::playback::context::dlopen_built_dso()
15701 JIT: exiting: virtual void gcc::jit::playback::compile_to_memory::postprocess(const char*)
15702 JIT: entering: void gcc::jit::playback::context::release_mutex()
15703 JIT: exiting: void gcc::jit::playback::context::release_mutex()
15704 JIT: exiting: void gcc::jit::playback::context::compile()
15705 JIT: entering: gcc::jit::playback::context::~context()
15706 JIT: exiting: gcc::jit::playback::context::~context()
15707 JIT: exiting: gcc::jit::result* gcc::jit::recording::context::compile()
15708 JIT: gcc_jit_context_compile: returning (gcc_jit_result *)0x12f75d0
15709 JIT: exiting: gcc_jit_context_compile
15710 JIT: entering: gcc_jit_result_get_code
15711 JIT: locating fnname: hello_world
15712 JIT: entering: void* gcc::jit::result::get_code(const char*)
15713 JIT: exiting: void* gcc::jit::result::get_code(const char*)
15714 JIT: gcc_jit_result_get_code: returning (void *)0x7ff6b8cd87f0
15715 JIT: exiting: gcc_jit_result_get_code
15716 JIT: entering: gcc_jit_context_release
15717 JIT: deleting ctxt: 0x1283e20
15718 JIT: entering: gcc::jit::recording::context::~context()
15719 JIT: exiting: gcc::jit::recording::context::~context()
15720 JIT: exiting: gcc_jit_context_release
15721 JIT: entering: gcc_jit_result_release
15722 JIT: deleting result: 0x12f75d0
15723 JIT: entering: virtual gcc::jit::result::~result()
15724 JIT: entering: gcc::jit::tempdir::~tempdir()
15725 JIT: unlinking .s file: /tmp/libgccjit-CKq1M9/fake.s
15726 JIT: unlinking .so file: /tmp/libgccjit-CKq1M9/fake.so
15727 JIT: removing tempdir: /tmp/libgccjit-CKq1M9
15728 JIT: exiting: gcc::jit::tempdir::~tempdir()
15729 JIT: exiting: virtual gcc::jit::result::~result()
15730 JIT: exiting: gcc_jit_result_release
15731 JIT: gcc::jit::logger::~logger()
15737 @node Design notes,Submitting patches,Overview of code structure,Internals
15738 @anchor{internals/index design-notes}@anchor{1e9}
15739 @section Design notes
15742 It should not be possible for client code to cause an internal compiler
15743 error. If this @emph{does} happen, the root cause should be isolated (perhaps
15744 using @pxref{5d,,gcc_jit_context_dump_reproducer_to_file()}) and the cause
15745 should be rejected via additional checking. The checking ideally should
15746 be within the libgccjit API entrypoints in libgccjit.c, since this is as
15747 close as possible to the error; failing that, a good place is within
15748 @code{recording::context::validate ()} in jit-recording.c.
15750 @node Submitting patches,,Design notes,Internals
15751 @anchor{internals/index submitting-patches}@anchor{1ea}
15752 @section Submitting patches
15755 Please read the contribution guidelines for gcc at
15756 @indicateurl{https://gcc.gnu.org/contribute.html}.
15758 Patches for the jit should be sent to both the
15759 @email{gcc-patches@@gcc.gnu.org} and @email{jit@@gcc.gnu.org} mailing lists,
15760 with "jit" and "PATCH" in the Subject line.
15762 You don't need to do a full bootstrap for code that just touches the
15763 @code{jit} and @code{testsuite/jit.dg} subdirectories. However, please run
15764 @code{make check-jit} before submitting the patch, and mention the results
15765 in your email (along with the host triple that the tests were run on).
15767 A good patch should contain the information listed in the
15768 gcc contribution guide linked to above; for a @code{jit} patch, the patch
15777 the code itself (for example, a new API entrypoint will typically
15778 touch @code{libgccjit.h} and @code{.c}, along with support code in
15779 @code{jit-recording.[ch]} and @code{jit-playback.[ch]} as appropriate)
15785 documentation for the C API
15788 documentation for the C++ API
15792 A patch that adds new API entrypoints should also contain:
15800 a feature macro in @code{libgccjit.h} so that client code that doesn't
15801 use a "configure" mechanism can still easily detect the presence of
15802 the entrypoint. See e.g. @code{LIBGCCJIT_HAVE_SWITCH_STATEMENTS} (for
15803 a category of entrypoints) and
15804 @code{LIBGCCJIT_HAVE_gcc_jit_context_set_bool_allow_unreachable_blocks}
15805 (for an individual entrypoint).
15808 a new ABI tag containing the new symbols (in @code{libgccjit.map}), so
15809 that we can detect client code that uses them
15812 Support for @pxref{5d,,gcc_jit_context_dump_reproducer_to_file()}. Most
15813 jit testcases attempt to dump their contexts to a .c file; @code{jit.exp}
15814 then sanity-checks the generated c by compiling them (though
15815 not running them). A new API entrypoint
15816 needs to "know" how to write itself back out to C (by implementing
15817 @code{gcc::jit::recording::memento::write_reproducer} for the appropriate
15818 @code{memento} subclass).
15821 C++ bindings for the new entrypoints (see @code{libgccjit++.h}); ideally
15822 with test coverage, though the C++ API test coverage is admittedly
15823 spotty at the moment
15826 documentation for the new C entrypoints
15829 documentation for the new C++ entrypoints
15832 documentation for the new ABI tag (see @code{topics/compatibility.rst}).
15836 Depending on the patch you can either extend an existing test case, or
15837 add a new test case. If you add an entirely new testcase: @code{jit.exp}
15838 expects jit testcases to begin with @code{test-}, or @code{test-error-} (for a
15839 testcase that generates an error on a @pxref{8,,gcc_jit_context}).
15841 Every new testcase that doesn't generate errors should also touch
15842 @code{gcc/testsuite/jit.dg/all-non-failing-tests.h}:
15850 Testcases that don't generate errors should ideally be added to the
15851 @code{testcases} array in that file; this means that, in addition
15852 to being run standalone, they also get run within
15853 @code{test-combination.c} (which runs all successful tests inside one
15854 big @pxref{8,,gcc_jit_context}), and @code{test-threads.c} (which runs all
15855 successful tests in one process, each one running in a different
15856 thread on a different @pxref{8,,gcc_jit_context}).
15860 Given that exported functions within a @pxref{8,,gcc_jit_context}
15861 must have unique names, and most testcases are run within
15862 @code{test-combination.c}, this means that every jit-compiled test
15863 function typically needs a name that's unique across the entire
15869 Testcases that aren't to be added to the @code{testcases} array should
15870 instead add a comment to the file clarifying why they're not in that
15871 array. See the file for examples.
15875 Typically a patch that touches the .rst documentation will also need the
15876 texinfo to be regenerated. You can do this with
15877 Sphinx 1.0@footnote{http://sphinx-doc.org/} or later by
15878 running @code{make texinfo} within @code{SRCDIR/gcc/jit/docs}. Don't do this
15879 within the patch sent to the mailing list; it can often be relatively
15880 large and inconsequential (e.g. anchor renumbering), rather like generated
15881 "configure" changes from configure.ac. You can regenerate it when
15884 @node Indices and tables,Index,Internals,Top
15885 @anchor{index indices-and-tables}@anchor{1eb}
15886 @unnumbered Indices and tables
15904 @c The Sphinx C domain appears to lack explicit support for enum values,
15905 @c so I've been using :c:macro: for them.
15907 @c See http://sphinx-doc.org/domains.html#the-c-domain
15909 @node Index,,Indices and tables,Top