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 5.0.0 (experimental 20141210), December 10, 2014
26 Copyright @copyright{} 2014, Free Software Foundation
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 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 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.
123 Tutorial part 2: Creating a trivial machine code function
129 Tutorial part 3: Loops and variables
131 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues.
133 * Visualizing the control flow graph::
134 * Full example: Full example<2>.
136 Tutorial part 4: Adding JIT-compilation to a toy interpreter
138 * Our toy interpreter::
139 * Compiling to machine code::
140 * Setting things up::
141 * Populating the function::
142 * Verifying the control flow graph::
143 * Compiling the context::
144 * Single-stepping through the generated code::
145 * Examining the generated code::
146 * Putting it all together::
147 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?.
149 Behind the curtain: How does our code get optimized?
151 * Optimizing away stack manipulation::
152 * Elimination of tail recursion::
156 * Compilation contexts::
160 * Creating and using functions::
162 * Compilation results::
166 * Lifetime-management::
168 * Error-handling: Error-handling<2>.
170 * Options: Options<2>.
181 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile.
182 * Structures and unions::
188 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions.
192 * Simple expressions::
194 * Binary Operations::
203 Creating and using functions
214 C++ bindings for libgccjit
216 * Tutorial: Tutorial<2>.
217 * Topic Reference: Topic Reference<2>.
221 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world"<2>.
222 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function<2>.
223 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables<2>.
224 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>.
226 Tutorial part 2: Creating a trivial machine code function
228 * Options: Options<3>.
229 * Full example: Full example<3>.
231 Tutorial part 3: Loops and variables
233 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues<2>.
234 * Control flow: Control flow<2>.
235 * Visualizing the control flow graph: Visualizing the control flow graph<2>.
236 * Full example: Full example<4>.
238 Tutorial part 4: Adding JIT-compilation to a toy interpreter
240 * Our toy interpreter: Our toy interpreter<2>.
241 * Compiling to machine code: Compiling to machine code<2>.
242 * Setting things up: Setting things up<2>.
243 * Populating the function: Populating the function<2>.
244 * Verifying the control flow graph: Verifying the control flow graph<2>.
245 * Compiling the context: Compiling the context<2>.
246 * Single-stepping through the generated code: Single-stepping through the generated code<2>.
247 * Examining the generated code: Examining the generated code<2>.
248 * Putting it all together: Putting it all together<2>.
249 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?<2>.
251 Behind the curtain: How does our code get optimized?
253 * Optimizing away stack manipulation: Optimizing away stack manipulation<2>.
254 * Elimination of tail recursion: Elimination of tail recursion<2>.
258 * Compilation contexts: Compilation contexts<2>.
259 * Objects: Objects<2>.
261 * Expressions: Expressions<2>.
262 * Creating and using functions: Creating and using functions<2>.
263 * Source Locations: Source Locations<2>.
264 * Compilation results: Compilation results<2>.
268 * Lifetime-management: Lifetime-management<2>.
269 * Thread-safety: Thread-safety<2>.
270 * Error-handling: Error-handling<3>.
271 * Debugging: Debugging<2>.
272 * Options: Options<4>.
276 * Boolean options: Boolean options<2>.
277 * Integer options: Integer options<2>.
281 * Standard types: Standard types<2>.
282 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile<2>.
283 * Structures and unions: Structures and unions<2>.
287 * Rvalues: Rvalues<2>.
288 * Lvalues: Lvalues<2>.
289 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions<2>.
293 * Simple expressions: Simple expressions<2>.
294 * Unary Operations: Unary Operations<2>.
295 * Binary Operations: Binary Operations<2>.
296 * Comparisons: Comparisons<2>.
297 * Function calls: Function calls<2>.
298 * Type-coercion: Type-coercion<2>.
302 * Global variables: Global variables<2>.
304 Creating and using functions
307 * Functions: Functions<2>.
309 * Statements: Statements<2>.
313 * Faking it: Faking it<2>.
317 * Working on the JIT library::
318 * Running the test suite::
319 * Environment variables::
320 * Overview of code structure::
322 Running the test suite
324 * Running under valgrind::
330 @node Tutorial,Topic Reference,Top,Top
331 @anchor{intro/index libgccjit}@anchor{1}@anchor{intro/index doc}@anchor{2}@anchor{intro/index tutorial}@anchor{3}
335 @c Copyright (C) 2014 Free Software Foundation, Inc.
336 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
338 @c This is free software: you can redistribute it and/or modify it
339 @c under the terms of the GNU General Public License as published by
340 @c the Free Software Foundation, either version 3 of the License, or
341 @c (at your option) any later version.
343 @c This program is distributed in the hope that it will be useful, but
344 @c WITHOUT ANY WARRANTY; without even the implied warranty of
345 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
346 @c General Public License for more details.
348 @c You should have received a copy of the GNU General Public License
349 @c along with this program. If not, see
350 @c <http://www.gnu.org/licenses/>.
353 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world".
354 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function.
355 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables.
356 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter.
360 @node Tutorial part 1 "Hello world",Tutorial part 2 Creating a trivial machine code function,,Tutorial
361 @anchor{intro/tutorial01 doc}@anchor{4}@anchor{intro/tutorial01 tutorial-part-1-hello-world}@anchor{5}
362 @section Tutorial part 1: "Hello world"
365 Before we look at the details of the API, let's look at building and
366 running programs that use the library.
368 Here's a toy "hello world" program that uses the library to synthesize
369 a call to @cite{printf} and uses it to write a message to stdout.
371 Don't worry about the content of the program for now; we'll cover
372 the details in later parts of this tutorial.
377 /* Smoketest example for libgccjit.so
378 Copyright (C) 2014 Free Software Foundation, Inc.
380 This file is part of GCC.
382 GCC is free software; you can redistribute it and/or modify it
383 under the terms of the GNU General Public License as published by
384 the Free Software Foundation; either version 3, or (at your option)
387 GCC is distributed in the hope that it will be useful, but
388 WITHOUT ANY WARRANTY; without even the implied warranty of
389 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
390 General Public License for more details.
392 You should have received a copy of the GNU General Public License
393 along with GCC; see the file COPYING3. If not see
394 <http://www.gnu.org/licenses/>. */
396 #include <libgccjit.h>
402 create_code (gcc_jit_context *ctxt)
404 /* Let's try to inject the equivalent of:
406 greet (const char *name)
408 printf ("hello %s\n", name);
411 gcc_jit_type *void_type =
412 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_VOID);
413 gcc_jit_type *const_char_ptr_type =
414 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_CONST_CHAR_PTR);
415 gcc_jit_param *param_name =
416 gcc_jit_context_new_param (ctxt, NULL, const_char_ptr_type, "name");
417 gcc_jit_function *func =
418 gcc_jit_context_new_function (ctxt, NULL,
419 GCC_JIT_FUNCTION_EXPORTED,
425 gcc_jit_param *param_format =
426 gcc_jit_context_new_param (ctxt, NULL, const_char_ptr_type, "format");
427 gcc_jit_function *printf_func =
428 gcc_jit_context_new_function (ctxt, NULL,
429 GCC_JIT_FUNCTION_IMPORTED,
430 gcc_jit_context_get_type (
431 ctxt, GCC_JIT_TYPE_INT),
435 gcc_jit_rvalue *args[2];
436 args[0] = gcc_jit_context_new_string_literal (ctxt, "hello %s\n");
437 args[1] = gcc_jit_param_as_rvalue (param_name);
439 gcc_jit_block *block = gcc_jit_function_new_block (func, NULL);
441 gcc_jit_block_add_eval (
443 gcc_jit_context_new_call (ctxt,
447 gcc_jit_block_end_with_void_return (block, NULL);
451 main (int argc, char **argv)
453 gcc_jit_context *ctxt;
454 gcc_jit_result *result;
456 /* Get a "context" object for working with the library. */
457 ctxt = gcc_jit_context_acquire ();
460 fprintf (stderr, "NULL ctxt");
464 /* Set some options on the context.
465 Let's see the code being generated, in assembler form. */
466 gcc_jit_context_set_bool_option (
468 GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
471 /* Populate the context. */
474 /* Compile the code. */
475 result = gcc_jit_context_compile (ctxt);
478 fprintf (stderr, "NULL result");
482 /* Extract the generated code from "result". */
483 typedef void (*fn_type) (const char *);
485 (fn_type)gcc_jit_result_get_code (result, "greet");
488 fprintf (stderr, "NULL greet");
492 /* Now call the generated function: */
496 gcc_jit_context_release (ctxt);
497 gcc_jit_result_release (result);
506 Copy the above to @cite{tut01-hello-world.c}.
508 Assuming you have the jit library installed, build the test program
513 tut01-hello-world.c \
514 -o tut01-hello-world \
520 You should then be able to run the built program:
523 $ ./tut01-hello-world
529 @c Copyright (C) 2014 Free Software Foundation, Inc.
530 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
532 @c This is free software: you can redistribute it and/or modify it
533 @c under the terms of the GNU General Public License as published by
534 @c the Free Software Foundation, either version 3 of the License, or
535 @c (at your option) any later version.
537 @c This program is distributed in the hope that it will be useful, but
538 @c WITHOUT ANY WARRANTY; without even the implied warranty of
539 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
540 @c General Public License for more details.
542 @c You should have received a copy of the GNU General Public License
543 @c along with this program. If not, see
544 @c <http://www.gnu.org/licenses/>.
546 @node Tutorial part 2 Creating a trivial machine code function,Tutorial part 3 Loops and variables,Tutorial part 1 "Hello world",Tutorial
547 @anchor{intro/tutorial02 doc}@anchor{6}@anchor{intro/tutorial02 tutorial-part-2-creating-a-trivial-machine-code-function}@anchor{7}
548 @section Tutorial part 2: Creating a trivial machine code function
551 Consider this C function:
562 How can we construct this at run-time using libgccjit?
564 First we need to include the relevant header:
567 #include <libgccjit.h>
572 All state associated with compilation is associated with a
573 @pxref{8,,gcc_jit_context *}.
575 Create one using @pxref{9,,gcc_jit_context_acquire()}:
578 gcc_jit_context *ctxt;
579 ctxt = gcc_jit_context_acquire ();
584 The JIT library has a system of types. It is statically-typed: every
585 expression is of a specific type, fixed at compile-time. In our example,
586 all of the expressions are of the C @cite{int} type, so let's obtain this from
587 the context, as a @pxref{a,,gcc_jit_type *}, using
588 @pxref{b,,gcc_jit_context_get_type()}:
591 gcc_jit_type *int_type =
592 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
597 @pxref{a,,gcc_jit_type *} is an example of a "contextual" object: every
598 entity in the API is associated with a @pxref{8,,gcc_jit_context *}.
600 Memory management is easy: all such "contextual" objects are automatically
601 cleaned up for you when the context is released, using
602 @pxref{c,,gcc_jit_context_release()}:
605 gcc_jit_context_release (ctxt);
610 so you don't need to manually track and cleanup all objects, just the
613 Although the API is C-based, there is a form of class hierarchy, which
631 There are casting methods for upcasting from subclasses to parent classes.
632 For example, @pxref{d,,gcc_jit_type_as_object()}:
635 gcc_jit_object *obj = gcc_jit_type_as_object (int_type);
640 One thing you can do with a @pxref{e,,gcc_jit_object *} is
641 to ask it for a human-readable description, using
642 @pxref{f,,gcc_jit_object_get_debug_string()}:
645 printf ("obj: %s\n", gcc_jit_object_get_debug_string (obj));
650 giving this text on stdout:
658 This is invaluable when debugging.
660 Let's create the function. To do so, we first need to construct
661 its single parameter, specifying its type and giving it a name,
662 using @pxref{10,,gcc_jit_context_new_param()}:
665 gcc_jit_param *param_i =
666 gcc_jit_context_new_param (ctxt, NULL, int_type, "i");
671 Now we can create the function, using
672 @pxref{11,,gcc_jit_context_new_function()}:
675 gcc_jit_function *func =
676 gcc_jit_context_new_function (ctxt, NULL,
677 GCC_JIT_FUNCTION_EXPORTED,
686 To define the code within the function, we must create basic blocks
687 containing statements.
689 Every basic block contains a list of statements, eventually terminated
690 by a statement that either returns, or jumps to another basic block.
692 Our function has no control-flow, so we just need one basic block:
695 gcc_jit_block *block = gcc_jit_function_new_block (func, NULL);
700 Our basic block is relatively simple: it immediately terminates by
701 returning the value of an expression.
703 We can build the expression using @pxref{12,,gcc_jit_context_new_binary_op()}:
706 gcc_jit_rvalue *expr =
707 gcc_jit_context_new_binary_op (
709 GCC_JIT_BINARY_OP_MULT, int_type,
710 gcc_jit_param_as_rvalue (param_i),
711 gcc_jit_param_as_rvalue (param_i));
716 A @pxref{13,,gcc_jit_rvalue *} is another example of a
717 @pxref{e,,gcc_jit_object *} subclass. We can upcast it using
718 @pxref{14,,gcc_jit_rvalue_as_object()} and as before print it with
719 @pxref{f,,gcc_jit_object_get_debug_string()}.
722 printf ("expr: %s\n",
723 gcc_jit_object_get_debug_string (
724 gcc_jit_rvalue_as_object (expr)));
737 Creating the expression in itself doesn't do anything; we have to add
738 this expression to a statement within the block. In this case, we use it
739 to build a return statement, which terminates the basic block:
742 gcc_jit_block_end_with_return (block, NULL, expr);
747 OK, we've populated the context. We can now compile it using
748 @pxref{15,,gcc_jit_context_compile()}:
751 gcc_jit_result *result;
752 result = gcc_jit_context_compile (ctxt);
757 and get a @pxref{16,,gcc_jit_result *}.
759 At this point we're done with the context; we can release it:
762 gcc_jit_context_release (ctxt);
767 We can now use @pxref{17,,gcc_jit_result_get_code()} to look up a specific
768 machine code routine within the result, in this case, the function we
772 void *fn_ptr = gcc_jit_result_get_code (result, "square");
775 fprintf (stderr, "NULL fn_ptr");
782 We can now cast the pointer to an appropriate function pointer type, and
786 typedef int (*fn_type) (int);
787 fn_type square = (fn_type)fn_ptr;
788 printf ("result: %d", square (5));
799 Once we're done with the code, we can release the result:
802 gcc_jit_result_release (result);
807 We can't call @code{square} anymore once we've released @code{result}.
816 @node Error-handling,Options,,Tutorial part 2 Creating a trivial machine code function
817 @anchor{intro/tutorial02 error-handling}@anchor{18}
818 @subsection Error-handling
821 Various kinds of errors are possible when using the API, such as
822 mismatched types in an assignment. You can only compile and get code
823 from a context if no errors occur.
825 Errors are printed on stderr; they typically contain the name of the API
826 entrypoint where the error occurred, and pertinent information on the
830 ./buggy-program: error: gcc_jit_block_add_assignment: mismatching types: assignment to i (type: int) from "hello world" (type: const char *)
835 The API is designed to cope with errors without crashing, so you can get
836 away with having a single error-handling check in your code:
839 void *fn_ptr = gcc_jit_result_get_code (result, "square");
842 fprintf (stderr, "NULL fn_ptr");
849 For more information, see the @pxref{19,,error-handling guide}
850 within the Topic eference.
852 @node Options,Full example,Error-handling,Tutorial part 2 Creating a trivial machine code function
853 @anchor{intro/tutorial02 options}@anchor{1a}
857 To get more information on what's going on, you can set debugging flags
858 on the context using @pxref{1b,,gcc_jit_context_set_bool_option()}.
860 @c (I'm deliberately not mentioning
861 @c :c:macro:`GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE` here since I think
862 @c it's probably more of use to implementors than to users)
864 Setting @pxref{1c,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE} will dump a
865 C-like representation to stderr when you compile (GCC's "GIMPLE"
869 gcc_jit_context_set_bool_option (
871 GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE,
873 result = gcc_jit_context_compile (ctxt);
879 square (signed int i)
891 We can see the generated machine code in assembler form (on stderr) by
892 setting @pxref{1d,,GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE} on the context
896 gcc_jit_context_set_bool_option (
898 GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
900 result = gcc_jit_context_compile (ctxt);
909 .type square, @@function
914 .cfi_def_cfa_offset 16
917 .cfi_def_cfa_register 6
927 .size square, .-square
928 .ident "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)"
929 .section .note.GNU-stack,"",@@progbits
934 By default, no optimizations are performed, the equivalent of GCC's
935 @cite{-O0} option. We can turn things up to e.g. @cite{-O3} by calling
936 @pxref{1e,,gcc_jit_context_set_int_option()} with
937 @pxref{1f,,GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}:
940 gcc_jit_context_set_int_option (
942 GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL,
953 .type square, @@function
963 .size square, .-square
964 .ident "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)"
965 .section .note.GNU-stack,"",@@progbits
970 Naturally this has only a small effect on such a trivial function.
972 @node Full example,,Options,Tutorial part 2 Creating a trivial machine code function
973 @anchor{intro/tutorial02 full-example}@anchor{20}
974 @subsection Full example
977 Here's what the above looks like as a complete program:
982 /* Usage example for libgccjit.so
983 Copyright (C) 2014 Free Software Foundation, Inc.
985 This file is part of GCC.
987 GCC is free software; you can redistribute it and/or modify it
988 under the terms of the GNU General Public License as published by
989 the Free Software Foundation; either version 3, or (at your option)
992 GCC is distributed in the hope that it will be useful, but
993 WITHOUT ANY WARRANTY; without even the implied warranty of
994 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
995 General Public License for more details.
997 You should have received a copy of the GNU General Public License
998 along with GCC; see the file COPYING3. If not see
999 <http://www.gnu.org/licenses/>. */
1001 #include <libgccjit.h>
1007 create_code (gcc_jit_context *ctxt)
1009 /* Let's try to inject the equivalent of:
1016 gcc_jit_type *int_type =
1017 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
1018 gcc_jit_param *param_i =
1019 gcc_jit_context_new_param (ctxt, NULL, int_type, "i");
1020 gcc_jit_function *func =
1021 gcc_jit_context_new_function (ctxt, NULL,
1022 GCC_JIT_FUNCTION_EXPORTED,
1028 gcc_jit_block *block = gcc_jit_function_new_block (func, NULL);
1030 gcc_jit_rvalue *expr =
1031 gcc_jit_context_new_binary_op (
1033 GCC_JIT_BINARY_OP_MULT, int_type,
1034 gcc_jit_param_as_rvalue (param_i),
1035 gcc_jit_param_as_rvalue (param_i));
1037 gcc_jit_block_end_with_return (block, NULL, expr);
1041 main (int argc, char **argv)
1043 gcc_jit_context *ctxt = NULL;
1044 gcc_jit_result *result = NULL;
1046 /* Get a "context" object for working with the library. */
1047 ctxt = gcc_jit_context_acquire ();
1050 fprintf (stderr, "NULL ctxt");
1054 /* Set some options on the context.
1055 Let's see the code being generated, in assembler form. */
1056 gcc_jit_context_set_bool_option (
1058 GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
1061 /* Populate the context. */
1064 /* Compile the code. */
1065 result = gcc_jit_context_compile (ctxt);
1068 fprintf (stderr, "NULL result");
1072 /* We're done with the context; we can release it: */
1073 gcc_jit_context_release (ctxt);
1076 /* Extract the generated code from "result". */
1077 void *fn_ptr = gcc_jit_result_get_code (result, "square");
1080 fprintf (stderr, "NULL fn_ptr");
1084 typedef int (*fn_type) (int);
1085 fn_type square = (fn_type)fn_ptr;
1086 printf ("result: %d\n", square (5));
1090 gcc_jit_context_release (ctxt);
1092 gcc_jit_result_release (result);
1101 Building and running it:
1109 # Run the built program:
1116 @c Copyright (C) 2014 Free Software Foundation, Inc.
1117 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
1119 @c This is free software: you can redistribute it and/or modify it
1120 @c under the terms of the GNU General Public License as published by
1121 @c the Free Software Foundation, either version 3 of the License, or
1122 @c (at your option) any later version.
1124 @c This program is distributed in the hope that it will be useful, but
1125 @c WITHOUT ANY WARRANTY; without even the implied warranty of
1126 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
1127 @c General Public License for more details.
1129 @c You should have received a copy of the GNU General Public License
1130 @c along with this program. If not, see
1131 @c <http://www.gnu.org/licenses/>.
1133 @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
1134 @anchor{intro/tutorial03 tutorial-part-3-loops-and-variables}@anchor{21}@anchor{intro/tutorial03 doc}@anchor{22}
1135 @section Tutorial part 3: Loops and variables
1138 Consider this C function:
1143 int loop_test (int n)
1146 for (int i = 0; i < n; i++)
1155 This example demonstrates some more features of libgccjit, with local
1156 variables and a loop.
1158 To break this down into libgccjit terms, it's usually easier to reword
1159 the @cite{for} loop as a @cite{while} loop, giving:
1164 int loop_test (int n)
1180 Here's what the final control flow graph will look like:
1187 @image{sum-of-squares,,,image of a control flow graph,png}
1193 As before, we include the libgccjit header and make a
1194 @pxref{8,,gcc_jit_context *}.
1197 #include <libgccjit.h>
1201 gcc_jit_context *ctxt;
1202 ctxt = gcc_jit_context_acquire ();
1207 The function works with the C @cite{int} type:
1210 gcc_jit_type *the_type =
1211 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
1212 gcc_jit_type *return_type = the_type;
1217 though we could equally well make it work on, say, @cite{double}:
1220 gcc_jit_type *the_type =
1221 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_DOUBLE);
1226 Let's build the function:
1230 gcc_jit_context_new_param (ctxt, NULL, the_type, "n");
1231 gcc_jit_param *params[1] = @{n@};
1232 gcc_jit_function *func =
1233 gcc_jit_context_new_function (ctxt, NULL,
1234 GCC_JIT_FUNCTION_EXPORTED,
1243 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues.
1245 * Visualizing the control flow graph::
1246 * Full example: Full example<2>.
1250 @node Expressions lvalues and rvalues,Control flow,,Tutorial part 3 Loops and variables
1251 @anchor{intro/tutorial03 expressions-lvalues-and-rvalues}@anchor{23}
1252 @subsection Expressions: lvalues and rvalues
1255 The base class of expression is the @pxref{13,,gcc_jit_rvalue *},
1256 representing an expression that can be on the @emph{right}-hand side of
1257 an assignment: a value that can be computed somehow, and assigned
1258 @emph{to} a storage area (such as a variable). It has a specific
1259 @pxref{a,,gcc_jit_type *}.
1261 Anothe important class is @pxref{24,,gcc_jit_lvalue *}.
1262 A @pxref{24,,gcc_jit_lvalue *}. is something that can of the @emph{left}-hand
1263 side of an assignment: a storage area (such as a variable).
1265 In other words, every assignment can be thought of as:
1273 Note that @pxref{24,,gcc_jit_lvalue *} is a subclass of
1274 @pxref{13,,gcc_jit_rvalue *}, where in an assignment of the form:
1277 LVALUE_A = LVALUE_B;
1282 the @cite{LVALUE_B} implies reading the current value of that storage
1283 area, assigning it into the @cite{LVALUE_A}.
1285 So far the only expressions we've seen are @cite{i * i}:
1288 gcc_jit_rvalue *expr =
1289 gcc_jit_context_new_binary_op (
1291 GCC_JIT_BINARY_OP_MULT, int_type,
1292 gcc_jit_param_as_rvalue (param_i),
1293 gcc_jit_param_as_rvalue (param_i));
1298 which is a @pxref{13,,gcc_jit_rvalue *}, and the various function
1299 parameters: @cite{param_i} and @cite{param_n}, instances of
1300 @pxref{25,,gcc_jit_param *}, which is a subclass of
1301 @pxref{24,,gcc_jit_lvalue *} (and, in turn, of @pxref{13,,gcc_jit_rvalue *}):
1302 we can both read from and write to function parameters within the
1305 Our new example has a couple of local variables. We create them by
1306 calling @pxref{26,,gcc_jit_function_new_local()}, supplying a type and a
1312 gcc_jit_function_new_local (func, NULL, the_type, "i");
1313 gcc_jit_lvalue *sum =
1314 gcc_jit_function_new_local (func, NULL, the_type, "sum");
1319 These are instances of @pxref{24,,gcc_jit_lvalue *} - they can be read from
1322 Note that there is no precanned way to create @emph{and} initialize a variable
1331 Instead, having added the local to the function, we have to separately add
1332 an assignment of @cite{0} to @cite{local_i} at the beginning of the function.
1334 @node Control flow,Visualizing the control flow graph,Expressions lvalues and rvalues,Tutorial part 3 Loops and variables
1335 @anchor{intro/tutorial03 control-flow}@anchor{27}
1336 @subsection Control flow
1339 This function has a loop, so we need to build some basic blocks to
1340 handle the control flow. In this case, we need 4 blocks:
1346 before the loop (initializing the locals)
1349 the conditional at the top of the loop (comparing @cite{i < n})
1352 the body of the loop
1355 after the loop terminates (@cite{return sum})
1358 so we create these as @pxref{28,,gcc_jit_block *} instances within the
1359 @pxref{29,,gcc_jit_function *}:
1362 gcc_jit_block *b_initial =
1363 gcc_jit_function_new_block (func, "initial");
1364 gcc_jit_block *b_loop_cond =
1365 gcc_jit_function_new_block (func, "loop_cond");
1366 gcc_jit_block *b_loop_body =
1367 gcc_jit_function_new_block (func, "loop_body");
1368 gcc_jit_block *b_after_loop =
1369 gcc_jit_function_new_block (func, "after_loop");
1374 We now populate each block with statements.
1376 The entry block @cite{b_initial} consists of initializations followed by a jump
1377 to the conditional. We assign @cite{0} to @cite{i} and to @cite{sum}, using
1378 @pxref{2a,,gcc_jit_block_add_assignment()} to add
1379 an assignment statement, and using @pxref{2b,,gcc_jit_context_zero()} to get
1380 the constant value @cite{0} for the relevant type for the right-hand side of
1385 gcc_jit_block_add_assignment (
1388 gcc_jit_context_zero (ctxt, the_type));
1391 gcc_jit_block_add_assignment (
1394 gcc_jit_context_zero (ctxt, the_type));
1399 We can then terminate the entry block by jumping to the conditional:
1402 gcc_jit_block_end_with_jump (b_initial, NULL, b_loop_cond);
1407 The conditional block is equivalent to the line @cite{while (i < n)} from our
1408 C example. It contains a single statement: a conditional, which jumps to
1409 one of two destination blocks depending on a boolean
1410 @pxref{13,,gcc_jit_rvalue *}, in this case the comparison of @cite{i} and @cite{n}.
1411 We build the comparison using @pxref{2c,,gcc_jit_context_new_comparison()}:
1414 gcc_jit_rvalue *guard =
1415 gcc_jit_context_new_comparison (
1417 GCC_JIT_COMPARISON_GE,
1418 gcc_jit_lvalue_as_rvalue (i),
1419 gcc_jit_param_as_rvalue (n));
1424 and can then use this to add @cite{b_loop_cond}'s sole statement, via
1425 @pxref{2d,,gcc_jit_block_end_with_conditional()}:
1428 gcc_jit_block_end_with_conditional (b_loop_cond, NULL, guard);
1433 Next, we populate the body of the loop.
1435 The C statement @cite{sum += i * i;} is an assignment operation, where an
1436 lvalue is modified "in-place". We use
1437 @pxref{2e,,gcc_jit_block_add_assignment_op()} to handle these operations:
1441 gcc_jit_block_add_assignment_op (
1444 GCC_JIT_BINARY_OP_PLUS,
1445 gcc_jit_context_new_binary_op (
1447 GCC_JIT_BINARY_OP_MULT, the_type,
1448 gcc_jit_lvalue_as_rvalue (i),
1449 gcc_jit_lvalue_as_rvalue (i)));
1454 The @cite{i++} can be thought of as @cite{i += 1}, and can thus be handled in
1455 a similar way. We use @pxref{2f,,gcc_jit_context_one()} to get the constant
1456 value @cite{1} (for the relevant type) for the right-hand side
1461 gcc_jit_block_add_assignment_op (
1464 GCC_JIT_BINARY_OP_PLUS,
1465 gcc_jit_context_one (ctxt, the_type));
1472 For numeric constants other than 0 or 1, we could use
1473 @pxref{30,,gcc_jit_context_new_rvalue_from_int()} and
1474 @pxref{31,,gcc_jit_context_new_rvalue_from_double()}.
1478 The loop body completes by jumping back to the conditional:
1481 gcc_jit_block_end_with_jump (b_loop_body, NULL, b_loop_cond);
1486 Finally, we populate the @cite{b_after_loop} block, reached when the loop
1487 conditional is false. We want to generate the equivalent of:
1495 so the block is just one statement:
1499 gcc_jit_block_end_with_return (
1502 gcc_jit_lvalue_as_rvalue (sum));
1509 You can intermingle block creation with statement creation,
1510 but given that the terminator statements generally include references
1511 to other blocks, I find it's clearer to create all the blocks,
1512 @emph{then} all the statements.
1516 We've finished populating the function. As before, we can now compile it
1520 gcc_jit_result *result;
1521 result = gcc_jit_context_compile (ctxt);
1523 typedef int (*loop_test_fn_type) (int);
1524 loop_test_fn_type loop_test =
1525 (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
1528 printf ("result: %d", loop_test (10));
1539 @node Visualizing the control flow graph,Full example<2>,Control flow,Tutorial part 3 Loops and variables
1540 @anchor{intro/tutorial03 visualizing-the-control-flow-graph}@anchor{32}
1541 @subsection Visualizing the control flow graph
1544 You can see the control flow graph of a function using
1545 @pxref{33,,gcc_jit_function_dump_to_dot()}:
1548 gcc_jit_function_dump_to_dot (func, "/tmp/sum-of-squares.dot");
1553 giving a .dot file in GraphViz format.
1555 You can convert this to an image using @cite{dot}:
1558 $ dot -Tpng /tmp/sum-of-squares.dot -o /tmp/sum-of-squares.png
1563 or use a viewer (my preferred one is xdot.py; see
1564 @indicateurl{https://github.com/jrfonseca/xdot.py}; on Fedora you can
1565 install it with @cite{yum install python-xdot}):
1572 @image{sum-of-squares,,,image of a control flow graph,png}
1578 @node Full example<2>,,Visualizing the control flow graph,Tutorial part 3 Loops and variables
1579 @anchor{intro/tutorial03 full-example}@anchor{34}
1580 @subsection Full example
1586 /* Usage example for libgccjit.so
1587 Copyright (C) 2014 Free Software Foundation, Inc.
1589 This file is part of GCC.
1591 GCC is free software; you can redistribute it and/or modify it
1592 under the terms of the GNU General Public License as published by
1593 the Free Software Foundation; either version 3, or (at your option)
1596 GCC is distributed in the hope that it will be useful, but
1597 WITHOUT ANY WARRANTY; without even the implied warranty of
1598 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
1599 General Public License for more details.
1601 You should have received a copy of the GNU General Public License
1602 along with GCC; see the file COPYING3. If not see
1603 <http://www.gnu.org/licenses/>. */
1605 #include <libgccjit.h>
1611 create_code (gcc_jit_context *ctxt)
1614 Simple sum-of-squares, to test conditionals and looping
1616 int loop_test (int n)
1620 for (i = 0; i < n ; i ++)
1626 gcc_jit_type *the_type =
1627 gcc_jit_context_get_type (ctxt, GCC_JIT_TYPE_INT);
1628 gcc_jit_type *return_type = the_type;
1631 gcc_jit_context_new_param (ctxt, NULL, the_type, "n");
1632 gcc_jit_param *params[1] = @{n@};
1633 gcc_jit_function *func =
1634 gcc_jit_context_new_function (ctxt, NULL,
1635 GCC_JIT_FUNCTION_EXPORTED,
1642 gcc_jit_function_new_local (func, NULL, the_type, "i");
1643 gcc_jit_lvalue *sum =
1644 gcc_jit_function_new_local (func, NULL, the_type, "sum");
1646 gcc_jit_block *b_initial =
1647 gcc_jit_function_new_block (func, "initial");
1648 gcc_jit_block *b_loop_cond =
1649 gcc_jit_function_new_block (func, "loop_cond");
1650 gcc_jit_block *b_loop_body =
1651 gcc_jit_function_new_block (func, "loop_body");
1652 gcc_jit_block *b_after_loop =
1653 gcc_jit_function_new_block (func, "after_loop");
1656 gcc_jit_block_add_assignment (
1659 gcc_jit_context_zero (ctxt, the_type));
1662 gcc_jit_block_add_assignment (
1665 gcc_jit_context_zero (ctxt, the_type));
1667 gcc_jit_block_end_with_jump (b_initial, NULL, b_loop_cond);
1670 gcc_jit_block_end_with_conditional (
1672 gcc_jit_context_new_comparison (
1674 GCC_JIT_COMPARISON_GE,
1675 gcc_jit_lvalue_as_rvalue (i),
1676 gcc_jit_param_as_rvalue (n)),
1681 gcc_jit_block_add_assignment_op (
1684 GCC_JIT_BINARY_OP_PLUS,
1685 gcc_jit_context_new_binary_op (
1687 GCC_JIT_BINARY_OP_MULT, the_type,
1688 gcc_jit_lvalue_as_rvalue (i),
1689 gcc_jit_lvalue_as_rvalue (i)));
1692 gcc_jit_block_add_assignment_op (
1695 GCC_JIT_BINARY_OP_PLUS,
1696 gcc_jit_context_one (ctxt, the_type));
1698 gcc_jit_block_end_with_jump (b_loop_body, NULL, b_loop_cond);
1701 gcc_jit_block_end_with_return (
1704 gcc_jit_lvalue_as_rvalue (sum));
1708 main (int argc, char **argv)
1710 gcc_jit_context *ctxt = NULL;
1711 gcc_jit_result *result = NULL;
1713 /* Get a "context" object for working with the library. */
1714 ctxt = gcc_jit_context_acquire ();
1717 fprintf (stderr, "NULL ctxt");
1721 /* Set some options on the context.
1722 Let's see the code being generated, in assembler form. */
1723 gcc_jit_context_set_bool_option (
1725 GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
1728 /* Populate the context. */
1731 /* Compile the code. */
1732 result = gcc_jit_context_compile (ctxt);
1735 fprintf (stderr, "NULL result");
1739 /* Extract the generated code from "result". */
1740 typedef int (*loop_test_fn_type) (int);
1741 loop_test_fn_type loop_test =
1742 (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
1745 fprintf (stderr, "NULL loop_test");
1749 /* Run the generated code. */
1750 int val = loop_test (10);
1751 printf("loop_test returned: %d\n", val);
1754 gcc_jit_context_release (ctxt);
1755 gcc_jit_result_release (result);
1764 Building and running it:
1768 tut03-sum-of-squares.c \
1769 -o tut03-sum-of-squares \
1772 # Run the built program:
1773 $ ./tut03-sum-of-squares
1774 loop_test returned: 285
1779 @c Copyright (C) 2014 Free Software Foundation, Inc.
1780 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
1782 @c This is free software: you can redistribute it and/or modify it
1783 @c under the terms of the GNU General Public License as published by
1784 @c the Free Software Foundation, either version 3 of the License, or
1785 @c (at your option) any later version.
1787 @c This program is distributed in the hope that it will be useful, but
1788 @c WITHOUT ANY WARRANTY; without even the implied warranty of
1789 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
1790 @c General Public License for more details.
1792 @c You should have received a copy of the GNU General Public License
1793 @c along with this program. If not, see
1794 @c <http://www.gnu.org/licenses/>.
1796 @node Tutorial part 4 Adding JIT-compilation to a toy interpreter,,Tutorial part 3 Loops and variables,Tutorial
1797 @anchor{intro/tutorial04 tutorial-part-4-adding-jit-compilation-to-a-toy-interpreter}@anchor{35}@anchor{intro/tutorial04 doc}@anchor{36}
1798 @section Tutorial part 4: Adding JIT-compilation to a toy interpreter
1801 In this example we construct a "toy" interpreter, and add JIT-compilation
1805 * Our toy interpreter::
1806 * Compiling to machine code::
1807 * Setting things up::
1808 * Populating the function::
1809 * Verifying the control flow graph::
1810 * Compiling the context::
1811 * Single-stepping through the generated code::
1812 * Examining the generated code::
1813 * Putting it all together::
1814 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?.
1818 @node Our toy interpreter,Compiling to machine code,,Tutorial part 4 Adding JIT-compilation to a toy interpreter
1819 @anchor{intro/tutorial04 our-toy-interpreter}@anchor{37}
1820 @subsection Our toy interpreter
1823 It's a stack-based interpreter, and is intended as a (very simple) example
1824 of the kind of bytecode interpreter seen in dynamic languages such as
1827 For the sake of simplicity, our toy virtual machine is very limited:
1835 The only data type is @cite{int}
1838 It can only work on one function at a time (so that the only
1839 function call that can be made is to recurse).
1842 Functions can only take one parameter.
1845 Functions have a stack of @cite{int} values.
1848 We'll implement function call within the interpreter by calling a
1849 function in our implementation, rather than implementing our own
1853 The parser is only good enough to get the examples to work.
1857 Naturally, a real interpreter would be much more complicated that this.
1859 The following operations are supported:
1862 @multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxx}
1885 Duplicate top of stack.
1901 Swap top two elements
1918 Add the top two elements
1935 Likewise, but subtract.
1951 Likewise, but multiply.
1968 elements on the stack
1969 and push a nonzero/zero
1986 Recurse, passing the top
2004 Return the top of the
2017 PUSH_CONST @cite{arg}
2033 JUMP_ABS_IF_TRUE @cite{arg}
2037 Pop; if top of stack was
2052 Programs can be interpreted, disassembled, and compiled to machine code.
2054 The interpreter reads @code{.toy} scripts. Here's what a simple recursive
2055 factorial program looks like, the script @code{factorial.toy}.
2056 The parser ignores lines beginning with a @cite{#}.
2061 # Simple recursive factorial implementation, roughly equivalent to:
2063 # int factorial (int arg)
2067 # return arg * factorial (arg - 1)
2079 # stack: [arg, arg, 2]
2083 # stack: [arg, (arg < 2)]
2095 # stack: [arg, arg, 1]
2099 # stack: [arg, (arg - 1)
2103 # stack: [arg, factorial(arg - 1)]
2107 # stack: [arg * factorial(arg - 1)]
2117 The interpreter is a simple infinite loop with a big @code{switch} statement
2118 based on what the next opcode is:
2125 toyvm_function_interpret (toyvm_function *fn, int arg, FILE *trace)
2128 #define PUSH(ARG) (toyvm_frame_push (&frame, (ARG)))
2129 #define POP(ARG) (toyvm_frame_pop (&frame))
2131 frame.frm_function = fn;
2133 frame.frm_cur_depth = 0;
2141 assert (frame.frm_pc < fn->fn_num_ops);
2142 op = &fn->fn_ops[frame.frm_pc++];
2146 toyvm_frame_dump_stack (&frame, trace);
2147 toyvm_function_disassemble_op (fn, op, frame.frm_pc, trace);
2150 switch (op->op_opcode)
2152 /* Ops taking no operand. */
2172 case BINARY_SUBTRACT:
2184 case BINARY_COMPARE_LT:
2192 x = toyvm_function_interpret (fn, x, trace);
2199 /* Ops taking an operand. */
2201 PUSH (op->op_operand);
2204 case JUMP_ABS_IF_TRUE:
2207 frame.frm_pc = op->op_operand;
2211 assert (0); /* unknown opcode */
2213 @} /* end of switch on opcode */
2214 @} /* end of while loop */
2226 @node Compiling to machine code,Setting things up,Our toy interpreter,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2227 @anchor{intro/tutorial04 compiling-to-machine-code}@anchor{38}
2228 @subsection Compiling to machine code
2231 We want to generate machine code that can be cast to this type and
2232 then directly executed in-process:
2237 typedef int (*toyvm_compiled_code) (int);
2245 The lifetime of the code is tied to that of a @pxref{16,,gcc_jit_result *}.
2246 We'll handle this by bundling them up in a structure, so that we can
2247 clean them up together by calling @pxref{39,,gcc_jit_result_release()}:
2253 struct toyvm_compiled_function
2255 gcc_jit_result *cf_jit_result;
2256 toyvm_compiled_code cf_code;
2265 Our compiler isn't very sophisticated; it takes the implementation of
2266 each opcode above, and maps it directly to the operations supported by
2269 How should we handle the stack? In theory we could calculate what the
2270 stack depth will be at each opcode, and optimize away the stack
2271 manipulation "by hand". We'll see below that libgccjit is able to do
2272 this for us, so we'll implement stack manipulation
2273 in a direct way, by creating a @code{stack} array and @code{stack_depth}
2274 variables, local within the generated function, equivalent to this C code:
2278 int stack[MAX_STACK_DEPTH];
2283 We'll also have local variables @code{x} and @code{y} for use when implementing
2284 the opcodes, equivalent to this:
2293 This means our compiler has the following state:
2299 struct compilation_state
2301 gcc_jit_context *ctxt;
2303 gcc_jit_type *int_type;
2304 gcc_jit_type *bool_type;
2305 gcc_jit_type *stack_type; /* int[MAX_STACK_DEPTH] */
2307 gcc_jit_rvalue *const_one;
2309 gcc_jit_function *fn;
2310 gcc_jit_param *param_arg;
2311 gcc_jit_lvalue *stack;
2312 gcc_jit_lvalue *stack_depth;
2316 gcc_jit_location *op_locs[MAX_OPS];
2317 gcc_jit_block *initial_block;
2318 gcc_jit_block *op_blocks[MAX_OPS];
2328 @node Setting things up,Populating the function,Compiling to machine code,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2329 @anchor{intro/tutorial04 setting-things-up}@anchor{3a}
2330 @subsection Setting things up
2333 First we create our types:
2339 gcc_jit_context_get_type (state.ctxt, GCC_JIT_TYPE_INT);
2341 gcc_jit_context_get_type (state.ctxt, GCC_JIT_TYPE_BOOL);
2343 gcc_jit_context_new_array_type (state.ctxt, NULL,
2344 state.int_type, MAX_STACK_DEPTH);
2352 along with extracting a useful @cite{int} constant:
2357 state.const_one = gcc_jit_context_one (state.ctxt, state.int_type);
2365 We'll implement push and pop in terms of the @code{stack} array and
2366 @code{stack_depth}. Here are helper functions for adding statements to
2367 a block, implementing pushing and popping values:
2374 add_push (compilation_state *state,
2375 gcc_jit_block *block,
2376 gcc_jit_rvalue *rvalue,
2377 gcc_jit_location *loc)
2379 /* stack[stack_depth] = RVALUE */
2380 gcc_jit_block_add_assignment (
2383 /* stack[stack_depth] */
2384 gcc_jit_context_new_array_access (
2387 gcc_jit_lvalue_as_rvalue (state->stack),
2388 gcc_jit_lvalue_as_rvalue (state->stack_depth)),
2391 /* "stack_depth++;". */
2392 gcc_jit_block_add_assignment_op (
2396 GCC_JIT_BINARY_OP_PLUS,
2401 add_pop (compilation_state *state,
2402 gcc_jit_block *block,
2403 gcc_jit_lvalue *lvalue,
2404 gcc_jit_location *loc)
2406 /* "--stack_depth;". */
2407 gcc_jit_block_add_assignment_op (
2411 GCC_JIT_BINARY_OP_MINUS,
2414 /* "LVALUE = stack[stack_depth];". */
2415 gcc_jit_block_add_assignment (
2419 /* stack[stack_depth] */
2420 gcc_jit_lvalue_as_rvalue (
2421 gcc_jit_context_new_array_access (
2424 gcc_jit_lvalue_as_rvalue (state->stack),
2425 gcc_jit_lvalue_as_rvalue (state->stack_depth))));
2434 We will support single-stepping through the generated code in the
2435 debugger, so we need to create @pxref{3b,,gcc_jit_location} instances, one
2436 per operation in the source code. These will reference the lines of
2437 e.g. @code{factorial.toy}.
2442 for (pc = 0; pc < fn->fn_num_ops; pc++)
2444 toyvm_op *op = &fn->fn_ops[pc];
2446 state.op_locs[pc] = gcc_jit_context_new_location (state.ctxt,
2458 Let's create the function itself. As usual, we create its parameter
2459 first, then use the parameter to create the function:
2465 gcc_jit_context_new_param (state.ctxt, state.op_locs[0],
2466 state.int_type, "arg");
2468 gcc_jit_context_new_function (state.ctxt,
2470 GCC_JIT_FUNCTION_EXPORTED,
2473 1, &state.param_arg, 0);
2481 We create the locals within the function.
2487 gcc_jit_function_new_local (state.fn, NULL,
2488 state.stack_type, "stack");
2490 gcc_jit_function_new_local (state.fn, NULL,
2491 state.int_type, "stack_depth");
2493 gcc_jit_function_new_local (state.fn, NULL,
2494 state.int_type, "x");
2496 gcc_jit_function_new_local (state.fn, NULL,
2497 state.int_type, "y");
2505 @node Populating the function,Verifying the control flow graph,Setting things up,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2506 @anchor{intro/tutorial04 populating-the-function}@anchor{3c}
2507 @subsection Populating the function
2510 There's some one-time initialization, and the API treats the first block
2511 you create as the entrypoint of the function, so we need to create that
2517 state.initial_block = gcc_jit_function_new_block (state.fn, "initial");
2525 We can now create blocks for each of the operations. Most of these will
2526 be consolidated into larger blocks when the optimizer runs.
2531 for (pc = 0; pc < fn->fn_num_ops; pc++)
2534 sprintf (buf, "instr%i", pc);
2535 state.op_blocks[pc] = gcc_jit_function_new_block (state.fn, buf);
2544 Now that we have a block it can jump to when it's done, we can populate
2551 /* "stack_depth = 0;". */
2552 gcc_jit_block_add_assignment (
2553 state.initial_block,
2556 gcc_jit_context_zero (state.ctxt, state.int_type));
2558 /* "PUSH (arg);". */
2560 state.initial_block,
2561 gcc_jit_param_as_rvalue (state.param_arg),
2564 /* ...and jump to insn 0. */
2565 gcc_jit_block_end_with_jump (state.initial_block,
2567 state.op_blocks[0]);
2575 We can now populate the blocks for the individual operations. We loop
2576 through them, adding instructions to their blocks:
2581 for (pc = 0; pc < fn->fn_num_ops; pc++)
2583 gcc_jit_location *loc = state.op_locs[pc];
2585 gcc_jit_block *block = state.op_blocks[pc];
2586 gcc_jit_block *next_block = (pc < fn->fn_num_ops
2587 ? state.op_blocks[pc + 1]
2591 op = &fn->fn_ops[pc];
2599 We're going to have another big @code{switch} statement for implementing
2600 the opcodes, this time for compiling them, rather than interpreting
2601 them. It's helpful to have macros for implementing push and pop, so that
2602 we can make the @code{switch} statement that's coming up look as much as
2603 possible like the one above within the interpreter:
2607 #define X_EQUALS_POP()\
2608 add_pop (&state, block, state.x, loc)
2609 #define Y_EQUALS_POP()\
2610 add_pop (&state, block, state.y, loc)
2611 #define PUSH_RVALUE(RVALUE)\
2612 add_push (&state, block, (RVALUE), loc)
2614 PUSH_RVALUE (gcc_jit_lvalue_as_rvalue (state.x))
2616 PUSH_RVALUE (gcc_jit_lvalue_as_rvalue (state.y))
2625 A particularly clever implementation would have an @emph{identical}
2626 @code{switch} statement shared by the interpreter and the compiler, with
2627 some preprocessor "magic". We're not doing that here, for the sake
2632 When I first implemented this compiler, I accidentally missed an edit
2633 when copying and pasting the @code{Y_EQUALS_POP} macro, so that popping the
2634 stack into @code{y} instead erroneously assigned it to @code{x}, leaving @code{y}
2637 To track this kind of thing down, we can use
2638 @pxref{3d,,gcc_jit_block_add_comment()} to add descriptive comments
2639 to the internal representation. This is invaluable when looking through
2640 the generated IR for, say @code{factorial}:
2646 gcc_jit_block_add_comment (block, loc, opcode_names[op->op_opcode]);
2654 We can now write the big @code{switch} statement that implements the
2655 individual opcodes, populating the relevant block with statements:
2661 switch (op->op_opcode)
2680 gcc_jit_context_new_binary_op (
2683 GCC_JIT_BINARY_OP_PLUS,
2685 gcc_jit_lvalue_as_rvalue (state.x),
2686 gcc_jit_lvalue_as_rvalue (state.y)));
2689 case BINARY_SUBTRACT:
2693 gcc_jit_context_new_binary_op (
2696 GCC_JIT_BINARY_OP_MINUS,
2698 gcc_jit_lvalue_as_rvalue (state.x),
2699 gcc_jit_lvalue_as_rvalue (state.y)));
2706 gcc_jit_context_new_binary_op (
2709 GCC_JIT_BINARY_OP_MULT,
2711 gcc_jit_lvalue_as_rvalue (state.x),
2712 gcc_jit_lvalue_as_rvalue (state.y)));
2715 case BINARY_COMPARE_LT:
2719 /* cast of bool to int */
2720 gcc_jit_context_new_cast (
2723 /* (x < y) as a bool */
2724 gcc_jit_context_new_comparison (
2727 GCC_JIT_COMPARISON_LT,
2728 gcc_jit_lvalue_as_rvalue (state.x),
2729 gcc_jit_lvalue_as_rvalue (state.y)),
2736 gcc_jit_rvalue *arg = gcc_jit_lvalue_as_rvalue (state.x);
2738 gcc_jit_context_new_call (
2748 gcc_jit_block_end_with_return (
2751 gcc_jit_lvalue_as_rvalue (state.x));
2754 /* Ops taking an operand. */
2757 gcc_jit_context_new_rvalue_from_int (
2763 case JUMP_ABS_IF_TRUE:
2765 gcc_jit_block_end_with_conditional (
2769 gcc_jit_context_new_cast (
2772 gcc_jit_lvalue_as_rvalue (state.x),
2774 state.op_blocks[op->op_operand], /* on_true */
2775 next_block); /* on_false */
2780 @} /* end of switch on opcode */
2788 Every block must be terminated, via a call to one of the
2789 @code{gcc_jit_block_end_with_} entrypoints. This has been done for two
2790 of the opcodes, but we need to do it for the other ones, by jumping
2796 if (op->op_opcode != JUMP_ABS_IF_TRUE
2797 && op->op_opcode != RETURN)
2798 gcc_jit_block_end_with_jump (
2809 This is analogous to simply incrementing the program counter.
2811 @node Verifying the control flow graph,Compiling the context,Populating the function,Tutorial part 4 Adding JIT-compilation to a toy interpreter
2812 @anchor{intro/tutorial04 verifying-the-control-flow-graph}@anchor{3e}
2813 @subsection Verifying the control flow graph
2816 Having finished looping over the blocks, the context is complete.
2818 As before, we can verify that the control flow and statements are sane by
2819 using @pxref{33,,gcc_jit_function_dump_to_dot()}:
2822 gcc_jit_function_dump_to_dot (state.fn, "/tmp/factorial.dot");
2827 and viewing the result. Note how the label names, comments, and
2828 variable names show up in the dump, to make it easier to spot
2829 errors in our compiler.
2836 @image{factorial,,,image of a control flow graph,png}
2842 @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
2843 @anchor{intro/tutorial04 compiling-the-context}@anchor{3f}
2844 @subsection Compiling the context
2847 Having finished looping over the blocks and populating them with
2848 statements, the context is complete.
2850 We can now compile it, and extract machine code from the result:
2855 gcc_jit_result *jit_result = gcc_jit_context_compile (state.ctxt);
2856 gcc_jit_context_release (state.ctxt);
2858 toyvm_compiled_function *toyvm_result =
2859 (toyvm_compiled_function *)calloc (1, sizeof (toyvm_compiled_function));
2862 fprintf (stderr, "out of memory allocating toyvm_compiled_function\n");
2863 gcc_jit_result_release (jit_result);
2867 toyvm_result->cf_jit_result = jit_result;
2868 toyvm_result->cf_code =
2869 (toyvm_compiled_code)gcc_jit_result_get_code (jit_result,
2874 return toyvm_result;
2879 #define CHECK_NON_NULL(PTR) \
2881 if ((PTR) != NULL) \
2883 pass ("%s: %s is non-null", test, #PTR); \
2887 fail ("%s: %s is NULL", test, #PTR); \
2892 #define CHECK_VALUE(ACTUAL, EXPECTED) \
2894 if ((ACTUAL) == (EXPECTED)) \
2896 pass ("%s: actual: %s == expected: %s", test, #ACTUAL, #EXPECTED); \
2900 fail ("%s: actual: %s != expected: %s", test, #ACTUAL, #EXPECTED); \
2901 fprintf (stderr, "incorrect value\n"); \
2907 test_script (const char *scripts_dir, const char *script_name, int input,
2908 int expected_result)
2912 int interpreted_result;
2913 toyvm_compiled_function *compiled_fn;
2914 toyvm_compiled_code code;
2915 int compiled_result;
2917 snprintf (test, sizeof (test), "toyvm.c: %s", script_name);
2919 script_path = (char *)malloc (strlen (scripts_dir)
2920 + strlen (script_name) + 1);
2921 CHECK_NON_NULL (script_path);
2922 sprintf (script_path, "%s%s", scripts_dir, script_name);
2924 fn = toyvm_function_parse (script_path, script_name);
2925 CHECK_NON_NULL (fn);
2927 interpreted_result = toyvm_function_interpret (fn, input, NULL);
2928 CHECK_VALUE (interpreted_result, expected_result);
2930 compiled_fn = toyvm_function_compile (fn);
2931 CHECK_NON_NULL (compiled_fn);
2933 code = (toyvm_compiled_code)compiled_fn->cf_code;
2934 CHECK_NON_NULL (code);
2936 compiled_result = code (input);
2937 CHECK_VALUE (compiled_result, expected_result);
2939 gcc_jit_result_release (compiled_fn->cf_jit_result);
2945 #define PATH_TO_SCRIPTS ("/jit/docs/examples/tut04-toyvm/")
2953 snprintf (test, sizeof (test), "toyvm.c");
2955 /* We need to locate the test scripts.
2956 Rely on "srcdir" being set in the environment. */
2958 srcdir = getenv ("srcdir");
2959 CHECK_NON_NULL (srcdir);
2961 scripts_dir = (char *)malloc (strlen (srcdir) + strlen(PATH_TO_SCRIPTS)
2963 CHECK_NON_NULL (scripts_dir);
2964 sprintf (scripts_dir, "%s%s", srcdir, PATH_TO_SCRIPTS);
2966 test_script (scripts_dir, "factorial.toy", 10, 3628800);
2967 test_script (scripts_dir, "fibonacci.toy", 10, 55);
2973 main (int argc, char **argv)
2975 const char *filename = NULL;
2976 toyvm_function *fn = NULL;
2978 /* If called with no args, assume we're being run by the test suite. */
2988 "%s FILENAME INPUT: Parse and run a .toy file\n",
2994 fn = toyvm_function_parse (filename, filename);
2999 toyvm_function_disassemble (fn, stdout);
3001 printf ("interpreter result: %d\n",
3002 toyvm_function_interpret (fn, atoi (argv[2]), NULL));
3004 /* JIT-compilation. */
3005 toyvm_compiled_function *compiled_fn
3006 = toyvm_function_compile (fn);
3008 toyvm_compiled_code code = compiled_fn->cf_code;
3009 printf ("compiler result: %d\n",
3010 code (atoi (argv[2])));
3012 gcc_jit_result_release (compiled_fn->cf_jit_result);
3023 We can now run the result:
3028 toyvm_compiled_function *compiled_fn
3029 = toyvm_function_compile (fn);
3031 toyvm_compiled_code code = compiled_fn->cf_code;
3032 printf ("compiler result: %d\n",
3033 code (atoi (argv[2])));
3035 gcc_jit_result_release (compiled_fn->cf_jit_result);
3044 @node Single-stepping through the generated code,Examining the generated code,Compiling the context,Tutorial part 4 Adding JIT-compilation to a toy interpreter
3045 @anchor{intro/tutorial04 single-stepping-through-the-generated-code}@anchor{40}
3046 @subsection Single-stepping through the generated code
3049 It's possible to debug the generated code. To do this we need to both:
3057 Set up source code locations for our statements, so that we can
3058 meaningfully step through the code. We did this above by
3059 calling @pxref{41,,gcc_jit_context_new_location()} and using the
3063 Enable the generation of debugging information, by setting
3064 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} on the
3065 @pxref{8,,gcc_jit_context} via
3066 @pxref{1b,,gcc_jit_context_set_bool_option()}:
3069 gcc_jit_context_set_bool_option (
3071 GCC_JIT_BOOL_OPTION_DEBUGINFO,
3079 Having done this, we can put a breakpoint on the generated function:
3082 $ gdb --args ./toyvm factorial.toy 10
3083 (gdb) break factorial
3084 Function "factorial" not defined.
3085 Make breakpoint pending on future shared library load? (y or [n]) y
3086 Breakpoint 1 (factorial) pending.
3088 Breakpoint 1, factorial (arg=10) at factorial.toy:14
3094 We've set up location information, which references @code{factorial.toy}.
3095 This allows us to use e.g. @code{list} to see where we are in the script:
3105 15 # stack: [arg, arg]
3113 and to step through the function, examining the data:
3119 22 BINARY_COMPARE_LT
3121 $5 = @{10, 10, 2, 0, -7152, 32767, 0, 0@}
3122 (gdb) print stack_depth
3128 You'll see that the parts of the @code{stack} array that haven't been
3129 touched yet are uninitialized.
3133 Turning on optimizations may lead to unpredictable results when
3134 stepping through the generated code: the execution may appear to
3135 "jump around" the source code. This is analogous to turning up the
3136 optimization level in a regular compiler.
3140 @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
3141 @anchor{intro/tutorial04 examining-the-generated-code}@anchor{43}
3142 @subsection Examining the generated code
3145 How good is the optimized code?
3147 We can turn up optimizations, by calling
3148 @pxref{1e,,gcc_jit_context_set_int_option()} with
3149 @pxref{1f,,GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}:
3152 gcc_jit_context_set_int_option (
3154 GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL,
3160 One of GCC's internal representations is called "gimple". A dump of the
3161 initial gimple representation of the code can be seen by setting:
3164 gcc_jit_context_set_bool_option (ctxt,
3165 GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE,
3171 With optimization on and source locations displayed, this gives:
3173 @c We'll use "c" for gimple dumps
3176 factorial (signed int arg)
3178 <unnamed type> D.80;
3186 signed int stack_depth;
3187 signed int stack[8];
3193 stack[stack_depth] = arg;
3194 stack_depth = stack_depth + 1;
3198 stack_depth = stack_depth + -1;
3199 x = stack[stack_depth];
3200 stack[stack_depth] = x;
3201 stack_depth = stack_depth + 1;
3202 stack[stack_depth] = x;
3203 stack_depth = stack_depth + 1;
3207 stack[stack_depth] = 2;
3208 stack_depth = stack_depth + 1;
3216 You can see the generated machine code in assembly form via:
3219 gcc_jit_context_set_bool_option (
3221 GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
3223 result = gcc_jit_context_compile (ctxt);
3228 which shows that (on this x86_64 box) the compiler has unrolled the loop
3229 and is using MMX instructions to perform several multiplications
3238 .type factorial, @@function
3241 .file 1 "factorial.toy"
3252 leal 0(,%rcx,4), %esi
3258 movl %eax, -16(%rsp)
3260 movd -16(%rsp), %xmm0
3261 movl %edi, -16(%rsp)
3262 movl %eax, -12(%rsp)
3263 movd -16(%rsp), %xmm1
3265 movl %edx, -16(%rsp)
3266 movd -12(%rsp), %xmm4
3267 movd -16(%rsp), %xmm6
3268 punpckldq %xmm4, %xmm0
3269 movdqa .LC1(%rip), %xmm4
3270 punpckldq %xmm6, %xmm1
3271 punpcklqdq %xmm0, %xmm1
3272 movdqa .LC0(%rip), %xmm0
3274 # etc - edited for brevity
3279 This is clearly overkill for a function that will likely overflow the
3280 @code{int} type before the vectorization is worthwhile - but then again, this
3283 Turning down the optimization level to 2:
3286 gcc_jit_context_set_int_option (
3288 GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL,
3294 yields this code, which is simple enough to quote in its entirety:
3301 .type factorial, @@function
3330 .size factorial, .-factorial
3331 .ident "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-%@{gcc_release@})"
3332 .section .note.GNU-stack,"",@@progbits
3337 Note that the stack pushing and popping have been eliminated, as has the
3338 recursive call (in favor of an iteration).
3340 @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
3341 @anchor{intro/tutorial04 putting-it-all-together}@anchor{44}
3342 @subsection Putting it all together
3345 The complete example can be seen in the source tree at
3346 @code{gcc/jit/docs/examples/tut04-toyvm/toyvm.c}
3348 along with a Makefile and a couple of sample .toy scripts:
3352 drwxrwxr-x. 2 david david 4096 Sep 19 17:46 .
3353 drwxrwxr-x. 3 david david 4096 Sep 19 15:26 ..
3354 -rw-rw-r--. 1 david david 615 Sep 19 12:43 factorial.toy
3355 -rw-rw-r--. 1 david david 834 Sep 19 13:08 fibonacci.toy
3356 -rw-rw-r--. 1 david david 238 Sep 19 14:22 Makefile
3357 -rw-rw-r--. 1 david david 16457 Sep 19 17:07 toyvm.c
3360 g++ -Wall -g -o toyvm toyvm.c -lgccjit
3362 $ ./toyvm factorial.toy 10
3363 interpreter result: 3628800
3364 compiler result: 3628800
3366 $ ./toyvm fibonacci.toy 10
3367 interpreter result: 55
3373 @node Behind the curtain How does our code get optimized?,,Putting it all together,Tutorial part 4 Adding JIT-compilation to a toy interpreter
3374 @anchor{intro/tutorial04 behind-the-curtain-how-does-our-code-get-optimized}@anchor{45}
3375 @subsection Behind the curtain: How does our code get optimized?
3378 Our example is done, but you may be wondering about exactly how the
3379 compiler turned what we gave it into the machine code seen above.
3381 We can examine what the compiler is doing in detail by setting:
3384 gcc_jit_context_set_bool_option (state.ctxt,
3385 GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING,
3387 gcc_jit_context_set_bool_option (state.ctxt,
3388 GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES,
3394 This will dump detailed information about the compiler's state to a
3395 directory under @code{/tmp}, and keep it from being cleaned up.
3397 The precise names and their formats of these files is subject to change.
3398 Higher optimization levels lead to more files.
3399 Here's what I saw (edited for brevity; there were almost 200 files):
3402 intermediate files written to /tmp/libgccjit-KPQbGw
3403 $ ls /tmp/libgccjit-KPQbGw/
3405 fake.c.000i.type-inheritance
3407 fake.c.007t.omplower
3411 fake.c.014i.visibility
3412 fake.c.015i.early_local_cleanups
3419 The gimple code is converted into Static Single Assignment form,
3420 with annotations for use when generating the debuginfo:
3423 $ less /tmp/libgccjit-KPQbGw/fake.c.016t.ssa
3429 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3431 factorial (signed int arg)
3433 signed int stack[8];
3434 signed int stack_depth;
3446 # DEBUG stack_depth => stack_depth_3
3447 stack[stack_depth_3] = arg_5(D);
3448 stack_depth_7 = stack_depth_3 + 1;
3449 # DEBUG stack_depth => stack_depth_7
3450 # DEBUG instr0 => NULL
3451 # DEBUG /* DUP */ => NULL
3452 stack_depth_8 = stack_depth_7 + -1;
3453 # DEBUG stack_depth => stack_depth_8
3454 x_9 = stack[stack_depth_8];
3456 stack[stack_depth_8] = x_9;
3457 stack_depth_11 = stack_depth_8 + 1;
3458 # DEBUG stack_depth => stack_depth_11
3459 stack[stack_depth_11] = x_9;
3460 stack_depth_13 = stack_depth_11 + 1;
3461 # DEBUG stack_depth => stack_depth_13
3462 # DEBUG instr1 => NULL
3463 # DEBUG /* PUSH_CONST */ => NULL
3464 stack[stack_depth_13] = 2;
3466 /* etc; edited for brevity */
3471 We can perhaps better see the code by turning off
3472 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} to suppress all those @code{DEBUG}
3476 $ less /tmp/libgccjit-1Hywc0/fake.c.016t.ssa
3482 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3484 factorial (signed int arg)
3486 signed int stack[8];
3487 signed int stack_depth;
3499 stack[stack_depth_3] = arg_5(D);
3500 stack_depth_7 = stack_depth_3 + 1;
3501 stack_depth_8 = stack_depth_7 + -1;
3502 x_9 = stack[stack_depth_8];
3503 stack[stack_depth_8] = x_9;
3504 stack_depth_11 = stack_depth_8 + 1;
3505 stack[stack_depth_11] = x_9;
3506 stack_depth_13 = stack_depth_11 + 1;
3507 stack[stack_depth_13] = 2;
3508 stack_depth_15 = stack_depth_13 + 1;
3509 stack_depth_16 = stack_depth_15 + -1;
3510 y_17 = stack[stack_depth_16];
3511 stack_depth_18 = stack_depth_16 + -1;
3512 x_19 = stack[stack_depth_18];
3514 _21 = (signed int) _20;
3515 stack[stack_depth_18] = _21;
3516 stack_depth_23 = stack_depth_18 + 1;
3517 stack_depth_24 = stack_depth_23 + -1;
3518 x_25 = stack[stack_depth_24];
3520 goto <bb 4> (instr9);
3522 goto <bb 3> (instr4);
3526 stack_depth_26 = stack_depth_24 + -1;
3527 x_27 = stack[stack_depth_26];
3528 stack[stack_depth_26] = x_27;
3529 stack_depth_29 = stack_depth_26 + 1;
3530 stack[stack_depth_29] = x_27;
3531 stack_depth_31 = stack_depth_29 + 1;
3532 stack[stack_depth_31] = 1;
3533 stack_depth_33 = stack_depth_31 + 1;
3534 stack_depth_34 = stack_depth_33 + -1;
3535 y_35 = stack[stack_depth_34];
3536 stack_depth_36 = stack_depth_34 + -1;
3537 x_37 = stack[stack_depth_36];
3539 stack[stack_depth_36] = _38;
3540 stack_depth_40 = stack_depth_36 + 1;
3541 stack_depth_41 = stack_depth_40 + -1;
3542 x_42 = stack[stack_depth_41];
3543 _44 = factorial (x_42);
3544 stack[stack_depth_41] = _44;
3545 stack_depth_46 = stack_depth_41 + 1;
3546 stack_depth_47 = stack_depth_46 + -1;
3547 y_48 = stack[stack_depth_47];
3548 stack_depth_49 = stack_depth_47 + -1;
3549 x_50 = stack[stack_depth_49];
3551 stack[stack_depth_49] = _51;
3552 stack_depth_53 = stack_depth_49 + 1;
3554 # stack_depth_1 = PHI <stack_depth_24(2), stack_depth_53(3)>
3557 stack_depth_54 = stack_depth_1 + -1;
3558 x_55 = stack[stack_depth_54];
3560 stack =@{v@} @{CLOBBER@};
3568 Note in the above how all the @pxref{28,,gcc_jit_block} instances we
3569 created have been consolidated into just 3 blocks in GCC's internal
3570 representation: @code{initial}, @code{instr4} and @code{instr9}.
3573 * Optimizing away stack manipulation::
3574 * Elimination of tail recursion::
3578 @node Optimizing away stack manipulation,Elimination of tail recursion,,Behind the curtain How does our code get optimized?
3579 @anchor{intro/tutorial04 optimizing-away-stack-manipulation}@anchor{46}
3580 @subsubsection Optimizing away stack manipulation
3583 Recall our simple implementation of stack operations. Let's examine
3584 how the stack operations are optimized away.
3586 After a pass of constant-propagation, the depth of the stack at each
3587 opcode can be determined at compile-time:
3590 $ less /tmp/libgccjit-1Hywc0/fake.c.021t.ccp1
3596 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3598 factorial (signed int arg)
3600 signed int stack[8];
3601 signed int stack_depth;
3611 stack[0] = arg_5(D);
3619 _21 = (signed int) _20;
3623 goto <bb 4> (instr9);
3625 goto <bb 3> (instr4);
3638 _44 = factorial (x_42);
3649 stack =@{v@} @{CLOBBER@};
3657 Note how, in the above, all those @code{stack_depth} values are now just
3658 constants: we're accessing specific stack locations at each opcode.
3660 The "esra" pass ("Early Scalar Replacement of Aggregates") breaks
3661 out our "stack" array into individual elements:
3664 $ less /tmp/libgccjit-1Hywc0/fake.c.024t.esra
3670 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3672 Created a replacement for stack offset: 0, size: 32: stack$0
3673 Created a replacement for stack offset: 32, size: 32: stack$1
3674 Created a replacement for stack offset: 64, size: 32: stack$2
3676 Symbols to be put in SSA form
3677 @{ D.89 D.90 D.91 @}
3678 Incremental SSA update started at block: 0
3679 Number of blocks in CFG: 5
3680 Number of blocks to update: 4 ( 80%)
3683 factorial (signed int arg)
3688 signed int stack[8];
3689 signed int stack_depth;
3699 stack$0_45 = arg_5(D);
3707 _21 = (signed int) _20;
3711 goto <bb 4> (instr9);
3713 goto <bb 3> (instr4);
3726 _44 = factorial (x_42);
3733 # stack$0_52 = PHI <stack$0_39(2), stack$0_1(3)>
3738 stack =@{v@} @{CLOBBER@};
3746 Hence at this point, all those pushes and pops of the stack are now
3747 simply assignments to specific temporary variables.
3749 After some copy propagation, the stack manipulation has been completely
3753 $ less /tmp/libgccjit-1Hywc0/fake.c.026t.copyprop1
3759 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3761 factorial (signed int arg)
3766 signed int stack[8];
3767 signed int stack_depth;
3777 stack$0_39 = arg_5(D);
3778 _20 = arg_5(D) <= 1;
3779 _21 = (signed int) _20;
3781 goto <bb 4> (instr9);
3783 goto <bb 3> (instr4);
3787 _38 = arg_5(D) + -1;
3788 _44 = factorial (_38);
3789 _51 = arg_5(D) * _44;
3792 # stack$0_52 = PHI <arg_5(D)(2), _51(3)>
3795 stack =@{v@} @{CLOBBER@};
3803 Later on, another pass finally eliminated @code{stack_depth} local and the
3804 unused parts of the @cite{stack`} array altogether:
3807 $ less /tmp/libgccjit-1Hywc0/fake.c.036t.release_ssa
3813 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3815 Released 44 names, 314.29%, removed 44 holes
3816 factorial (signed int arg)
3819 signed int mult_acc_1;
3823 signed int mul_tmp_10;
3824 signed int mult_acc_11;
3825 signed int mult_acc_13;
3827 # arg_9 = PHI <arg_8(D)(0)>
3828 # mult_acc_13 = PHI <1(0)>
3832 # arg_4 = PHI <arg_9(2), _7(3)>
3833 # mult_acc_1 = PHI <mult_acc_13(2), mult_acc_11(3)>
3835 _6 = (signed int) _5;
3837 goto <bb 4> (instr9);
3839 goto <bb 3> (instr4);
3844 mult_acc_11 = mult_acc_1 * arg_4;
3847 # stack$0_12 = PHI <arg_4(5)>
3850 mul_tmp_10 = mult_acc_1 * stack$0_12;
3858 @node Elimination of tail recursion,,Optimizing away stack manipulation,Behind the curtain How does our code get optimized?
3859 @anchor{intro/tutorial04 elimination-of-tail-recursion}@anchor{47}
3860 @subsubsection Elimination of tail recursion
3863 Another significant optimization is the detection that the call to
3864 @code{factorial} is tail recursion, which can be eliminated in favor of
3868 $ less /tmp/libgccjit-1Hywc0/fake.c.030t.tailr1
3874 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
3877 Symbols to be put in SSA form
3879 Incremental SSA update started at block: 0
3880 Number of blocks in CFG: 5
3881 Number of blocks to update: 4 ( 80%)
3884 factorial (signed int arg)
3889 signed int stack[8];
3890 signed int stack_depth;
3893 signed int mult_acc_1;
3897 signed int mul_tmp_44;
3898 signed int mult_acc_51;
3900 # arg_5 = PHI <arg_39(D)(0), _38(3)>
3901 # mult_acc_1 = PHI <1(0), mult_acc_51(3)>
3904 _21 = (signed int) _20;
3906 goto <bb 4> (instr9);
3908 goto <bb 3> (instr4);
3913 mult_acc_51 = mult_acc_1 * arg_5;
3914 goto <bb 2> (initial);
3916 # stack$0_52 = PHI <arg_5(2)>
3919 stack =@{v@} @{CLOBBER@};
3920 mul_tmp_44 = mult_acc_1 * stack$0_52;
3928 @c Copyright (C) 2014 Free Software Foundation, Inc.
3929 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
3931 @c This is free software: you can redistribute it and/or modify it
3932 @c under the terms of the GNU General Public License as published by
3933 @c the Free Software Foundation, either version 3 of the License, or
3934 @c (at your option) any later version.
3936 @c This program is distributed in the hope that it will be useful, but
3937 @c WITHOUT ANY WARRANTY; without even the implied warranty of
3938 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
3939 @c General Public License for more details.
3941 @c You should have received a copy of the GNU General Public License
3942 @c along with this program. If not, see
3943 @c <http://www.gnu.org/licenses/>.
3945 @node Topic Reference,C++ bindings for libgccjit,Tutorial,Top
3946 @anchor{topics/index doc}@anchor{48}@anchor{topics/index topic-reference}@anchor{49}
3947 @chapter Topic Reference
3950 @c Copyright (C) 2014 Free Software Foundation, Inc.
3951 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
3953 @c This is free software: you can redistribute it and/or modify it
3954 @c under the terms of the GNU General Public License as published by
3955 @c the Free Software Foundation, either version 3 of the License, or
3956 @c (at your option) any later version.
3958 @c This program is distributed in the hope that it will be useful, but
3959 @c WITHOUT ANY WARRANTY; without even the implied warranty of
3960 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
3961 @c General Public License for more details.
3963 @c You should have received a copy of the GNU General Public License
3964 @c along with this program. If not, see
3965 @c <http://www.gnu.org/licenses/>.
3968 * Compilation contexts::
3972 * Creating and using functions::
3973 * Source Locations::
3974 * Compilation results::
3976 Compilation contexts
3978 * Lifetime-management::
3980 * Error-handling: Error-handling<2>.
3982 * Options: Options<2>.
3993 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile.
3994 * Structures and unions::
4000 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions.
4004 * Simple expressions::
4005 * Unary Operations::
4006 * Binary Operations::
4013 * Global variables::
4015 Creating and using functions
4029 @node Compilation contexts,Objects,,Topic Reference
4030 @anchor{topics/contexts compilation-contexts}@anchor{4a}@anchor{topics/contexts doc}@anchor{4b}
4031 @section Compilation contexts
4034 @geindex gcc_jit_context (C type)
4035 @anchor{topics/contexts gcc_jit_context}@anchor{8}
4036 @deffn {C Type} gcc_jit_context
4039 The top-level of the API is the @pxref{8,,gcc_jit_context} type.
4041 A @pxref{8,,gcc_jit_context} instance encapsulates the state of a
4044 You can set up options on it, and add types, functions and code.
4045 Invoking @pxref{15,,gcc_jit_context_compile()} on it gives you a
4046 @pxref{16,,gcc_jit_result}.
4049 * Lifetime-management::
4051 * Error-handling: Error-handling<2>.
4053 * Options: Options<2>.
4057 @node Lifetime-management,Thread-safety,,Compilation contexts
4058 @anchor{topics/contexts lifetime-management}@anchor{4c}
4059 @subsection Lifetime-management
4062 Contexts are the unit of lifetime-management within the API: objects
4063 have their lifetime bounded by the context they are created within, and
4064 cleanup of such objects is done for you when the context is released.
4066 @geindex gcc_jit_context_acquire (C function)
4067 @anchor{topics/contexts gcc_jit_context_acquire}@anchor{9}
4068 @deffn {C Function} gcc_jit_context *gcc_jit_context_acquire (void)
4070 This function acquires a new @pxref{e,,gcc_jit_object *} instance,
4071 which is independent of any others that may be present within this
4075 @geindex gcc_jit_context_release (C function)
4076 @anchor{topics/contexts gcc_jit_context_release}@anchor{c}
4077 @deffn {C Function} void gcc_jit_context_release (gcc_jit_context@w{ }*ctxt)
4079 This function releases all resources associated with the given context.
4080 Both the context itself and all of its @pxref{e,,gcc_jit_object *}
4081 instances are cleaned up. It should be called exactly once on a given
4084 It is invalid to use the context or any of its "contextual" objects
4088 gcc_jit_context_release (ctxt);
4094 @geindex gcc_jit_context_new_child_context (C function)
4095 @anchor{topics/contexts gcc_jit_context_new_child_context}@anchor{4d}
4096 @deffn {C Function} gcc_jit_context * gcc_jit_context_new_child_context (gcc_jit_context@w{ }*parent_ctxt)
4098 Given an existing JIT context, create a child context.
4100 The child inherits a copy of all option-settings from the parent.
4102 The child can reference objects created within the parent, but not
4105 The lifetime of the child context must be bounded by that of the
4106 parent: you should release a child context before releasing the parent
4109 If you use a function from a parent context within a child context,
4110 you have to compile the parent context before you can compile the
4111 child context, and the gcc_jit_result of the parent context must
4112 outlive the gcc_jit_result of the child context.
4114 This allows caching of shared initializations. For example, you could
4115 create types and declarations of global functions in a parent context
4116 once within a process, and then create child contexts whenever a
4117 function or loop becomes hot. Each such child context can be used for
4118 JIT-compiling just one function or loop, but can reference types
4119 and helper functions created within the parent context.
4121 Contexts can be arbitrarily nested, provided the above rules are
4122 followed, but it's probably not worth going above 2 or 3 levels, and
4123 there will likely be a performance hit for such nesting.
4126 @node Thread-safety,Error-handling<2>,Lifetime-management,Compilation contexts
4127 @anchor{topics/contexts thread-safety}@anchor{4e}
4128 @subsection Thread-safety
4131 Instances of @pxref{8,,gcc_jit_context *} created via
4132 @pxref{9,,gcc_jit_context_acquire()} are independent from each other:
4133 only one thread may use a given context at once, but multiple threads
4134 could each have their own contexts without needing locks.
4136 Contexts created via @pxref{4d,,gcc_jit_context_new_child_context()} are
4137 related to their parent context. They can be partitioned by their
4138 ultimate ancestor into independent "family trees". Only one thread
4139 within a process may use a given "family tree" of such contexts at once,
4140 and if you're using multiple threads you should provide your own locking
4141 around entire such context partitions.
4143 @node Error-handling<2>,Debugging,Thread-safety,Compilation contexts
4144 @anchor{topics/contexts error-handling}@anchor{19}@anchor{topics/contexts id1}@anchor{4f}
4145 @subsection Error-handling
4148 Various kinds of errors are possible when using the API, such as
4149 mismatched types in an assignment. You can only compile and get code from
4150 a context if no errors occur.
4152 Errors are printed on stderr and can be queried using
4153 @pxref{50,,gcc_jit_context_get_first_error()}.
4155 They typically contain the name of the API entrypoint where the error
4156 occurred, and pertinent information on the problem:
4159 ./buggy-program: error: gcc_jit_block_add_assignment: mismatching types: assignment to i (type: int) from "hello world" (type: const char *)
4164 In general, if an error occurs when using an API entrypoint, the
4165 entrypoint returns NULL. You don't have to check everywhere for NULL
4166 results, since the API handles a NULL being passed in for any
4167 argument by issuing another error. This typically leads to a cascade of
4168 followup error messages, but is safe (albeit verbose).
4170 @geindex gcc_jit_context_get_first_error (C function)
4171 @anchor{topics/contexts gcc_jit_context_get_first_error}@anchor{50}
4172 @deffn {C Function} const char * gcc_jit_context_get_first_error (gcc_jit_context@w{ }*ctxt)
4174 Returns the first error message that occurred on the context.
4176 The returned string is valid for the rest of the lifetime of the
4179 If no errors occurred, this will be NULL.
4182 @node Debugging,Options<2>,Error-handling<2>,Compilation contexts
4183 @anchor{topics/contexts debugging}@anchor{51}
4184 @subsection Debugging
4187 @geindex gcc_jit_context_dump_to_file (C function)
4188 @anchor{topics/contexts gcc_jit_context_dump_to_file}@anchor{52}
4189 @deffn {C Function} void gcc_jit_context_dump_to_file (gcc_jit_context@w{ }*ctxt, const char@w{ }*path, int@w{ }update_locations)
4191 To help with debugging: dump a C-like representation to the given path,
4192 describing what's been set up on the context.
4194 If "update_locations" is true, then also set up @pxref{3b,,gcc_jit_location}
4195 information throughout the context, pointing at the dump file as if it
4196 were a source file. This may be of use in conjunction with
4197 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} to allow stepping through the
4201 @geindex gcc_jit_context_enable_dump (C function)
4202 @anchor{topics/contexts gcc_jit_context_enable_dump}@anchor{53}
4203 @deffn {C Function} void gcc_jit_context_enable_dump (gcc_jit_context@w{ }*ctxt, const char@w{ }*dumpname, char@w{ }**out_ptr)
4205 Enable the dumping of a specific set of internal state from the
4206 compilation, capturing the result in-memory as a buffer.
4208 Parameter "dumpname" corresponds to the equivalent gcc command-line
4209 option, without the "-fdump-" prefix.
4210 For example, to get the equivalent of @code{-fdump-tree-vrp1},
4211 supply @code{"tree-vrp1"}:
4214 static char *dump_vrp1;
4217 create_code (gcc_jit_context *ctxt)
4219 gcc_jit_context_enable_dump (ctxt, "tree-vrp1", &dump_vrp1);
4220 /* (other API calls omitted for brevity) */
4226 The context directly stores the dumpname as a @code{(const char *)}, so
4227 the passed string must outlive the context.
4229 @pxref{15,,gcc_jit_context_compile()} will capture the dump as a
4230 dynamically-allocated buffer, writing it to @code{*out_ptr}.
4232 The caller becomes responsible for calling:
4240 each time that @pxref{15,,gcc_jit_context_compile()} is called.
4241 @code{*out_ptr} will be written to, either with the address of a buffer,
4242 or with @code{NULL} if an error occurred.
4246 This API entrypoint is likely to be less stable than the others.
4247 In particular, both the precise dumpnames, and the format and content
4248 of the dumps are subject to change.
4250 It exists primarily for writing the library's own test suite.
4255 @node Options<2>,,Debugging,Compilation contexts
4256 @anchor{topics/contexts options}@anchor{54}
4267 @node String Options,Boolean options,,Options<2>
4268 @anchor{topics/contexts string-options}@anchor{55}
4269 @subsubsection String Options
4272 @geindex gcc_jit_context_set_str_option (C function)
4273 @anchor{topics/contexts gcc_jit_context_set_str_option}@anchor{56}
4274 @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)
4276 Set a string option of the context.
4278 @geindex gcc_jit_str_option (C type)
4279 @anchor{topics/contexts gcc_jit_str_option}@anchor{57}
4280 @deffn {C Type} enum gcc_jit_str_option
4283 There is currently just one string option:
4285 @geindex GCC_JIT_STR_OPTION_PROGNAME (C macro)
4286 @anchor{topics/contexts GCC_JIT_STR_OPTION_PROGNAME}@anchor{58}
4287 @deffn {C Macro} GCC_JIT_STR_OPTION_PROGNAME
4289 The name of the program, for use as a prefix when printing error
4290 messages to stderr. If @cite{NULL}, or default, "libgccjit.so" is used.
4294 @node Boolean options,Integer options,String Options,Options<2>
4295 @anchor{topics/contexts boolean-options}@anchor{59}
4296 @subsubsection Boolean options
4299 @geindex gcc_jit_context_set_bool_option (C function)
4300 @anchor{topics/contexts gcc_jit_context_set_bool_option}@anchor{1b}
4301 @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)
4303 Set a boolean option of the context.
4304 Zero is "false" (the default), non-zero is "true".
4306 @geindex gcc_jit_bool_option (C type)
4307 @anchor{topics/contexts gcc_jit_bool_option}@anchor{5a}
4308 @deffn {C Type} enum gcc_jit_bool_option
4311 @geindex GCC_JIT_BOOL_OPTION_DEBUGINFO (C macro)
4312 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DEBUGINFO}@anchor{42}
4313 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DEBUGINFO
4315 If true, @pxref{15,,gcc_jit_context_compile()} will attempt to do the right
4316 thing so that if you attach a debugger to the process, it will
4317 be able to inspect variables and step through your code.
4319 Note that you can't step through code unless you set up source
4320 location information for the code (by creating and passing in
4321 @pxref{3b,,gcc_jit_location} instances).
4324 @geindex GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE (C macro)
4325 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE}@anchor{5b}
4326 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE
4328 If true, @pxref{15,,gcc_jit_context_compile()} will dump its initial
4329 "tree" representation of your code to stderr (before any
4332 Here's some sample output (from the @cite{square} example):
4335 <statement_list 0x7f4875a62cc0
4336 type <void_type 0x7f4875a64bd0 VOID
4337 align 8 symtab 0 alias set -1 canonical type 0x7f4875a64bd0
4338 pointer_to_this <pointer_type 0x7f4875a64c78>>
4339 side-effects head 0x7f4875a761e0 tail 0x7f4875a761f8 stmts 0x7f4875a62d20 0x7f4875a62d00
4341 stmt <label_expr 0x7f4875a62d20 type <void_type 0x7f4875a64bd0>
4343 arg 0 <label_decl 0x7f4875a79080 entry type <void_type 0x7f4875a64bd0>
4344 VOID file (null) line 0 col 0
4345 align 1 context <function_decl 0x7f4875a77500 square>>>
4346 stmt <return_expr 0x7f4875a62d00
4347 type <integer_type 0x7f4875a645e8 public SI
4348 size <integer_cst 0x7f4875a623a0 constant 32>
4349 unit size <integer_cst 0x7f4875a623c0 constant 4>
4350 align 32 symtab 0 alias set -1 canonical type 0x7f4875a645e8 precision 32 min <integer_cst 0x7f4875a62340 -2147483648> max <integer_cst 0x7f4875a62360 2147483647>
4351 pointer_to_this <pointer_type 0x7f4875a6b348>>
4353 arg 0 <modify_expr 0x7f4875a72a78 type <integer_type 0x7f4875a645e8>
4354 side-effects arg 0 <result_decl 0x7f4875a7a000 D.54>
4355 arg 1 <mult_expr 0x7f4875a72a50 type <integer_type 0x7f4875a645e8>
4356 arg 0 <parm_decl 0x7f4875a79000 i> arg 1 <parm_decl 0x7f4875a79000 i>>>>>
4362 @geindex GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE (C macro)
4363 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE}@anchor{1c}
4364 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE
4366 If true, @pxref{15,,gcc_jit_context_compile()} will dump the "gimple"
4367 representation of your code to stderr, before any optimizations
4368 are performed. The dump resembles C code:
4371 square (signed int i)
4384 @geindex GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE (C macro)
4385 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE}@anchor{1d}
4386 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE
4388 If true, @pxref{15,,gcc_jit_context_compile()} will dump the final
4389 generated code to stderr, in the form of assembly language:
4395 .type square, @@function
4400 .cfi_def_cfa_offset 16
4403 .cfi_def_cfa_register 6
4407 imull -4(%rbp), %eax
4413 .size square, .-square
4414 .ident "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.1-%@{gcc_release@})"
4415 .section .note.GNU-stack,"",@@progbits
4421 @geindex GCC_JIT_BOOL_OPTION_DUMP_SUMMARY (C macro)
4422 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_SUMMARY}@anchor{5c}
4423 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_SUMMARY
4425 If true, @pxref{15,,gcc_jit_context_compile()} will print information to stderr
4426 on the actions it is performing, followed by a profile showing
4427 the time taken and memory usage of each phase.
4430 @geindex GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING (C macro)
4431 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING}@anchor{5d}
4432 @deffn {C Macro} GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING
4434 If true, @pxref{15,,gcc_jit_context_compile()} will dump copious
4435 amount of information on what it's doing to various
4436 files within a temporary directory. Use
4437 @pxref{5e,,GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES} (see below) to
4438 see the results. The files are intended to be human-readable,
4439 but the exact files and their formats are subject to change.
4442 @geindex GCC_JIT_BOOL_OPTION_SELFCHECK_GC (C macro)
4443 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_SELFCHECK_GC}@anchor{5f}
4444 @deffn {C Macro} GCC_JIT_BOOL_OPTION_SELFCHECK_GC
4446 If true, libgccjit will aggressively run its garbage collector, to
4447 shake out bugs (greatly slowing down the compile). This is likely
4448 to only be of interest to developers @emph{of} the library. It is
4449 used when running the selftest suite.
4452 @geindex GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES (C macro)
4453 @anchor{topics/contexts GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES}@anchor{5e}
4454 @deffn {C Macro} GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES
4456 If true, the @pxref{8,,gcc_jit_context} will not clean up intermediate files
4457 written to the filesystem, and will display their location on stderr.
4461 @node Integer options,,Boolean options,Options<2>
4462 @anchor{topics/contexts integer-options}@anchor{60}
4463 @subsubsection Integer options
4466 @geindex gcc_jit_context_set_int_option (C function)
4467 @anchor{topics/contexts gcc_jit_context_set_int_option}@anchor{1e}
4468 @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)
4470 Set an integer option of the context.
4472 @geindex gcc_jit_int_option (C type)
4473 @anchor{topics/contexts gcc_jit_int_option}@anchor{61}
4474 @deffn {C Type} enum gcc_jit_int_option
4477 There is currently just one integer option:
4479 @geindex GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL (C macro)
4480 @anchor{topics/contexts GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}@anchor{1f}
4481 @deffn {C Macro} GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL
4483 How much to optimize the code.
4485 Valid values are 0-3, corresponding to GCC's command-line options
4488 The default value is 0 (unoptimized).
4492 @c Copyright (C) 2014 Free Software Foundation, Inc.
4493 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
4495 @c This is free software: you can redistribute it and/or modify it
4496 @c under the terms of the GNU General Public License as published by
4497 @c the Free Software Foundation, either version 3 of the License, or
4498 @c (at your option) any later version.
4500 @c This program is distributed in the hope that it will be useful, but
4501 @c WITHOUT ANY WARRANTY; without even the implied warranty of
4502 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
4503 @c General Public License for more details.
4505 @c You should have received a copy of the GNU General Public License
4506 @c along with this program. If not, see
4507 @c <http://www.gnu.org/licenses/>.
4509 @node Objects,Types,Compilation contexts,Topic Reference
4510 @anchor{topics/objects objects}@anchor{62}@anchor{topics/objects doc}@anchor{63}
4514 @geindex gcc_jit_object (C type)
4515 @anchor{topics/objects gcc_jit_object}@anchor{e}
4516 @deffn {C Type} gcc_jit_object
4519 Almost every entity in the API (with the exception of
4520 @pxref{8,,gcc_jit_context *} and @pxref{16,,gcc_jit_result *}) is a
4521 "contextual" object, a @pxref{e,,gcc_jit_object *}
4531 is associated with a @pxref{8,,gcc_jit_context *}.
4534 is automatically cleaned up for you when its context is released so
4535 you don't need to manually track and cleanup all objects, just the
4540 Although the API is C-based, there is a form of class hierarchy, which
4558 There are casting methods for upcasting from subclasses to parent classes.
4559 For example, @pxref{d,,gcc_jit_type_as_object()}:
4562 gcc_jit_object *obj = gcc_jit_type_as_object (int_type);
4567 The object "base class" has the following operations:
4569 @geindex gcc_jit_object_get_context (C function)
4570 @anchor{topics/objects gcc_jit_object_get_context}@anchor{64}
4571 @deffn {C Function} gcc_jit_context *gcc_jit_object_get_context (gcc_jit_object@w{ }*obj)
4573 Which context is "obj" within?
4576 @geindex gcc_jit_object_get_debug_string (C function)
4577 @anchor{topics/objects gcc_jit_object_get_debug_string}@anchor{f}
4578 @deffn {C Function} const char *gcc_jit_object_get_debug_string (gcc_jit_object@w{ }*obj)
4580 Generate a human-readable description for the given object.
4585 printf ("obj: %s\n", gcc_jit_object_get_debug_string (obj));
4590 might give this text on stdout:
4600 If you call this on an object, the @cite{const char *} buffer is allocated
4601 and generated on the first call for that object, and the buffer will
4602 have the same lifetime as the object i.e. it will exist until the
4603 object's context is released.
4608 @c Copyright (C) 2014 Free Software Foundation, Inc.
4609 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
4611 @c This is free software: you can redistribute it and/or modify it
4612 @c under the terms of the GNU General Public License as published by
4613 @c the Free Software Foundation, either version 3 of the License, or
4614 @c (at your option) any later version.
4616 @c This program is distributed in the hope that it will be useful, but
4617 @c WITHOUT ANY WARRANTY; without even the implied warranty of
4618 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
4619 @c General Public License for more details.
4621 @c You should have received a copy of the GNU General Public License
4622 @c along with this program. If not, see
4623 @c <http://www.gnu.org/licenses/>.
4625 @node Types,Expressions,Objects,Topic Reference
4626 @anchor{topics/types doc}@anchor{65}@anchor{topics/types types}@anchor{66}
4630 @geindex gcc_jit_type (C type)
4631 @anchor{topics/types gcc_jit_type}@anchor{a}
4632 @deffn {C Type} gcc_jit_type
4634 gcc_jit_type represents a type within the library.
4637 @geindex gcc_jit_type_as_object (C function)
4638 @anchor{topics/types gcc_jit_type_as_object}@anchor{d}
4639 @deffn {C Function} gcc_jit_object *gcc_jit_type_as_object (gcc_jit_type@w{ }*type)
4641 Upcast a type to an object.
4644 Types can be created in several ways:
4650 fundamental types can be accessed using
4651 @pxref{b,,gcc_jit_context_get_type()}:
4654 gcc_jit_type *int_type = gcc_jit_context_get_type (GCC_JIT_TYPE_INT);
4659 See @pxref{b,,gcc_jit_context_get_type()} for the available types.
4662 derived types can be accessed by using functions such as
4663 @pxref{67,,gcc_jit_type_get_pointer()} and @pxref{68,,gcc_jit_type_get_const()}:
4666 gcc_jit_type *const_int_star = gcc_jit_type_get_pointer (gcc_jit_type_get_const (int_type));
4667 gcc_jit_type *int_const_star = gcc_jit_type_get_const (gcc_jit_type_get_pointer (int_type));
4673 by creating structures (see below).
4678 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile.
4679 * Structures and unions::
4683 @node Standard types,Pointers const and volatile,,Types
4684 @anchor{topics/types standard-types}@anchor{69}
4685 @subsection Standard types
4688 @geindex gcc_jit_context_get_type (C function)
4689 @anchor{topics/types gcc_jit_context_get_type}@anchor{b}
4690 @deffn {C Function} gcc_jit_type *gcc_jit_context_get_type (gcc_jit_context@w{ }*ctxt, enum gcc_jit_types@w{ }type_)
4692 Access a specific type. The available types are:
4695 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
4698 @cite{enum gcc_jit_types} value
4706 @code{GCC_JIT_TYPE_VOID}
4710 C's @code{void} type.
4714 @code{GCC_JIT_TYPE_VOID_PTR}
4722 @code{GCC_JIT_TYPE_BOOL}
4726 C++'s @code{bool} type; also C99's
4727 @code{_Bool} type, aka @code{bool} if
4732 @code{GCC_JIT_TYPE_CHAR}
4736 C's @code{char} (of some signedness)
4740 @code{GCC_JIT_TYPE_SIGNED_CHAR}
4744 C's @code{signed char}
4748 @code{GCC_JIT_TYPE_UNSIGNED_CHAR}
4752 C's @code{unsigned char}
4756 @code{GCC_JIT_TYPE_SHORT}
4760 C's @code{short} (signed)
4764 @code{GCC_JIT_TYPE_UNSIGNED_SHORT}
4768 C's @code{unsigned short}
4772 @code{GCC_JIT_TYPE_INT}
4776 C's @code{int} (signed)
4780 @code{GCC_JIT_TYPE_UNSIGNED_INT}
4784 C's @code{unsigned int}
4788 @code{GCC_JIT_TYPE_LONG}
4792 C's @code{long} (signed)
4796 @code{GCC_JIT_TYPE_UNSIGNED_LONG}
4800 C's @code{unsigned long}
4804 @code{GCC_JIT_TYPE_LONG_LONG}
4808 C99's @code{long long} (signed)
4812 @code{GCC_JIT_TYPE_UNSIGNED_LONG_LONG}
4816 C99's @code{unsigned long long}
4820 @code{GCC_JIT_TYPE_FLOAT}
4826 @code{GCC_JIT_TYPE_DOUBLE}
4832 @code{GCC_JIT_TYPE_LONG_DOUBLE}
4838 @code{GCC_JIT_TYPE_CONST_CHAR_PTR}
4842 C type: @code{(const char *)}
4846 @code{GCC_JIT_TYPE_SIZE_T}
4850 C's @code{size_t} type
4854 @code{GCC_JIT_TYPE_FILE_PTR}
4858 C type: @code{(FILE *)}
4862 @code{GCC_JIT_TYPE_COMPLEX_FLOAT}
4866 C99's @code{_Complex float}
4870 @code{GCC_JIT_TYPE_COMPLEX_DOUBLE}
4874 C99's @code{_Complex double}
4878 @code{GCC_JIT_TYPE_COMPLEX_LONG_DOUBLE}
4882 C99's @code{_Complex long double}
4888 @geindex gcc_jit_context_get_int_type (C function)
4889 @anchor{topics/types gcc_jit_context_get_int_type}@anchor{6a}
4890 @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)
4892 Access the integer type of the given size.
4895 @node Pointers const and volatile,Structures and unions,Standard types,Types
4896 @anchor{topics/types pointers-const-and-volatile}@anchor{6b}
4897 @subsection Pointers, @cite{const}, and @cite{volatile}
4900 @geindex gcc_jit_type_get_pointer (C function)
4901 @anchor{topics/types gcc_jit_type_get_pointer}@anchor{67}
4902 @deffn {C Function} gcc_jit_type *gcc_jit_type_get_pointer (gcc_jit_type@w{ }*type)
4904 Given type "T", get type "T*".
4907 @geindex gcc_jit_type_get_const (C function)
4908 @anchor{topics/types gcc_jit_type_get_const}@anchor{68}
4909 @deffn {C Function} gcc_jit_type *gcc_jit_type_get_const (gcc_jit_type@w{ }*type)
4911 Given type "T", get type "const T".
4914 @geindex gcc_jit_type_get_volatile (C function)
4915 @anchor{topics/types gcc_jit_type_get_volatile}@anchor{6c}
4916 @deffn {C Function} gcc_jit_type *gcc_jit_type_get_volatile (gcc_jit_type@w{ }*type)
4918 Given type "T", get type "volatile T".
4921 @geindex gcc_jit_context_new_array_type (C function)
4922 @anchor{topics/types gcc_jit_context_new_array_type}@anchor{6d}
4923 @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)
4925 Given type "T", get type "T[N]" (for a constant N).
4928 @node Structures and unions,,Pointers const and volatile,Types
4929 @anchor{topics/types structures-and-unions}@anchor{6e}
4930 @subsection Structures and unions
4933 @geindex gcc_jit_struct (C type)
4934 @anchor{topics/types gcc_jit_struct}@anchor{6f}
4935 @deffn {C Type} gcc_jit_struct
4938 A compound type analagous to a C @cite{struct}.
4940 @geindex gcc_jit_field (C type)
4941 @anchor{topics/types gcc_jit_field}@anchor{70}
4942 @deffn {C Type} gcc_jit_field
4945 A field within a @pxref{6f,,gcc_jit_struct}.
4947 You can model C @cite{struct} types by creating @pxref{6f,,gcc_jit_struct *} and
4948 @pxref{70,,gcc_jit_field} instances, in either order:
4954 by creating the fields, then the structure. For example, to model:
4957 struct coord @{double x; double y; @};
4965 gcc_jit_field *field_x =
4966 gcc_jit_context_new_field (ctxt, NULL, double_type, "x");
4967 gcc_jit_field *field_y =
4968 gcc_jit_context_new_field (ctxt, NULL, double_type, "y");
4969 gcc_jit_field *fields[2] = @{field_x, field_y@};
4970 gcc_jit_struct *coord =
4971 gcc_jit_context_new_struct_type (ctxt, NULL, "coord", 2, fields);
4977 by creating the structure, then populating it with fields, typically
4978 to allow modelling self-referential structs such as:
4981 struct node @{ int m_hash; struct node *m_next; @};
4989 gcc_jit_type *node =
4990 gcc_jit_context_new_opaque_struct (ctxt, NULL, "node");
4991 gcc_jit_type *node_ptr =
4992 gcc_jit_type_get_pointer (node);
4993 gcc_jit_field *field_hash =
4994 gcc_jit_context_new_field (ctxt, NULL, int_type, "m_hash");
4995 gcc_jit_field *field_next =
4996 gcc_jit_context_new_field (ctxt, NULL, node_ptr, "m_next");
4997 gcc_jit_field *fields[2] = @{field_hash, field_next@};
4998 gcc_jit_struct_set_fields (node, NULL, 2, fields);
5004 @geindex gcc_jit_context_new_field (C function)
5005 @anchor{topics/types gcc_jit_context_new_field}@anchor{71}
5006 @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)
5008 Construct a new field, with the given type and name.
5011 @geindex gcc_jit_field_as_object (C function)
5012 @anchor{topics/types gcc_jit_field_as_object}@anchor{72}
5013 @deffn {C Function} gcc_jit_object * gcc_jit_field_as_object (gcc_jit_field@w{ }*field)
5015 Upcast from field to object.
5018 @geindex gcc_jit_context_new_struct_type (C function)
5019 @anchor{topics/types gcc_jit_context_new_struct_type}@anchor{73}
5020 @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)
5024 Construct a new struct type, with the given name and fields.
5028 @geindex gcc_jit_context_new_opaque_struct (C function)
5029 @anchor{topics/types gcc_jit_context_new_opaque_struct}@anchor{74}
5030 @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)
5032 Construct a new struct type, with the given name, but without
5033 specifying the fields. The fields can be omitted (in which case the
5034 size of the struct is not known), or later specified using
5035 @pxref{75,,gcc_jit_struct_set_fields()}.
5038 @geindex gcc_jit_struct_as_type (C function)
5039 @anchor{topics/types gcc_jit_struct_as_type}@anchor{76}
5040 @deffn {C Function} gcc_jit_type * gcc_jit_struct_as_type (gcc_jit_struct@w{ }*struct_type)
5042 Upcast from struct to type.
5045 @geindex gcc_jit_struct_set_fields (C function)
5046 @anchor{topics/types gcc_jit_struct_set_fields}@anchor{75}
5047 @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)
5049 Populate the fields of a formerly-opaque struct type.
5051 This can only be called once on a given struct type.
5054 @c Copyright (C) 2014 Free Software Foundation, Inc.
5055 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
5057 @c This is free software: you can redistribute it and/or modify it
5058 @c under the terms of the GNU General Public License as published by
5059 @c the Free Software Foundation, either version 3 of the License, or
5060 @c (at your option) any later version.
5062 @c This program is distributed in the hope that it will be useful, but
5063 @c WITHOUT ANY WARRANTY; without even the implied warranty of
5064 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
5065 @c General Public License for more details.
5067 @c You should have received a copy of the GNU General Public License
5068 @c along with this program. If not, see
5069 @c <http://www.gnu.org/licenses/>.
5071 @node Expressions,Creating and using functions,Types,Topic Reference
5072 @anchor{topics/expressions expressions}@anchor{77}@anchor{topics/expressions doc}@anchor{78}
5073 @section Expressions
5079 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions.
5083 * Simple expressions::
5084 * Unary Operations::
5085 * Binary Operations::
5092 * Global variables::
5097 @node Rvalues,Lvalues,,Expressions
5098 @anchor{topics/expressions rvalues}@anchor{79}
5102 @geindex gcc_jit_rvalue (C type)
5103 @anchor{topics/expressions gcc_jit_rvalue}@anchor{13}
5104 @deffn {C Type} gcc_jit_rvalue
5107 A @pxref{13,,gcc_jit_rvalue *} is an expression that can be computed.
5109 It can be simple, e.g.:
5117 an integer value e.g. @cite{0} or @cite{42}
5120 a string literal e.g. @cite{"Hello world"}
5123 a variable e.g. @cite{i}. These are also lvalues (see below).
5135 a unary expression e.g. @cite{!cond}
5138 a binary expression e.g. @cite{(a + b)}
5141 a function call e.g. @cite{get_distance (&player_ship@comma{} &target)}
5148 Every rvalue has an associated type, and the API will check to ensure
5149 that types match up correctly (otherwise the context will emit an error).
5151 @geindex gcc_jit_rvalue_get_type (C function)
5152 @anchor{topics/expressions gcc_jit_rvalue_get_type}@anchor{7a}
5153 @deffn {C Function} gcc_jit_type *gcc_jit_rvalue_get_type (gcc_jit_rvalue@w{ }*rvalue)
5155 Get the type of this rvalue.
5158 @geindex gcc_jit_rvalue_as_object (C function)
5159 @anchor{topics/expressions gcc_jit_rvalue_as_object}@anchor{14}
5160 @deffn {C Function} gcc_jit_object *gcc_jit_rvalue_as_object (gcc_jit_rvalue@w{ }*rvalue)
5162 Upcast the given rvalue to be an object.
5166 * Simple expressions::
5167 * Unary Operations::
5168 * Binary Operations::
5175 @node Simple expressions,Unary Operations,,Rvalues
5176 @anchor{topics/expressions simple-expressions}@anchor{7b}
5177 @subsubsection Simple expressions
5180 @geindex gcc_jit_context_new_rvalue_from_int (C function)
5181 @anchor{topics/expressions gcc_jit_context_new_rvalue_from_int}@anchor{30}
5182 @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)
5184 Given a numeric type (integer or floating point), build an rvalue for
5185 the given constant value.
5188 @geindex gcc_jit_context_zero (C function)
5189 @anchor{topics/expressions gcc_jit_context_zero}@anchor{2b}
5190 @deffn {C Function} gcc_jit_rvalue *gcc_jit_context_zero (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*numeric_type)
5192 Given a numeric type (integer or floating point), get the rvalue for
5193 zero. Essentially this is just a shortcut for:
5196 gcc_jit_context_new_rvalue_from_int (ctxt, numeric_type, 0)
5202 @geindex gcc_jit_context_one (C function)
5203 @anchor{topics/expressions gcc_jit_context_one}@anchor{2f}
5204 @deffn {C Function} gcc_jit_rvalue *gcc_jit_context_one (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*numeric_type)
5206 Given a numeric type (integer or floating point), get the rvalue for
5207 zero. Essentially this is just a shortcut for:
5210 gcc_jit_context_new_rvalue_from_int (ctxt, numeric_type, 1)
5216 @geindex gcc_jit_context_new_rvalue_from_double (C function)
5217 @anchor{topics/expressions gcc_jit_context_new_rvalue_from_double}@anchor{31}
5218 @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)
5220 Given a numeric type (integer or floating point), build an rvalue for
5221 the given constant value.
5224 @geindex gcc_jit_context_new_rvalue_from_ptr (C function)
5225 @anchor{topics/expressions gcc_jit_context_new_rvalue_from_ptr}@anchor{7c}
5226 @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)
5228 Given a pointer type, build an rvalue for the given address.
5231 @geindex gcc_jit_context_null (C function)
5232 @anchor{topics/expressions gcc_jit_context_null}@anchor{7d}
5233 @deffn {C Function} gcc_jit_rvalue *gcc_jit_context_null (gcc_jit_context@w{ }*ctxt, gcc_jit_type@w{ }*pointer_type)
5235 Given a pointer type, build an rvalue for @code{NULL}. Essentially this
5236 is just a shortcut for:
5239 gcc_jit_context_new_rvalue_from_ptr (ctxt, pointer_type, NULL)
5245 @geindex gcc_jit_context_new_string_literal (C function)
5246 @anchor{topics/expressions gcc_jit_context_new_string_literal}@anchor{7e}
5247 @deffn {C Function} gcc_jit_rvalue * gcc_jit_context_new_string_literal (gcc_jit_context@w{ }*ctxt, const char@w{ }*value)
5249 Generate an rvalue for the given NIL-terminated string, of type
5250 @code{GCC_JIT_TYPE_CONST_CHAR_PTR}.
5253 @node Unary Operations,Binary Operations,Simple expressions,Rvalues
5254 @anchor{topics/expressions unary-operations}@anchor{7f}
5255 @subsubsection Unary Operations
5258 @geindex gcc_jit_context_new_unary_op (C function)
5259 @anchor{topics/expressions gcc_jit_context_new_unary_op}@anchor{80}
5260 @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)
5262 Build a unary operation out of an input rvalue.
5265 @geindex gcc_jit_unary_op (C type)
5266 @anchor{topics/expressions gcc_jit_unary_op}@anchor{81}
5267 @deffn {C Type} enum gcc_jit_unary_op
5270 The available unary operations are:
5273 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx}
5284 @pxref{82,,GCC_JIT_UNARY_OP_MINUS}
5292 @pxref{83,,GCC_JIT_UNARY_OP_BITWISE_NEGATE}
5300 @pxref{84,,GCC_JIT_UNARY_OP_LOGICAL_NEGATE}
5309 @geindex GCC_JIT_UNARY_OP_MINUS (C macro)
5310 @anchor{topics/expressions GCC_JIT_UNARY_OP_MINUS}@anchor{82}
5311 @deffn {C Macro} GCC_JIT_UNARY_OP_MINUS
5313 Negate an arithmetic value; analogous to:
5324 @geindex GCC_JIT_UNARY_OP_BITWISE_NEGATE (C macro)
5325 @anchor{topics/expressions GCC_JIT_UNARY_OP_BITWISE_NEGATE}@anchor{83}
5326 @deffn {C Macro} GCC_JIT_UNARY_OP_BITWISE_NEGATE
5328 Bitwise negation of an integer value (one's complement); analogous
5340 @geindex GCC_JIT_UNARY_OP_LOGICAL_NEGATE (C macro)
5341 @anchor{topics/expressions GCC_JIT_UNARY_OP_LOGICAL_NEGATE}@anchor{84}
5342 @deffn {C Macro} GCC_JIT_UNARY_OP_LOGICAL_NEGATE
5344 Logical negation of an arithmetic or pointer value; analogous to:
5355 @node Binary Operations,Comparisons,Unary Operations,Rvalues
5356 @anchor{topics/expressions binary-operations}@anchor{85}
5357 @subsubsection Binary Operations
5360 @geindex gcc_jit_context_new_binary_op (C function)
5361 @anchor{topics/expressions gcc_jit_context_new_binary_op}@anchor{12}
5362 @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)
5364 Build a binary operation out of two constituent rvalues.
5367 @geindex gcc_jit_binary_op (C type)
5368 @anchor{topics/expressions gcc_jit_binary_op}@anchor{86}
5369 @deffn {C Type} enum gcc_jit_binary_op
5372 The available binary operations are:
5375 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx}
5386 @pxref{87,,GCC_JIT_BINARY_OP_PLUS}
5394 @code{GCC_JIT_BINARY_OP_MINUS}
5402 @pxref{88,,GCC_JIT_BINARY_OP_MULT}
5410 @pxref{89,,GCC_JIT_BINARY_OP_DIVIDE}
5418 @pxref{8a,,GCC_JIT_BINARY_OP_MODULO}
5426 @pxref{8b,,GCC_JIT_BINARY_OP_BITWISE_AND}
5434 @pxref{8c,,GCC_JIT_BINARY_OP_BITWISE_XOR}
5442 @pxref{8d,,GCC_JIT_BINARY_OP_BITWISE_OR}
5450 @pxref{8e,,GCC_JIT_BINARY_OP_LOGICAL_AND}
5458 @pxref{8f,,GCC_JIT_BINARY_OP_LOGICAL_OR}
5466 @pxref{90,,GCC_JIT_BINARY_OP_LSHIFT}
5474 @pxref{91,,GCC_JIT_BINARY_OP_RSHIFT}
5483 @geindex GCC_JIT_BINARY_OP_PLUS (C macro)
5484 @anchor{topics/expressions GCC_JIT_BINARY_OP_PLUS}@anchor{87}
5485 @deffn {C Macro} GCC_JIT_BINARY_OP_PLUS
5487 Addition of arithmetic values; analogous to:
5497 For pointer addition, use @pxref{92,,gcc_jit_context_new_array_access()}.
5501 @deffn {C Macro} GCC_JIT_BINARY_OP_MINUS`
5503 Subtraction of arithmetic values; analogous to:
5514 @geindex GCC_JIT_BINARY_OP_MULT (C macro)
5515 @anchor{topics/expressions GCC_JIT_BINARY_OP_MULT}@anchor{88}
5516 @deffn {C Macro} GCC_JIT_BINARY_OP_MULT
5518 Multiplication of a pair of arithmetic values; analogous to:
5529 @geindex GCC_JIT_BINARY_OP_DIVIDE (C macro)
5530 @anchor{topics/expressions GCC_JIT_BINARY_OP_DIVIDE}@anchor{89}
5531 @deffn {C Macro} GCC_JIT_BINARY_OP_DIVIDE
5533 Quotient of division of arithmetic values; analogous to:
5543 The result type affects the kind of division: if the result type is
5544 integer-based, then the result is truncated towards zero, whereas
5545 a floating-point result type indicates floating-point division.
5548 @geindex GCC_JIT_BINARY_OP_MODULO (C macro)
5549 @anchor{topics/expressions GCC_JIT_BINARY_OP_MODULO}@anchor{8a}
5550 @deffn {C Macro} GCC_JIT_BINARY_OP_MODULO
5552 Remainder of division of arithmetic values; analogous to:
5563 @geindex GCC_JIT_BINARY_OP_BITWISE_AND (C macro)
5564 @anchor{topics/expressions GCC_JIT_BINARY_OP_BITWISE_AND}@anchor{8b}
5565 @deffn {C Macro} GCC_JIT_BINARY_OP_BITWISE_AND
5567 Bitwise AND; analogous to:
5578 @geindex GCC_JIT_BINARY_OP_BITWISE_XOR (C macro)
5579 @anchor{topics/expressions GCC_JIT_BINARY_OP_BITWISE_XOR}@anchor{8c}
5580 @deffn {C Macro} GCC_JIT_BINARY_OP_BITWISE_XOR
5582 Bitwise exclusive OR; analogous to:
5593 @geindex GCC_JIT_BINARY_OP_BITWISE_OR (C macro)
5594 @anchor{topics/expressions GCC_JIT_BINARY_OP_BITWISE_OR}@anchor{8d}
5595 @deffn {C Macro} GCC_JIT_BINARY_OP_BITWISE_OR
5597 Bitwise inclusive OR; analogous to:
5608 @geindex GCC_JIT_BINARY_OP_LOGICAL_AND (C macro)
5609 @anchor{topics/expressions GCC_JIT_BINARY_OP_LOGICAL_AND}@anchor{8e}
5610 @deffn {C Macro} GCC_JIT_BINARY_OP_LOGICAL_AND
5612 Logical AND; analogous to:
5615 (EXPR_A) && (EXPR_B)
5623 @geindex GCC_JIT_BINARY_OP_LOGICAL_OR (C macro)
5624 @anchor{topics/expressions GCC_JIT_BINARY_OP_LOGICAL_OR}@anchor{8f}
5625 @deffn {C Macro} GCC_JIT_BINARY_OP_LOGICAL_OR
5627 Logical OR; analogous to:
5630 (EXPR_A) || (EXPR_B)
5638 @geindex GCC_JIT_BINARY_OP_LSHIFT (C macro)
5639 @anchor{topics/expressions GCC_JIT_BINARY_OP_LSHIFT}@anchor{90}
5640 @deffn {C Macro} GCC_JIT_BINARY_OP_LSHIFT
5642 Left shift; analogous to:
5645 (EXPR_A) << (EXPR_B)
5653 @geindex GCC_JIT_BINARY_OP_RSHIFT (C macro)
5654 @anchor{topics/expressions GCC_JIT_BINARY_OP_RSHIFT}@anchor{91}
5655 @deffn {C Macro} GCC_JIT_BINARY_OP_RSHIFT
5657 Right shift; analogous to:
5660 (EXPR_A) >> (EXPR_B)
5668 @node Comparisons,Function calls,Binary Operations,Rvalues
5669 @anchor{topics/expressions comparisons}@anchor{93}
5670 @subsubsection Comparisons
5673 @geindex gcc_jit_context_new_comparison (C function)
5674 @anchor{topics/expressions gcc_jit_context_new_comparison}@anchor{2c}
5675 @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)
5677 Build a boolean rvalue out of the comparison of two other rvalues.
5680 @geindex gcc_jit_comparison (C type)
5681 @anchor{topics/expressions gcc_jit_comparison}@anchor{94}
5682 @deffn {C Type} enum gcc_jit_comparison
5686 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx}
5697 @code{GCC_JIT_COMPARISON_EQ}
5705 @code{GCC_JIT_COMPARISON_NE}
5713 @code{GCC_JIT_COMPARISON_LT}
5721 @code{GCC_JIT_COMPARISON_LE}
5729 @code{GCC_JIT_COMPARISON_GT}
5737 @code{GCC_JIT_COMPARISON_GE}
5746 @node Function calls,Type-coercion,Comparisons,Rvalues
5747 @anchor{topics/expressions function-calls}@anchor{95}
5748 @subsubsection Function calls
5751 @geindex gcc_jit_context_new_call (C function)
5752 @anchor{topics/expressions gcc_jit_context_new_call}@anchor{96}
5753 @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)
5755 Given a function and the given table of argument rvalues, construct a
5756 call to the function, with the result as an rvalue.
5760 @pxref{96,,gcc_jit_context_new_call()} merely builds a
5761 @pxref{13,,gcc_jit_rvalue} i.e. an expression that can be evaluated,
5762 perhaps as part of a more complicated expression.
5763 The call @emph{won't} happen unless you add a statement to a function
5764 that evaluates the expression.
5766 For example, if you want to call a function and discard the result
5767 (or to call a function with @code{void} return type), use
5768 @pxref{97,,gcc_jit_block_add_eval()}:
5771 /* Add "(void)printf (arg0, arg1);". */
5772 gcc_jit_block_add_eval (
5774 gcc_jit_context_new_call (
5786 @node Type-coercion,,Function calls,Rvalues
5787 @anchor{topics/expressions type-coercion}@anchor{98}
5788 @subsubsection Type-coercion
5791 @geindex gcc_jit_context_new_cast (C function)
5792 @anchor{topics/expressions gcc_jit_context_new_cast}@anchor{99}
5793 @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)
5795 Given an rvalue of T, construct another rvalue of another type.
5797 Currently only a limited set of conversions are possible:
5811 P* <-> Q*, for pointer types P and Q
5816 @node Lvalues,Working with pointers structs and unions,Rvalues,Expressions
5817 @anchor{topics/expressions lvalues}@anchor{9a}
5821 @geindex gcc_jit_lvalue (C type)
5822 @anchor{topics/expressions gcc_jit_lvalue}@anchor{24}
5823 @deffn {C Type} gcc_jit_lvalue
5826 An lvalue is something that can of the @emph{left}-hand side of an assignment:
5827 a storage area (such as a variable). It is also usable as an rvalue,
5828 where the rvalue is computed by reading from the storage area.
5830 @geindex gcc_jit_lvalue_as_object (C function)
5831 @anchor{topics/expressions gcc_jit_lvalue_as_object}@anchor{9b}
5832 @deffn {C Function} gcc_jit_object * gcc_jit_lvalue_as_object (gcc_jit_lvalue@w{ }*lvalue)
5834 Upcast an lvalue to be an object.
5837 @geindex gcc_jit_lvalue_as_rvalue (C function)
5838 @anchor{topics/expressions gcc_jit_lvalue_as_rvalue}@anchor{9c}
5839 @deffn {C Function} gcc_jit_rvalue * gcc_jit_lvalue_as_rvalue (gcc_jit_lvalue@w{ }*lvalue)
5841 Upcast an lvalue to be an rvalue.
5844 @geindex gcc_jit_lvalue_get_address (C function)
5845 @anchor{topics/expressions gcc_jit_lvalue_get_address}@anchor{9d}
5846 @deffn {C Function} gcc_jit_rvalue * gcc_jit_lvalue_get_address (gcc_jit_lvalue@w{ }*lvalue, gcc_jit_location@w{ }*loc)
5848 Take the address of an lvalue; analogous to:
5860 * Global variables::
5864 @node Global variables,,,Lvalues
5865 @anchor{topics/expressions global-variables}@anchor{9e}
5866 @subsubsection Global variables
5869 @geindex gcc_jit_context_new_global (C function)
5870 @anchor{topics/expressions gcc_jit_context_new_global}@anchor{9f}
5871 @deffn {C Function} gcc_jit_lvalue * gcc_jit_context_new_global (gcc_jit_context@w{ }*ctxt, gcc_jit_location@w{ }*loc, gcc_jit_type@w{ }*type, const char@w{ }*name)
5873 Add a new global variable of the given type and name to the context.
5876 @node Working with pointers structs and unions,,Lvalues,Expressions
5877 @anchor{topics/expressions working-with-pointers-structs-and-unions}@anchor{a0}
5878 @subsection Working with pointers, structs and unions
5881 @geindex gcc_jit_rvalue_dereference (C function)
5882 @anchor{topics/expressions gcc_jit_rvalue_dereference}@anchor{a1}
5883 @deffn {C Function} gcc_jit_lvalue * gcc_jit_rvalue_dereference (gcc_jit_rvalue@w{ }*rvalue, gcc_jit_location@w{ }*loc)
5885 Given an rvalue of pointer type @code{T *}, dereferencing the pointer,
5886 getting an lvalue of type @code{T}. Analogous to:
5897 Field access is provided separately for both lvalues and rvalues.
5899 @geindex gcc_jit_lvalue_access_field (C function)
5900 @anchor{topics/expressions gcc_jit_lvalue_access_field}@anchor{a2}
5901 @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)
5903 Given an lvalue of struct or union type, access the given field,
5904 getting an lvalue of the field's type. Analogous to:
5915 @geindex gcc_jit_rvalue_access_field (C function)
5916 @anchor{topics/expressions gcc_jit_rvalue_access_field}@anchor{a3}
5917 @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)
5919 Given an rvalue of struct or union type, access the given field
5920 as an rvalue. Analogous to:
5931 @geindex gcc_jit_rvalue_dereference_field (C function)
5932 @anchor{topics/expressions gcc_jit_rvalue_dereference_field}@anchor{a4}
5933 @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)
5935 Given an rvalue of pointer type @code{T *} where T is of struct or union
5936 type, access the given field as an lvalue. Analogous to:
5944 in C, itself equivalent to @code{(*EXPR).FIELD}.
5947 @geindex gcc_jit_context_new_array_access (C function)
5948 @anchor{topics/expressions gcc_jit_context_new_array_access}@anchor{92}
5949 @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)
5951 Given an rvalue of pointer type @code{T *}, get at the element @cite{T} at
5952 the given index, using standard C array indexing rules i.e. each
5953 increment of @code{index} corresponds to @code{sizeof(T)} bytes.
5962 in C (or, indeed, to @code{PTR + INDEX}).
5965 @c Copyright (C) 2014 Free Software Foundation, Inc.
5966 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
5968 @c This is free software: you can redistribute it and/or modify it
5969 @c under the terms of the GNU General Public License as published by
5970 @c the Free Software Foundation, either version 3 of the License, or
5971 @c (at your option) any later version.
5973 @c This program is distributed in the hope that it will be useful, but
5974 @c WITHOUT ANY WARRANTY; without even the implied warranty of
5975 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
5976 @c General Public License for more details.
5978 @c You should have received a copy of the GNU General Public License
5979 @c along with this program. If not, see
5980 @c <http://www.gnu.org/licenses/>.
5982 @node Creating and using functions,Source Locations,Expressions,Topic Reference
5983 @anchor{topics/functions doc}@anchor{a5}@anchor{topics/functions creating-and-using-functions}@anchor{a6}
5984 @section Creating and using functions
5995 @node Params,Functions,,Creating and using functions
5996 @anchor{topics/functions params}@anchor{a7}
6000 @geindex gcc_jit_param (C type)
6001 @anchor{topics/functions gcc_jit_param}@anchor{25}
6002 @deffn {C Type} gcc_jit_param
6004 A @cite{gcc_jit_param} represents a parameter to a function.
6007 @geindex gcc_jit_context_new_param (C function)
6008 @anchor{topics/functions gcc_jit_context_new_param}@anchor{10}
6009 @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)
6011 In preparation for creating a function, create a new parameter of the
6012 given type and name.
6015 Parameters are lvalues, and thus are also rvalues (and objects), so the
6016 following upcasts are available:
6018 @geindex gcc_jit_param_as_lvalue (C function)
6019 @anchor{topics/functions gcc_jit_param_as_lvalue}@anchor{a8}
6020 @deffn {C Function} gcc_jit_lvalue * gcc_jit_param_as_lvalue (gcc_jit_param@w{ }*param)
6022 Upcasting from param to lvalue.
6025 @geindex gcc_jit_param_as_rvalue (C function)
6026 @anchor{topics/functions gcc_jit_param_as_rvalue}@anchor{a9}
6027 @deffn {C Function} gcc_jit_rvalue * gcc_jit_param_as_rvalue (gcc_jit_param@w{ }*param)
6029 Upcasting from param to rvalue.
6032 @geindex gcc_jit_param_as_object (C function)
6033 @anchor{topics/functions gcc_jit_param_as_object}@anchor{aa}
6034 @deffn {C Function} gcc_jit_object * gcc_jit_param_as_object (gcc_jit_param@w{ }*param)
6036 Upcasting from param to object.
6039 @node Functions,Blocks,Params,Creating and using functions
6040 @anchor{topics/functions functions}@anchor{ab}
6041 @subsection Functions
6044 @geindex gcc_jit_function (C type)
6045 @anchor{topics/functions gcc_jit_function}@anchor{29}
6046 @deffn {C Type} gcc_jit_function
6048 A @cite{gcc_jit_function} represents a function - either one that we're
6049 creating ourselves, or one that we're referencing.
6052 @geindex gcc_jit_context_new_function (C function)
6053 @anchor{topics/functions gcc_jit_context_new_function}@anchor{11}
6054 @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)
6056 Create a gcc_jit_function with the given name and parameters.
6058 @geindex gcc_jit_function_kind (C type)
6059 @anchor{topics/functions gcc_jit_function_kind}@anchor{ac}
6060 @deffn {C Type} enum gcc_jit_function_kind
6063 This enum controls the kind of function created, and has the following
6068 @geindex GCC_JIT_FUNCTION_EXPORTED (C macro)
6069 @anchor{topics/functions GCC_JIT_FUNCTION_EXPORTED}@anchor{ad}
6070 @deffn {C Macro} GCC_JIT_FUNCTION_EXPORTED
6072 Function is defined by the client code and visible
6073 by name outside of the JIT.
6075 This value is required if you want to extract machine code
6076 for this function from a @pxref{16,,gcc_jit_result} via
6077 @pxref{17,,gcc_jit_result_get_code()}.
6080 @geindex GCC_JIT_FUNCTION_INTERNAL (C macro)
6081 @anchor{topics/functions GCC_JIT_FUNCTION_INTERNAL}@anchor{ae}
6082 @deffn {C Macro} GCC_JIT_FUNCTION_INTERNAL
6084 Function is defined by the client code, but is invisible
6085 outside of the JIT. Analogous to a "static" function.
6088 @geindex GCC_JIT_FUNCTION_IMPORTED (C macro)
6089 @anchor{topics/functions GCC_JIT_FUNCTION_IMPORTED}@anchor{af}
6090 @deffn {C Macro} GCC_JIT_FUNCTION_IMPORTED
6092 Function is not defined by the client code; we're merely
6093 referring to it. Analogous to using an "extern" function from a
6097 @geindex GCC_JIT_FUNCTION_ALWAYS_INLINE (C macro)
6098 @anchor{topics/functions GCC_JIT_FUNCTION_ALWAYS_INLINE}@anchor{b0}
6099 @deffn {C Macro} GCC_JIT_FUNCTION_ALWAYS_INLINE
6101 Function is only ever inlined into other functions, and is
6102 invisible outside of the JIT.
6104 Analogous to prefixing with @code{inline} and adding
6105 @code{__attribute__((always_inline))}
6107 Inlining will only occur when the optimization level is
6108 above 0; when optimization is off, this is essentially the
6109 same as GCC_JIT_FUNCTION_INTERNAL.
6114 @geindex gcc_jit_context_get_builtin_function (C function)
6115 @anchor{topics/functions gcc_jit_context_get_builtin_function}@anchor{b1}
6116 @deffn {C Function} gcc_jit_function *gcc_jit_context_get_builtin_function (gcc_jit_context@w{ }*ctxt, const char@w{ }*name)
6119 @geindex gcc_jit_function_as_object (C function)
6120 @anchor{topics/functions gcc_jit_function_as_object}@anchor{b2}
6121 @deffn {C Function} gcc_jit_object * gcc_jit_function_as_object (gcc_jit_function@w{ }*func)
6123 Upcasting from function to object.
6126 @geindex gcc_jit_function_get_param (C function)
6127 @anchor{topics/functions gcc_jit_function_get_param}@anchor{b3}
6128 @deffn {C Function} gcc_jit_param * gcc_jit_function_get_param (gcc_jit_function@w{ }*func, int@w{ }index)
6130 Get the param of the given index (0-based).
6133 @geindex gcc_jit_function_dump_to_dot (C function)
6134 @anchor{topics/functions gcc_jit_function_dump_to_dot}@anchor{33}
6135 @deffn {C Function} void gcc_jit_function_dump_to_dot (gcc_jit_function@w{ }*func, const char@w{ }*path)
6137 Emit the function in graphviz format to the given path.
6140 @geindex gcc_jit_function_new_local (C function)
6141 @anchor{topics/functions gcc_jit_function_new_local}@anchor{26}
6142 @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)
6144 Create a new local variable within the function, of the given type and
6148 @node Blocks,Statements,Functions,Creating and using functions
6149 @anchor{topics/functions blocks}@anchor{b4}
6153 @geindex gcc_jit_block (C type)
6154 @anchor{topics/functions gcc_jit_block}@anchor{28}
6155 @deffn {C Type} gcc_jit_block
6157 A @cite{gcc_jit_block} represents a basic block within a function i.e. a
6158 sequence of statements with a single entry point and a single exit
6161 The first basic block that you create within a function will
6164 Each basic block that you create within a function must be
6165 terminated, either with a conditional, a jump, or a return.
6167 It's legal to have multiple basic blocks that return within
6171 @geindex gcc_jit_function_new_block (C function)
6172 @anchor{topics/functions gcc_jit_function_new_block}@anchor{b5}
6173 @deffn {C Function} gcc_jit_block * gcc_jit_function_new_block (gcc_jit_function@w{ }*func, const char@w{ }*name)
6175 Create a basic block of the given name. The name may be NULL, but
6176 providing meaningful names is often helpful when debugging: it may
6177 show up in dumps of the internal representation, and in error
6181 @geindex gcc_jit_block_as_object (C function)
6182 @anchor{topics/functions gcc_jit_block_as_object}@anchor{b6}
6183 @deffn {C Function} gcc_jit_object * gcc_jit_block_as_object (gcc_jit_block@w{ }*block)
6185 Upcast from block to object.
6188 @geindex gcc_jit_block_get_function (C function)
6189 @anchor{topics/functions gcc_jit_block_get_function}@anchor{b7}
6190 @deffn {C Function} gcc_jit_function * gcc_jit_block_get_function (gcc_jit_block@w{ }*block)
6192 Which function is this block within?
6195 @node Statements,,Blocks,Creating and using functions
6196 @anchor{topics/functions statements}@anchor{b8}
6197 @subsection Statements
6200 @geindex gcc_jit_block_add_eval (C function)
6201 @anchor{topics/functions gcc_jit_block_add_eval}@anchor{97}
6202 @deffn {C Function} void gcc_jit_block_add_eval (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, gcc_jit_rvalue@w{ }*rvalue)
6204 Add evaluation of an rvalue, discarding the result
6205 (e.g. a function call that "returns" void).
6207 This is equivalent to this C code:
6216 @geindex gcc_jit_block_add_assignment (C function)
6217 @anchor{topics/functions gcc_jit_block_add_assignment}@anchor{2a}
6218 @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)
6220 Add evaluation of an rvalue, assigning the result to the given
6223 This is roughly equivalent to this C code:
6232 @geindex gcc_jit_block_add_assignment_op (C function)
6233 @anchor{topics/functions gcc_jit_block_add_assignment_op}@anchor{2e}
6234 @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)
6236 Add evaluation of an rvalue, using the result to modify an
6239 This is analogous to "+=" and friends:
6253 gcc_jit_block_add_assignment_op (
6256 GCC_JIT_BINARY_OP_PLUS,
6257 gcc_jit_context_one (ctxt, int_type));
6263 @geindex gcc_jit_block_add_comment (C function)
6264 @anchor{topics/functions gcc_jit_block_add_comment}@anchor{3d}
6265 @deffn {C Function} void gcc_jit_block_add_comment (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc, const char@w{ }*text)
6267 Add a no-op textual comment to the internal representation of the
6268 code. It will be optimized away, but will be visible in the dumps
6269 seen via @pxref{5b,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE}
6270 and @pxref{1c,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE},
6271 and thus may be of use when debugging how your project's internal
6272 representation gets converted to the libgccjit IR.
6275 @geindex gcc_jit_block_end_with_conditional (C function)
6276 @anchor{topics/functions gcc_jit_block_end_with_conditional}@anchor{2d}
6277 @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)
6279 Terminate a block by adding evaluation of an rvalue, branching on the
6280 result to the appropriate successor block.
6282 This is roughly equivalent to this C code:
6293 block, boolval, on_true, and on_false must be non-NULL.
6296 @geindex gcc_jit_block_end_with_jump (C function)
6297 @anchor{topics/functions gcc_jit_block_end_with_jump}@anchor{b9}
6298 @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)
6300 Terminate a block by adding a jump to the given target block.
6302 This is roughly equivalent to this C code:
6311 @geindex gcc_jit_block_end_with_return (C function)
6312 @anchor{topics/functions gcc_jit_block_end_with_return}@anchor{ba}
6313 @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)
6315 Terminate a block by adding evaluation of an rvalue, returning the value.
6317 This is roughly equivalent to this C code:
6326 @geindex gcc_jit_block_end_with_void_return (C function)
6327 @anchor{topics/functions gcc_jit_block_end_with_void_return}@anchor{bb}
6328 @deffn {C Function} void gcc_jit_block_end_with_void_return (gcc_jit_block@w{ }*block, gcc_jit_location@w{ }*loc)
6330 Terminate a block by adding a valueless return, for use within a function
6331 with "void" return type.
6333 This is equivalent to this C code:
6342 @c Copyright (C) 2014 Free Software Foundation, Inc.
6343 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6345 @c This is free software: you can redistribute it and/or modify it
6346 @c under the terms of the GNU General Public License as published by
6347 @c the Free Software Foundation, either version 3 of the License, or
6348 @c (at your option) any later version.
6350 @c This program is distributed in the hope that it will be useful, but
6351 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6352 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
6353 @c General Public License for more details.
6355 @c You should have received a copy of the GNU General Public License
6356 @c along with this program. If not, see
6357 @c <http://www.gnu.org/licenses/>.
6359 @node Source Locations,Compilation results,Creating and using functions,Topic Reference
6360 @anchor{topics/locations source-locations}@anchor{bc}@anchor{topics/locations doc}@anchor{bd}
6361 @section Source Locations
6364 @geindex gcc_jit_location (C type)
6365 @anchor{topics/locations gcc_jit_location}@anchor{3b}
6366 @deffn {C Type} gcc_jit_location
6368 A @cite{gcc_jit_location} encapsulates a source code location, so that
6369 you can (optionally) associate locations in your language with
6370 statements in the JIT-compiled code, allowing the debugger to
6371 single-step through your language.
6373 @cite{gcc_jit_location} instances are optional: you can always pass NULL to
6374 any API entrypoint accepting one.
6376 You can construct them using @pxref{41,,gcc_jit_context_new_location()}.
6378 You need to enable @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} on the
6379 @pxref{8,,gcc_jit_context} for these locations to actually be usable by
6383 gcc_jit_context_set_bool_option (
6385 GCC_JIT_BOOL_OPTION_DEBUGINFO,
6392 @geindex gcc_jit_context_new_location (C function)
6393 @anchor{topics/locations gcc_jit_context_new_location}@anchor{41}
6394 @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)
6396 Create a @cite{gcc_jit_location} instance representing the given source
6405 @node Faking it,,,Source Locations
6406 @anchor{topics/locations faking-it}@anchor{be}
6407 @subsection Faking it
6410 If you don't have source code for your internal representation, but need
6411 to debug, you can generate a C-like representation of the functions in
6412 your context using @pxref{52,,gcc_jit_context_dump_to_file()}:
6415 gcc_jit_context_dump_to_file (ctxt, "/tmp/something.c",
6416 1 /* update_locations */);
6421 This will dump C-like code to the given path. If the @cite{update_locations}
6422 argument is true, this will also set up @cite{gcc_jit_location} information
6423 throughout the context, pointing at the dump file as if it were a source
6424 file, giving you @emph{something} you can step through in the debugger.
6426 @c Copyright (C) 2014 Free Software Foundation, Inc.
6427 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6429 @c This is free software: you can redistribute it and/or modify it
6430 @c under the terms of the GNU General Public License as published by
6431 @c the Free Software Foundation, either version 3 of the License, or
6432 @c (at your option) any later version.
6434 @c This program is distributed in the hope that it will be useful, but
6435 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6436 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
6437 @c General Public License for more details.
6439 @c You should have received a copy of the GNU General Public License
6440 @c along with this program. If not, see
6441 @c <http://www.gnu.org/licenses/>.
6443 @node Compilation results,,Source Locations,Topic Reference
6444 @anchor{topics/results compilation-results}@anchor{bf}@anchor{topics/results doc}@anchor{c0}
6445 @section Compilation results
6448 @geindex gcc_jit_result (C type)
6449 @anchor{topics/results gcc_jit_result}@anchor{16}
6450 @deffn {C Type} gcc_jit_result
6452 A @cite{gcc_jit_result} encapsulates the result of compiling a context,
6453 and the lifetimes of any machine code functions that are
6457 @geindex gcc_jit_context_compile (C function)
6458 @anchor{topics/results gcc_jit_context_compile}@anchor{15}
6459 @deffn {C Function} gcc_jit_result * gcc_jit_context_compile (gcc_jit_context@w{ }*ctxt)
6461 This calls into GCC and builds the code, returning a
6462 @cite{gcc_jit_result *}.
6465 @geindex gcc_jit_result_get_code (C function)
6466 @anchor{topics/results gcc_jit_result_get_code}@anchor{17}
6467 @deffn {C Function} void * gcc_jit_result_get_code (gcc_jit_result@w{ }*result, const char@w{ }*funcname)
6469 Locate a given function within the built machine code.
6471 Functions are looked up by name. For this to succeed, a function
6472 with a name matching @cite{funcname} must have been created on
6473 @cite{result}'s context (or a parent context) via a call to
6474 @pxref{11,,gcc_jit_context_new_function()} with @cite{kind}
6475 @pxref{ad,,GCC_JIT_FUNCTION_EXPORTED}:
6478 gcc_jit_context_new_function (ctxt,
6479 any_location, /* or NULL */
6480 /* Required for func to be visible to
6481 gcc_jit_result_get_code: */
6482 GCC_JIT_FUNCTION_EXPORTED,
6484 /* Must string-compare equal: */
6491 If such a function is not found (or @cite{result} or @cite{funcname} are
6492 @code{NULL}), an error message will be emitted on stderr and
6493 @code{NULL} will be returned.
6495 If the function is found, the result will need to be cast to a
6496 function pointer of the correct type before it can be called.
6498 Note that the resulting machine code becomes invalid after
6499 @pxref{39,,gcc_jit_result_release()} is called on the
6500 @cite{gcc_jit_result *}; attempting to call it after that may lead
6501 to a segmentation fault.
6504 @geindex gcc_jit_result_release (C function)
6505 @anchor{topics/results gcc_jit_result_release}@anchor{39}
6506 @deffn {C Function} void gcc_jit_result_release (gcc_jit_result@w{ }*result)
6508 Once we're done with the code, this unloads the built .so file.
6509 This cleans up the result; after calling this, it's no longer
6510 valid to use the result, or any code that was obtained by calling
6511 @pxref{17,,gcc_jit_result_get_code()} on it.
6514 @c Copyright (C) 2014 Free Software Foundation, Inc.
6515 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6517 @c This is free software: you can redistribute it and/or modify it
6518 @c under the terms of the GNU General Public License as published by
6519 @c the Free Software Foundation, either version 3 of the License, or
6520 @c (at your option) any later version.
6522 @c This program is distributed in the hope that it will be useful, but
6523 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6524 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
6525 @c General Public License for more details.
6527 @c You should have received a copy of the GNU General Public License
6528 @c along with this program. If not, see
6529 @c <http://www.gnu.org/licenses/>.
6531 @node C++ bindings for libgccjit,Internals,Topic Reference,Top
6532 @anchor{cp/index c-bindings-for-libgccjit}@anchor{c1}@anchor{cp/index doc}@anchor{c2}
6533 @chapter C++ bindings for libgccjit
6536 This document describes the C++ bindings to
6537 libgccjit@footnote{http://gcc.gnu.org/wiki/JIT}, an API for embedding GCC
6538 inside programs and libraries.
6540 The C++ bindings consist of a single header file @code{libgccjit++.h}.
6542 This is a collection of "thin" wrapper classes around the C API.
6543 Everything is an inline function, implemented in terms of the C API,
6544 so there is nothing extra to link against.
6546 Note that libgccjit is currently of "Alpha" quality;
6547 the APIs are not yet set in stone, and they shouldn't be used in
6552 @c Copyright (C) 2014 Free Software Foundation, Inc.
6553 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6555 @c This is free software: you can redistribute it and/or modify it
6556 @c under the terms of the GNU General Public License as published by
6557 @c the Free Software Foundation, either version 3 of the License, or
6558 @c (at your option) any later version.
6560 @c This program is distributed in the hope that it will be useful, but
6561 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6562 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
6563 @c General Public License for more details.
6565 @c You should have received a copy of the GNU General Public License
6566 @c along with this program. If not, see
6567 @c <http://www.gnu.org/licenses/>.
6570 * Tutorial: Tutorial<2>.
6571 * Topic Reference: Topic Reference<2>.
6575 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world"<2>.
6576 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function<2>.
6577 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables<2>.
6578 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>.
6580 Tutorial part 2: Creating a trivial machine code function
6582 * Options: Options<3>.
6583 * Full example: Full example<3>.
6585 Tutorial part 3: Loops and variables
6587 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues<2>.
6588 * Control flow: Control flow<2>.
6589 * Visualizing the control flow graph: Visualizing the control flow graph<2>.
6590 * Full example: Full example<4>.
6592 Tutorial part 4: Adding JIT-compilation to a toy interpreter
6594 * Our toy interpreter: Our toy interpreter<2>.
6595 * Compiling to machine code: Compiling to machine code<2>.
6596 * Setting things up: Setting things up<2>.
6597 * Populating the function: Populating the function<2>.
6598 * Verifying the control flow graph: Verifying the control flow graph<2>.
6599 * Compiling the context: Compiling the context<2>.
6600 * Single-stepping through the generated code: Single-stepping through the generated code<2>.
6601 * Examining the generated code: Examining the generated code<2>.
6602 * Putting it all together: Putting it all together<2>.
6603 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?<2>.
6605 Behind the curtain: How does our code get optimized?
6607 * Optimizing away stack manipulation: Optimizing away stack manipulation<2>.
6608 * Elimination of tail recursion: Elimination of tail recursion<2>.
6612 * Compilation contexts: Compilation contexts<2>.
6613 * Objects: Objects<2>.
6615 * Expressions: Expressions<2>.
6616 * Creating and using functions: Creating and using functions<2>.
6617 * Source Locations: Source Locations<2>.
6618 * Compilation results: Compilation results<2>.
6620 Compilation contexts
6622 * Lifetime-management: Lifetime-management<2>.
6623 * Thread-safety: Thread-safety<2>.
6624 * Error-handling: Error-handling<3>.
6625 * Debugging: Debugging<2>.
6626 * Options: Options<4>.
6630 * Boolean options: Boolean options<2>.
6631 * Integer options: Integer options<2>.
6635 * Standard types: Standard types<2>.
6636 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile<2>.
6637 * Structures and unions: Structures and unions<2>.
6641 * Rvalues: Rvalues<2>.
6642 * Lvalues: Lvalues<2>.
6643 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions<2>.
6647 * Simple expressions: Simple expressions<2>.
6648 * Unary Operations: Unary Operations<2>.
6649 * Binary Operations: Binary Operations<2>.
6650 * Comparisons: Comparisons<2>.
6651 * Function calls: Function calls<2>.
6652 * Type-coercion: Type-coercion<2>.
6656 * Global variables: Global variables<2>.
6658 Creating and using functions
6660 * Params: Params<2>.
6661 * Functions: Functions<2>.
6662 * Blocks: Blocks<2>.
6663 * Statements: Statements<2>.
6667 * Faking it: Faking it<2>.
6672 @node Tutorial<2>,Topic Reference<2>,,C++ bindings for libgccjit
6673 @anchor{cp/intro/index doc}@anchor{c3}@anchor{cp/intro/index tutorial}@anchor{c4}
6677 @c Copyright (C) 2014 Free Software Foundation, Inc.
6678 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6680 @c This is free software: you can redistribute it and/or modify it
6681 @c under the terms of the GNU General Public License as published by
6682 @c the Free Software Foundation, either version 3 of the License, or
6683 @c (at your option) any later version.
6685 @c This program is distributed in the hope that it will be useful, but
6686 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6687 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
6688 @c General Public License for more details.
6690 @c You should have received a copy of the GNU General Public License
6691 @c along with this program. If not, see
6692 @c <http://www.gnu.org/licenses/>.
6695 * Tutorial part 1; "Hello world": Tutorial part 1 "Hello world"<2>.
6696 * Tutorial part 2; Creating a trivial machine code function: Tutorial part 2 Creating a trivial machine code function<2>.
6697 * Tutorial part 3; Loops and variables: Tutorial part 3 Loops and variables<2>.
6698 * Tutorial part 4; Adding JIT-compilation to a toy interpreter: Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>.
6702 @node Tutorial part 1 "Hello world"<2>,Tutorial part 2 Creating a trivial machine code function<2>,,Tutorial<2>
6703 @anchor{cp/intro/tutorial01 doc}@anchor{c5}@anchor{cp/intro/tutorial01 tutorial-part-1-hello-world}@anchor{c6}
6704 @subsection Tutorial part 1: "Hello world"
6707 Before we look at the details of the API, let's look at building and
6708 running programs that use the library.
6710 Here's a toy "hello world" program that uses the library's C++ API to
6711 synthesize a call to @cite{printf} and uses it to write a message to stdout.
6713 Don't worry about the content of the program for now; we'll cover
6714 the details in later parts of this tutorial.
6719 /* Smoketest example for libgccjit.so C++ API
6720 Copyright (C) 2014 Free Software Foundation, Inc.
6722 This file is part of GCC.
6724 GCC is free software; you can redistribute it and/or modify it
6725 under the terms of the GNU General Public License as published by
6726 the Free Software Foundation; either version 3, or (at your option)
6729 GCC is distributed in the hope that it will be useful, but
6730 WITHOUT ANY WARRANTY; without even the implied warranty of
6731 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
6732 General Public License for more details.
6734 You should have received a copy of the GNU General Public License
6735 along with GCC; see the file COPYING3. If not see
6736 <http://www.gnu.org/licenses/>. */
6738 #include <libgccjit++.h>
6744 create_code (gccjit::context ctxt)
6746 /* Let's try to inject the equivalent of this C code:
6748 greet (const char *name)
6750 printf ("hello %s\n", name);
6753 gccjit::type void_type = ctxt.get_type (GCC_JIT_TYPE_VOID);
6754 gccjit::type const_char_ptr_type =
6755 ctxt.get_type (GCC_JIT_TYPE_CONST_CHAR_PTR);
6756 gccjit::param param_name =
6757 ctxt.new_param (const_char_ptr_type, "name");
6758 std::vector<gccjit::param> func_params;
6759 func_params.push_back (param_name);
6760 gccjit::function func =
6761 ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
6766 gccjit::param param_format =
6767 ctxt.new_param (const_char_ptr_type, "format");
6768 std::vector<gccjit::param> printf_params;
6769 printf_params.push_back (param_format);
6770 gccjit::function printf_func =
6771 ctxt.new_function (GCC_JIT_FUNCTION_IMPORTED,
6772 ctxt.get_type (GCC_JIT_TYPE_INT),
6776 gccjit::block block = func.new_block ();
6777 block.add_eval (ctxt.new_call (printf_func,
6778 ctxt.new_rvalue ("hello %s\n"),
6780 block.end_with_return ();
6784 main (int argc, char **argv)
6786 gccjit::context ctxt;
6787 gcc_jit_result *result;
6789 /* Get a "context" object for working with the library. */
6790 ctxt = gccjit::context::acquire ();
6792 /* Set some options on the context.
6793 Turn this on to see the code being generated, in assembler form. */
6794 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE, 0);
6796 /* Populate the context. */
6799 /* Compile the code. */
6800 result = ctxt.compile ();
6803 fprintf (stderr, "NULL result");
6809 /* Extract the generated code from "result". */
6810 typedef void (*fn_type) (const char *);
6812 (fn_type)gcc_jit_result_get_code (result, "greet");
6815 fprintf (stderr, "NULL greet");
6819 /* Now call the generated function: */
6823 gcc_jit_result_release (result);
6832 Copy the above to @cite{tut01-hello-world.cc}.
6834 Assuming you have the jit library installed, build the test program
6839 tut01-hello-world.cc \
6840 -o tut01-hello-world \
6846 You should then be able to run the built program:
6849 $ ./tut01-hello-world
6855 @c Copyright (C) 2014 Free Software Foundation, Inc.
6856 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
6858 @c This is free software: you can redistribute it and/or modify it
6859 @c under the terms of the GNU General Public License as published by
6860 @c the Free Software Foundation, either version 3 of the License, or
6861 @c (at your option) any later version.
6863 @c This program is distributed in the hope that it will be useful, but
6864 @c WITHOUT ANY WARRANTY; without even the implied warranty of
6865 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
6866 @c General Public License for more details.
6868 @c You should have received a copy of the GNU General Public License
6869 @c along with this program. If not, see
6870 @c <http://www.gnu.org/licenses/>.
6872 @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>
6873 @anchor{cp/intro/tutorial02 doc}@anchor{c7}@anchor{cp/intro/tutorial02 tutorial-part-2-creating-a-trivial-machine-code-function}@anchor{c8}
6874 @subsection Tutorial part 2: Creating a trivial machine code function
6877 Consider this C function:
6888 How can we construct this at run-time using libgccjit's C++ API?
6890 First we need to include the relevant header:
6893 #include <libgccjit++.h>
6898 All state associated with compilation is associated with a
6899 @code{gccjit::context}, which is a thin C++ wrapper around the C API's
6900 @pxref{8,,gcc_jit_context *}.
6902 Create one using @pxref{c9,,gccjit;;context;;acquire()}:
6905 gccjit::context ctxt;
6906 ctxt = gccjit::context::acquire ();
6911 The JIT library has a system of types. It is statically-typed: every
6912 expression is of a specific type, fixed at compile-time. In our example,
6913 all of the expressions are of the C @cite{int} type, so let's obtain this from
6914 the context, as a @code{gccjit::type}, using
6915 @pxref{ca,,gccjit;;context;;get_type()}:
6918 gccjit::type int_type = ctxt.get_type (GCC_JIT_TYPE_INT);
6923 @code{gccjit::type} is an example of a "contextual" object: every
6924 entity in the API is associated with a @code{gccjit::context}.
6926 Memory management is easy: all such "contextual" objects are automatically
6927 cleaned up for you when the context is released, using
6928 @pxref{cb,,gccjit;;context;;release()}:
6936 so you don't need to manually track and cleanup all objects, just the
6939 All of the C++ classes in the API are thin wrappers around pointers to
6942 The C++ class hierarchy within the @code{gccjit} namespace looks like this:
6959 One thing you can do with a @code{gccjit::object} is
6960 to ask it for a human-readable description as a @code{std::string}, using
6961 @pxref{cc,,gccjit;;object;;get_debug_string()}:
6964 printf ("obj: %s\n", obj.get_debug_string ().c_str ());
6969 giving this text on stdout:
6977 This is invaluable when debugging.
6979 Let's create the function. To do so, we first need to construct
6980 its single parameter, specifying its type and giving it a name,
6981 using @pxref{cd,,gccjit;;context;;new_param()}:
6984 gccjit::param param_i = ctxt.new_param (int_type, "i");
6989 and we can then make a vector of all of the params of the function,
6990 in this case just one:
6993 std::vector<gccjit::param> params;
6994 params.push_back (param_i);
6999 Now we can create the function, using
7000 @code{gccjit::context::new_function()}:
7003 gccjit::function func =
7004 ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
7013 To define the code within the function, we must create basic blocks
7014 containing statements.
7016 Every basic block contains a list of statements, eventually terminated
7017 by a statement that either returns, or jumps to another basic block.
7019 Our function has no control-flow, so we just need one basic block:
7022 gccjit::block block = func.new_block ();
7027 Our basic block is relatively simple: it immediately terminates by
7028 returning the value of an expression.
7030 We can build the expression using @pxref{ce,,gccjit;;context;;new_binary_op()}:
7033 gccjit::rvalue expr =
7034 ctxt.new_binary_op (
7035 GCC_JIT_BINARY_OP_MULT, int_type,
7041 A @code{gccjit::rvalue} is another example of a
7042 @code{gccjit::object} subclass. As before, we can print it with
7043 @pxref{cc,,gccjit;;object;;get_debug_string()}.
7046 printf ("expr: %s\n", expr.get_debug_string ().c_str ());
7059 Note that @code{gccjit::rvalue} provides numerous overloaded operators
7060 which can be used to dramatically reduce the amount of typing needed.
7061 We can build the above binary operation more directly with this one-liner:
7064 gccjit::rvalue expr = param_i * param_i;
7069 Creating the expression in itself doesn't do anything; we have to add
7070 this expression to a statement within the block. In this case, we use it
7071 to build a return statement, which terminates the basic block:
7074 block.end_with_return (expr);
7079 OK, we've populated the context. We can now compile it using
7080 @pxref{cf,,gccjit;;context;;compile()}:
7083 gcc_jit_result *result;
7084 result = ctxt.compile ();
7089 and get a @pxref{16,,gcc_jit_result *}.
7091 We can now use @pxref{17,,gcc_jit_result_get_code()} to look up a specific
7092 machine code routine within the result, in this case, the function we
7096 void *fn_ptr = gcc_jit_result_get_code (result, "square");
7099 fprintf (stderr, "NULL fn_ptr");
7106 We can now cast the pointer to an appropriate function pointer type, and
7110 typedef int (*fn_type) (int);
7111 fn_type square = (fn_type)fn_ptr;
7112 printf ("result: %d", square (5));
7124 * Options: Options<3>.
7125 * Full example: Full example<3>.
7129 @node Options<3>,Full example<3>,,Tutorial part 2 Creating a trivial machine code function<2>
7130 @anchor{cp/intro/tutorial02 options}@anchor{d0}
7131 @subsubsection Options
7134 To get more information on what's going on, you can set debugging flags
7135 on the context using @pxref{d1,,gccjit;;context;;set_bool_option()}.
7137 @c (I'm deliberately not mentioning
7138 @c :c:macro:`GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE` here since I think
7139 @c it's probably more of use to implementors than to users)
7141 Setting @pxref{1c,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE} will dump a
7142 C-like representation to stderr when you compile (GCC's "GIMPLE"
7146 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE, 1);
7147 result = ctxt.compile ();
7153 square (signed int i)
7165 We can see the generated machine code in assembler form (on stderr) by
7166 setting @pxref{1d,,GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE} on the context
7170 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE, 1);
7171 result = ctxt.compile ();
7180 .type square, @@function
7185 .cfi_def_cfa_offset 16
7188 .cfi_def_cfa_register 6
7192 imull -4(%rbp), %eax
7198 .size square, .-square
7199 .ident "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)"
7200 .section .note.GNU-stack,"",@@progbits
7205 By default, no optimizations are performed, the equivalent of GCC's
7206 @cite{-O0} option. We can turn things up to e.g. @cite{-O3} by calling
7207 @pxref{d2,,gccjit;;context;;set_int_option()} with
7208 @pxref{1f,,GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}:
7211 ctxt.set_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL, 3);
7221 .type square, @@function
7231 .size square, .-square
7232 .ident "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)"
7233 .section .note.GNU-stack,"",@@progbits
7238 Naturally this has only a small effect on such a trivial function.
7240 @node Full example<3>,,Options<3>,Tutorial part 2 Creating a trivial machine code function<2>
7241 @anchor{cp/intro/tutorial02 full-example}@anchor{d3}
7242 @subsubsection Full example
7245 Here's what the above looks like as a complete program:
7250 /* Usage example for libgccjit.so's C++ API
7251 Copyright (C) 2014 Free Software Foundation, Inc.
7253 This file is part of GCC.
7255 GCC is free software; you can redistribute it and/or modify it
7256 under the terms of the GNU General Public License as published by
7257 the Free Software Foundation; either version 3, or (at your option)
7260 GCC is distributed in the hope that it will be useful, but
7261 WITHOUT ANY WARRANTY; without even the implied warranty of
7262 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
7263 General Public License for more details.
7265 You should have received a copy of the GNU General Public License
7266 along with GCC; see the file COPYING3. If not see
7267 <http://www.gnu.org/licenses/>. */
7269 #include <libgccjit++.h>
7275 create_code (gccjit::context ctxt)
7277 /* Let's try to inject the equivalent of this C code:
7284 gccjit::type int_type = ctxt.get_type (GCC_JIT_TYPE_INT);
7285 gccjit::param param_i = ctxt.new_param (int_type, "i");
7286 std::vector<gccjit::param> params;
7287 params.push_back (param_i);
7288 gccjit::function func = ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
7293 gccjit::block block = func.new_block ();
7295 gccjit::rvalue expr =
7296 ctxt.new_binary_op (GCC_JIT_BINARY_OP_MULT, int_type,
7299 block.end_with_return (expr);
7303 main (int argc, char **argv)
7305 /* Get a "context" object for working with the library. */
7306 gccjit::context ctxt = gccjit::context::acquire ();
7308 /* Set some options on the context.
7309 Turn this on to see the code being generated, in assembler form. */
7310 ctxt.set_bool_option (
7311 GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
7314 /* Populate the context. */
7317 /* Compile the code. */
7318 gcc_jit_result *result = ctxt.compile ();
7320 /* We're done with the context; we can release it: */
7325 fprintf (stderr, "NULL result");
7329 /* Extract the generated code from "result". */
7330 void *fn_ptr = gcc_jit_result_get_code (result, "square");
7333 fprintf (stderr, "NULL fn_ptr");
7334 gcc_jit_result_release (result);
7338 typedef int (*fn_type) (int);
7339 fn_type square = (fn_type)fn_ptr;
7340 printf ("result: %d\n", square (5));
7342 gcc_jit_result_release (result);
7351 Building and running it:
7359 # Run the built program:
7366 @c Copyright (C) 2014 Free Software Foundation, Inc.
7367 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
7369 @c This is free software: you can redistribute it and/or modify it
7370 @c under the terms of the GNU General Public License as published by
7371 @c the Free Software Foundation, either version 3 of the License, or
7372 @c (at your option) any later version.
7374 @c This program is distributed in the hope that it will be useful, but
7375 @c WITHOUT ANY WARRANTY; without even the implied warranty of
7376 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
7377 @c General Public License for more details.
7379 @c You should have received a copy of the GNU General Public License
7380 @c along with this program. If not, see
7381 @c <http://www.gnu.org/licenses/>.
7383 @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>
7384 @anchor{cp/intro/tutorial03 tutorial-part-3-loops-and-variables}@anchor{d4}@anchor{cp/intro/tutorial03 doc}@anchor{d5}
7385 @subsection Tutorial part 3: Loops and variables
7388 Consider this C function:
7393 int loop_test (int n)
7396 for (int i = 0; i < n; i++)
7405 This example demonstrates some more features of libgccjit, with local
7406 variables and a loop.
7408 To break this down into libgccjit terms, it's usually easier to reword
7409 the @cite{for} loop as a @cite{while} loop, giving:
7414 int loop_test (int n)
7430 Here's what the final control flow graph will look like:
7437 @image{sum-of-squares1,,,image of a control flow graph,png}
7443 As before, we include the libgccjit++ header and make a
7444 @code{gccjit::context}.
7447 #include <libgccjit++.h>
7451 gccjit::context ctxt;
7452 ctxt = gccjit::context::acquire ();
7457 The function works with the C @cite{int} type.
7459 In the previous tutorial we acquired this via
7462 gccjit::type the_type = ctxt.get_type (ctxt, GCC_JIT_TYPE_INT);
7467 though we could equally well make it work on, say, @cite{double}:
7470 gccjit::type the_type = ctxt.get_type (ctxt, GCC_JIT_TYPE_DOUBLE);
7475 For integer types we can use @code{gccjit::context::get_int_type}
7476 to directly bind a specific type:
7479 gccjit::type the_type = ctxt.get_int_type <int> ();
7484 Let's build the function:
7487 gcc_jit_param n = ctxt.new_param (the_type, "n");
7488 std::vector<gccjit::param> params;
7489 params.push_back (n);
7490 gccjit::function func =
7491 ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
7500 * Expressions; lvalues and rvalues: Expressions lvalues and rvalues<2>.
7501 * Control flow: Control flow<2>.
7502 * Visualizing the control flow graph: Visualizing the control flow graph<2>.
7503 * Full example: Full example<4>.
7507 @node Expressions lvalues and rvalues<2>,Control flow<2>,,Tutorial part 3 Loops and variables<2>
7508 @anchor{cp/intro/tutorial03 expressions-lvalues-and-rvalues}@anchor{d6}
7509 @subsubsection Expressions: lvalues and rvalues
7512 The base class of expression is the @code{gccjit::rvalue},
7513 representing an expression that can be on the @emph{right}-hand side of
7514 an assignment: a value that can be computed somehow, and assigned
7515 @emph{to} a storage area (such as a variable). It has a specific
7516 @code{gccjit::type}.
7518 Anothe important class is @code{gccjit::lvalue}.
7519 A @code{gccjit::lvalue}. is something that can of the @emph{left}-hand
7520 side of an assignment: a storage area (such as a variable).
7522 In other words, every assignment can be thought of as:
7530 Note that @code{gccjit::lvalue} is a subclass of
7531 @code{gccjit::rvalue}, where in an assignment of the form:
7534 LVALUE_A = LVALUE_B;
7539 the @cite{LVALUE_B} implies reading the current value of that storage
7540 area, assigning it into the @cite{LVALUE_A}.
7542 So far the only expressions we've seen are from the previous tutorial:
7548 the multiplication @cite{i * i}:
7554 gccjit::rvalue expr =
7555 ctxt.new_binary_op (
7556 GCC_JIT_BINARY_OP_MULT, int_type,
7559 /* Alternatively, using operator-overloading: */
7560 gccjit::rvalue expr = param_i * param_i;
7565 which is a @code{gccjit::rvalue}, and
7572 the various function parameters: @cite{param_i} and @cite{param_n}, instances of
7573 @code{gccjit::param}, which is a subclass of @code{gccjit::lvalue}
7574 (and, in turn, of @code{gccjit::rvalue}):
7575 we can both read from and write to function parameters within the
7579 Our new example has a new kind of expression: we have two local
7580 variables. We create them by calling
7581 @pxref{d7,,gccjit;;function;;new_local()}, supplying a type and a name:
7585 gccjit::lvalue i = func.new_local (the_type, "i");
7586 gccjit::lvalue sum = func.new_local (the_type, "sum");
7591 These are instances of @code{gccjit::lvalue} - they can be read from
7594 Note that there is no precanned way to create @emph{and} initialize a variable
7603 Instead, having added the local to the function, we have to separately add
7604 an assignment of @cite{0} to @cite{local_i} at the beginning of the function.
7606 @node Control flow<2>,Visualizing the control flow graph<2>,Expressions lvalues and rvalues<2>,Tutorial part 3 Loops and variables<2>
7607 @anchor{cp/intro/tutorial03 control-flow}@anchor{d8}
7608 @subsubsection Control flow
7611 This function has a loop, so we need to build some basic blocks to
7612 handle the control flow. In this case, we need 4 blocks:
7618 before the loop (initializing the locals)
7621 the conditional at the top of the loop (comparing @cite{i < n})
7624 the body of the loop
7627 after the loop terminates (@cite{return sum})
7630 so we create these as @code{gccjit::block} instances within the
7631 @code{gccjit::function}:
7634 gccjit::block b_initial = func.new_block ("initial");
7635 gccjit::block b_loop_cond = func.new_block ("loop_cond");
7636 gccjit::block b_loop_body = func.new_block ("loop_body");
7637 gccjit::block b_after_loop = func.new_block ("after_loop");
7642 We now populate each block with statements.
7644 The entry block @cite{b_initial} consists of initializations followed by a jump
7645 to the conditional. We assign @cite{0} to @cite{i} and to @cite{sum}, using
7646 @pxref{d9,,gccjit;;block;;add_assignment()} to add
7647 an assignment statement, and using @pxref{da,,gccjit;;context;;zero()} to get
7648 the constant value @cite{0} for the relevant type for the right-hand side of
7653 b_initial.add_assignment (sum, ctxt.zero (the_type));
7656 b_initial.add_assignment (i, ctxt.zero (the_type));
7661 We can then terminate the entry block by jumping to the conditional:
7664 b_initial.end_with_jump (b_loop_cond);
7669 The conditional block is equivalent to the line @cite{while (i < n)} from our
7670 C example. It contains a single statement: a conditional, which jumps to
7671 one of two destination blocks depending on a boolean
7672 @code{gccjit::rvalue}, in this case the comparison of @cite{i} and @cite{n}.
7674 We could build the comparison using @pxref{db,,gccjit;;context;;new_comparison()}:
7677 gccjit::rvalue guard =
7678 ctxt.new_comparison (GCC_JIT_COMPARISON_GE,
7684 and can then use this to add @cite{b_loop_cond}'s sole statement, via
7685 @pxref{dc,,gccjit;;block;;end_with_conditional()}:
7688 b_loop_cond.end_with_conditional (guard);
7693 However @code{gccjit::rvalue} has overloaded operators for this, so we
7694 express the conditional as
7697 gccjit::rvalue guard = (i >= n);
7702 and hence write the block more concisely as:
7705 b_loop_cond.end_with_conditional (
7713 Next, we populate the body of the loop.
7715 The C statement @cite{sum += i * i;} is an assignment operation, where an
7716 lvalue is modified "in-place". We use
7717 @pxref{dd,,gccjit;;block;;add_assignment_op()} to handle these operations:
7721 b_loop_body.add_assignment_op (sum,
7722 GCC_JIT_BINARY_OP_PLUS,
7728 The @cite{i++} can be thought of as @cite{i += 1}, and can thus be handled in
7729 a similar way. We use @pxref{2f,,gcc_jit_context_one()} to get the constant
7730 value @cite{1} (for the relevant type) for the right-hand side
7735 b_loop_body.add_assignment_op (i,
7736 GCC_JIT_BINARY_OP_PLUS,
7737 ctxt.one (the_type));
7744 For numeric constants other than 0 or 1, we could use
7745 @pxref{de,,gccjit;;context;;new_rvalue()}, which has overloads
7746 for both @code{int} and @code{double}.
7750 The loop body completes by jumping back to the conditional:
7753 b_loop_body.end_with_jump (b_loop_cond);
7758 Finally, we populate the @cite{b_after_loop} block, reached when the loop
7759 conditional is false. We want to generate the equivalent of:
7767 so the block is just one statement:
7771 b_after_loop.end_with_return (sum);
7778 You can intermingle block creation with statement creation,
7779 but given that the terminator statements generally include references
7780 to other blocks, I find it's clearer to create all the blocks,
7781 @emph{then} all the statements.
7785 We've finished populating the function. As before, we can now compile it
7789 gcc_jit_result *result;
7790 result = ctxt.compile ();
7796 fprintf (stderr, "NULL result");
7800 typedef int (*loop_test_fn_type) (int);
7801 loop_test_fn_type loop_test =
7802 (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
7805 fprintf (stderr, "NULL loop_test");
7806 gcc_jit_result_release (result);
7809 printf ("result: %d", loop_test (10));
7820 @node Visualizing the control flow graph<2>,Full example<4>,Control flow<2>,Tutorial part 3 Loops and variables<2>
7821 @anchor{cp/intro/tutorial03 visualizing-the-control-flow-graph}@anchor{df}
7822 @subsubsection Visualizing the control flow graph
7825 You can see the control flow graph of a function using
7826 @pxref{e0,,gccjit;;function;;dump_to_dot()}:
7829 func.dump_to_dot ("/tmp/sum-of-squares.dot");
7834 giving a .dot file in GraphViz format.
7836 You can convert this to an image using @cite{dot}:
7839 $ dot -Tpng /tmp/sum-of-squares.dot -o /tmp/sum-of-squares.png
7844 or use a viewer (my preferred one is xdot.py; see
7845 @indicateurl{https://github.com/jrfonseca/xdot.py}; on Fedora you can
7846 install it with @cite{yum install python-xdot}):
7853 @image{sum-of-squares1,,,image of a control flow graph,png}
7859 @node Full example<4>,,Visualizing the control flow graph<2>,Tutorial part 3 Loops and variables<2>
7860 @anchor{cp/intro/tutorial03 full-example}@anchor{e1}
7861 @subsubsection Full example
7867 /* Usage example for libgccjit.so's C++ API
7868 Copyright (C) 2014 Free Software Foundation, Inc.
7870 This file is part of GCC.
7872 GCC is free software; you can redistribute it and/or modify it
7873 under the terms of the GNU General Public License as published by
7874 the Free Software Foundation; either version 3, or (at your option)
7877 GCC is distributed in the hope that it will be useful, but
7878 WITHOUT ANY WARRANTY; without even the implied warranty of
7879 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
7880 General Public License for more details.
7882 You should have received a copy of the GNU General Public License
7883 along with GCC; see the file COPYING3. If not see
7884 <http://www.gnu.org/licenses/>. */
7886 #include <libgccjit++.h>
7892 create_code (gccjit::context ctxt)
7895 Simple sum-of-squares, to test conditionals and looping
7897 int loop_test (int n)
7901 for (i = 0; i < n ; i ++)
7907 gccjit::type the_type = ctxt.get_int_type <int> ();
7908 gccjit::type return_type = the_type;
7910 gccjit::param n = ctxt.new_param (the_type, "n");
7911 std::vector<gccjit::param> params;
7912 params.push_back (n);
7913 gccjit::function func =
7914 ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
7920 gccjit::lvalue i = func.new_local (the_type, "i");
7921 gccjit::lvalue sum = func.new_local (the_type, "sum");
7923 gccjit::block b_initial = func.new_block ("initial");
7924 gccjit::block b_loop_cond = func.new_block ("loop_cond");
7925 gccjit::block b_loop_body = func.new_block ("loop_body");
7926 gccjit::block b_after_loop = func.new_block ("after_loop");
7929 b_initial.add_assignment (sum, ctxt.zero (the_type));
7932 b_initial.add_assignment (i, ctxt.zero (the_type));
7934 b_initial.end_with_jump (b_loop_cond);
7937 b_loop_cond.end_with_conditional (
7943 b_loop_body.add_assignment_op (sum,
7944 GCC_JIT_BINARY_OP_PLUS,
7948 b_loop_body.add_assignment_op (i,
7949 GCC_JIT_BINARY_OP_PLUS,
7950 ctxt.one (the_type));
7952 b_loop_body.end_with_jump (b_loop_cond);
7955 b_after_loop.end_with_return (sum);
7959 main (int argc, char **argv)
7961 gccjit::context ctxt;
7962 gcc_jit_result *result = NULL;
7964 /* Get a "context" object for working with the library. */
7965 ctxt = gccjit::context::acquire ();
7967 /* Set some options on the context.
7968 Turn this on to see the code being generated, in assembler form. */
7969 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE,
7972 /* Populate the context. */
7975 /* Compile the code. */
7976 result = ctxt.compile ();
7982 fprintf (stderr, "NULL result");
7986 /* Extract the generated code from "result". */
7987 typedef int (*loop_test_fn_type) (int);
7988 loop_test_fn_type loop_test =
7989 (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
7992 fprintf (stderr, "NULL loop_test");
7993 gcc_jit_result_release (result);
7997 /* Run the generated code. */
7998 int val = loop_test (10);
7999 printf("loop_test returned: %d\n", val);
8001 gcc_jit_result_release (result);
8010 Building and running it:
8014 tut03-sum-of-squares.cc \
8015 -o tut03-sum-of-squares \
8018 # Run the built program:
8019 $ ./tut03-sum-of-squares
8020 loop_test returned: 285
8025 @c Copyright (C) 2014 Free Software Foundation, Inc.
8026 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
8028 @c This is free software: you can redistribute it and/or modify it
8029 @c under the terms of the GNU General Public License as published by
8030 @c the Free Software Foundation, either version 3 of the License, or
8031 @c (at your option) any later version.
8033 @c This program is distributed in the hope that it will be useful, but
8034 @c WITHOUT ANY WARRANTY; without even the implied warranty of
8035 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
8036 @c General Public License for more details.
8038 @c You should have received a copy of the GNU General Public License
8039 @c along with this program. If not, see
8040 @c <http://www.gnu.org/licenses/>.
8042 @node Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>,,Tutorial part 3 Loops and variables<2>,Tutorial<2>
8043 @anchor{cp/intro/tutorial04 tutorial-part-4-adding-jit-compilation-to-a-toy-interpreter}@anchor{e2}@anchor{cp/intro/tutorial04 doc}@anchor{e3}
8044 @subsection Tutorial part 4: Adding JIT-compilation to a toy interpreter
8047 In this example we construct a "toy" interpreter, and add JIT-compilation
8051 * Our toy interpreter: Our toy interpreter<2>.
8052 * Compiling to machine code: Compiling to machine code<2>.
8053 * Setting things up: Setting things up<2>.
8054 * Populating the function: Populating the function<2>.
8055 * Verifying the control flow graph: Verifying the control flow graph<2>.
8056 * Compiling the context: Compiling the context<2>.
8057 * Single-stepping through the generated code: Single-stepping through the generated code<2>.
8058 * Examining the generated code: Examining the generated code<2>.
8059 * Putting it all together: Putting it all together<2>.
8060 * Behind the curtain; How does our code get optimized?: Behind the curtain How does our code get optimized?<2>.
8064 @node Our toy interpreter<2>,Compiling to machine code<2>,,Tutorial part 4 Adding JIT-compilation to a toy interpreter<2>
8065 @anchor{cp/intro/tutorial04 our-toy-interpreter}@anchor{e4}
8066 @subsubsection Our toy interpreter
8069 It's a stack-based interpreter, and is intended as a (very simple) example
8070 of the kind of bytecode interpreter seen in dynamic languages such as
8073 For the sake of simplicity, our toy virtual machine is very limited:
8081 The only data type is @cite{int}
8084 It can only work on one function at a time (so that the only
8085 function call that can be made is to recurse).
8088 Functions can only take one parameter.
8091 Functions have a stack of @cite{int} values.
8094 We'll implement function call within the interpreter by calling a
8095 function in our implementation, rather than implementing our own
8099 The parser is only good enough to get the examples to work.
8103 Naturally, a real interpreter would be much more complicated that this.
8105 The following operations are supported:
8108 @multitable {xxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxx}
8131 Duplicate top of stack.
8147 Swap top two elements
8164 Add the top two elements
8181 Likewise, but subtract.
8197 Likewise, but multiply.
8214 elements on the stack
8215 and push a nonzero/zero
8232 Recurse, passing the top
8250 Return the top of the
8263 PUSH_CONST @cite{arg}
8279 JUMP_ABS_IF_TRUE @cite{arg}
8283 Pop; if top of stack was
8298 Programs can be interpreted, disassembled, and compiled to machine code.
8300 The interpreter reads @code{.toy} scripts. Here's what a simple recursive
8301 factorial program looks like, the script @code{factorial.toy}.
8302 The parser ignores lines beginning with a @cite{#}.
8307 # Simple recursive factorial implementation, roughly equivalent to:
8309 # int factorial (int arg)
8313 # return arg * factorial (arg - 1)
8325 # stack: [arg, arg, 2]
8329 # stack: [arg, (arg < 2)]
8341 # stack: [arg, arg, 1]
8345 # stack: [arg, (arg - 1)
8349 # stack: [arg, factorial(arg - 1)]
8353 # stack: [arg * factorial(arg - 1)]
8363 The interpreter is a simple infinite loop with a big @code{switch} statement
8364 based on what the next opcode is:
8371 toyvm_function::interpret (int arg, FILE *trace)
8374 #define PUSH(ARG) (frame.push (ARG))
8375 #define POP(ARG) (frame.pop ())
8377 frame.frm_function = this;
8379 frame.frm_cur_depth = 0;
8387 assert (frame.frm_pc < fn_num_ops);
8388 op = &fn_ops[frame.frm_pc++];
8392 frame.dump_stack (trace);
8393 disassemble_op (op, frame.frm_pc, trace);
8396 switch (op->op_opcode)
8398 /* Ops taking no operand. */
8418 case BINARY_SUBTRACT:
8430 case BINARY_COMPARE_LT:
8438 x = interpret (x, trace);
8445 /* Ops taking an operand. */
8447 PUSH (op->op_operand);
8450 case JUMP_ABS_IF_TRUE:
8453 frame.frm_pc = op->op_operand;
8457 assert (0); /* unknown opcode */
8459 @} /* end of switch on opcode */
8460 @} /* end of while loop */
8472 @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>
8473 @anchor{cp/intro/tutorial04 compiling-to-machine-code}@anchor{e5}
8474 @subsubsection Compiling to machine code
8477 We want to generate machine code that can be cast to this type and
8478 then directly executed in-process:
8483 typedef int (*toyvm_compiled_func) (int);
8491 Our compiler isn't very sophisticated; it takes the implementation of
8492 each opcode above, and maps it directly to the operations supported by
8495 How should we handle the stack? In theory we could calculate what the
8496 stack depth will be at each opcode, and optimize away the stack
8497 manipulation "by hand". We'll see below that libgccjit is able to do
8498 this for us, so we'll implement stack manipulation
8499 in a direct way, by creating a @code{stack} array and @code{stack_depth}
8500 variables, local within the generated function, equivalent to this C code:
8504 int stack[MAX_STACK_DEPTH];
8509 We'll also have local variables @code{x} and @code{y} for use when implementing
8510 the opcodes, equivalent to this:
8519 This means our compiler has the following state:
8525 toyvm_function &toyvmfn;
8527 gccjit::context ctxt;
8529 gccjit::type int_type;
8530 gccjit::type bool_type;
8531 gccjit::type stack_type; /* int[MAX_STACK_DEPTH] */
8533 gccjit::rvalue const_one;
8535 gccjit::function fn;
8536 gccjit::param param_arg;
8537 gccjit::lvalue stack;
8538 gccjit::lvalue stack_depth;
8542 gccjit::location op_locs[MAX_OPS];
8543 gccjit::block initial_block;
8544 gccjit::block op_blocks[MAX_OPS];
8552 @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>
8553 @anchor{cp/intro/tutorial04 setting-things-up}@anchor{e6}
8554 @subsubsection Setting things up
8557 First we create our types:
8564 compilation_state::create_types ()
8567 int_type = ctxt.get_type (GCC_JIT_TYPE_INT);
8568 bool_type = ctxt.get_type (GCC_JIT_TYPE_BOOL);
8569 stack_type = ctxt.new_array_type (int_type, MAX_STACK_DEPTH);
8577 along with extracting a useful @cite{int} constant:
8582 const_one = ctxt.one (int_type);
8592 We'll implement push and pop in terms of the @code{stack} array and
8593 @code{stack_depth}. Here are helper functions for adding statements to
8594 a block, implementing pushing and popping values:
8601 compilation_state::add_push (gccjit::block block,
8602 gccjit::rvalue rvalue,
8603 gccjit::location loc)
8605 /* stack[stack_depth] = RVALUE */
8606 block.add_assignment (
8607 /* stack[stack_depth] */
8608 ctxt.new_array_access (
8615 /* "stack_depth++;". */
8616 block.add_assignment_op (
8618 GCC_JIT_BINARY_OP_PLUS,
8624 compilation_state::add_pop (gccjit::block block,
8625 gccjit::lvalue lvalue,
8626 gccjit::location loc)
8628 /* "--stack_depth;". */
8629 block.add_assignment_op (
8631 GCC_JIT_BINARY_OP_MINUS,
8635 /* "LVALUE = stack[stack_depth];". */
8636 block.add_assignment (
8638 /* stack[stack_depth] */
8639 ctxt.new_array_access (stack,
8651 We will support single-stepping through the generated code in the
8652 debugger, so we need to create @code{gccjit::location} instances, one
8653 per operation in the source code. These will reference the lines of
8654 e.g. @code{factorial.toy}.
8661 compilation_state::create_locations ()
8663 for (int pc = 0; pc < toyvmfn.fn_num_ops; pc++)
8665 toyvm_op *op = &toyvmfn.fn_ops[pc];
8667 op_locs[pc] = ctxt.new_location (toyvmfn.fn_filename,
8679 Let's create the function itself. As usual, we create its parameter
8680 first, then use the parameter to create the function:
8687 compilation_state::create_function (const char *funcname)
8689 std::vector <gccjit::param> params;
8690 param_arg = ctxt.new_param (int_type, "arg", op_locs[0]);
8691 params.push_back (param_arg);
8692 fn = ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
8704 We create the locals within the function.
8709 stack = fn.new_local (stack_type, "stack");
8710 stack_depth = fn.new_local (int_type, "stack_depth");
8711 x = fn.new_local (int_type, "x");
8712 y = fn.new_local (int_type, "y");
8720 @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>
8721 @anchor{cp/intro/tutorial04 populating-the-function}@anchor{e7}
8722 @subsubsection Populating the function
8725 There's some one-time initialization, and the API treats the first block
8726 you create as the entrypoint of the function, so we need to create that
8732 initial_block = fn.new_block ("initial");
8740 We can now create blocks for each of the operations. Most of these will
8741 be consolidated into larger blocks when the optimizer runs.
8746 for (int pc = 0; pc < toyvmfn.fn_num_ops; pc++)
8749 sprintf (buf, "instr%i", pc);
8750 op_blocks[pc] = fn.new_block (buf);
8759 Now that we have a block it can jump to when it's done, we can populate
8766 /* "stack_depth = 0;". */
8767 initial_block.add_assignment (stack_depth,
8768 ctxt.zero (int_type),
8771 /* "PUSH (arg);". */
8772 add_push (initial_block,
8776 /* ...and jump to insn 0. */
8777 initial_block.end_with_jump (op_blocks[0],
8786 We can now populate the blocks for the individual operations. We loop
8787 through them, adding instructions to their blocks:
8792 for (int pc = 0; pc < toyvmfn.fn_num_ops; pc++)
8794 gccjit::location loc = op_locs[pc];
8796 gccjit::block block = op_blocks[pc];
8797 gccjit::block next_block = (pc < toyvmfn.fn_num_ops
8802 op = &toyvmfn.fn_ops[pc];
8810 We're going to have another big @code{switch} statement for implementing
8811 the opcodes, this time for compiling them, rather than interpreting
8812 them. It's helpful to have macros for implementing push and pop, so that
8813 we can make the @code{switch} statement that's coming up look as much as
8814 possible like the one above within the interpreter:
8818 #define X_EQUALS_POP()\
8819 add_pop (block, x, loc)
8820 #define Y_EQUALS_POP()\
8821 add_pop (block, y, loc)
8822 #define PUSH_RVALUE(RVALUE)\
8823 add_push (block, (RVALUE), loc)
8836 A particularly clever implementation would have an @emph{identical}
8837 @code{switch} statement shared by the interpreter and the compiler, with
8838 some preprocessor "magic". We're not doing that here, for the sake
8843 When I first implemented this compiler, I accidentally missed an edit
8844 when copying and pasting the @code{Y_EQUALS_POP} macro, so that popping the
8845 stack into @code{y} instead erroneously assigned it to @code{x}, leaving @code{y}
8848 To track this kind of thing down, we can use
8849 @pxref{e8,,gccjit;;block;;add_comment()} to add descriptive comments
8850 to the internal representation. This is invaluable when looking through
8851 the generated IR for, say @code{factorial}:
8857 block.add_comment (opcode_names[op->op_opcode], loc);
8865 We can now write the big @code{switch} statement that implements the
8866 individual opcodes, populating the relevant block with statements:
8872 switch (op->op_opcode)
8891 ctxt.new_binary_op (
8892 GCC_JIT_BINARY_OP_PLUS,
8898 case BINARY_SUBTRACT:
8902 ctxt.new_binary_op (
8903 GCC_JIT_BINARY_OP_MINUS,
8913 ctxt.new_binary_op (
8914 GCC_JIT_BINARY_OP_MULT,
8920 case BINARY_COMPARE_LT:
8924 /* cast of bool to int */
8926 /* (x < y) as a bool */
8927 ctxt.new_comparison (
8928 GCC_JIT_COMPARISON_LT,
8948 block.end_with_return (x, loc);
8951 /* Ops taking an operand. */
8954 ctxt.new_rvalue (int_type, op->op_operand));
8957 case JUMP_ABS_IF_TRUE:
8959 block.end_with_conditional (
8961 ctxt.new_cast (x, bool_type, loc),
8962 op_blocks[op->op_operand], /* on_true */
8963 next_block, /* on_false */
8969 @} /* end of switch on opcode */
8977 Every block must be terminated, via a call to one of the
8978 @code{gccjit::block::end_with_} entrypoints. This has been done for two
8979 of the opcodes, but we need to do it for the other ones, by jumping
8985 if (op->op_opcode != JUMP_ABS_IF_TRUE
8986 && op->op_opcode != RETURN)
8987 block.end_with_jump (next_block, loc);
8995 This is analogous to simply incrementing the program counter.
8997 @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>
8998 @anchor{cp/intro/tutorial04 verifying-the-control-flow-graph}@anchor{e9}
8999 @subsubsection Verifying the control flow graph
9002 Having finished looping over the blocks, the context is complete.
9004 As before, we can verify that the control flow and statements are sane by
9005 using @pxref{e0,,gccjit;;function;;dump_to_dot()}:
9008 fn.dump_to_dot ("/tmp/factorial.dot");
9013 and viewing the result. Note how the label names, comments, and
9014 variable names show up in the dump, to make it easier to spot
9015 errors in our compiler.
9022 @image{factorial1,,,image of a control flow graph,png}
9028 @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>
9029 @anchor{cp/intro/tutorial04 compiling-the-context}@anchor{ea}
9030 @subsubsection Compiling the context
9033 Having finished looping over the blocks and populating them with
9034 statements, the context is complete.
9036 We can now compile it, and extract machine code from the result:
9041 gcc_jit_result *result = state.compile ();
9043 return (toyvm_compiled_func)gcc_jit_result_get_code (result, funcname);
9050 We can now run the result:
9055 toyvm_compiled_func code = fn->compile ();
9056 printf ("compiler result: %d\n",
9057 code (atoi (argv[2])));
9065 @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>
9066 @anchor{cp/intro/tutorial04 single-stepping-through-the-generated-code}@anchor{eb}
9067 @subsubsection Single-stepping through the generated code
9070 It's possible to debug the generated code. To do this we need to both:
9078 Set up source code locations for our statements, so that we can
9079 meaningfully step through the code. We did this above by
9080 calling @pxref{ec,,gccjit;;context;;new_location()} and using the
9084 Enable the generation of debugging information, by setting
9085 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} on the
9086 @code{gccjit::context} via
9087 @pxref{d1,,gccjit;;context;;set_bool_option()}:
9090 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DEBUGINFO, 1);
9097 Having done this, we can put a breakpoint on the generated function:
9100 $ gdb --args ./toyvm factorial.toy 10
9101 (gdb) break factorial
9102 Function "factorial" not defined.
9103 Make breakpoint pending on future shared library load? (y or [n]) y
9104 Breakpoint 1 (factorial) pending.
9106 Breakpoint 1, factorial (arg=10) at factorial.toy:14
9112 We've set up location information, which references @code{factorial.toy}.
9113 This allows us to use e.g. @code{list} to see where we are in the script:
9123 15 # stack: [arg, arg]
9131 and to step through the function, examining the data:
9137 22 BINARY_COMPARE_LT
9139 $5 = @{10, 10, 2, 0, -7152, 32767, 0, 0@}
9140 (gdb) print stack_depth
9146 You'll see that the parts of the @code{stack} array that haven't been
9147 touched yet are uninitialized.
9151 Turning on optimizations may lead to unpredictable results when
9152 stepping through the generated code: the execution may appear to
9153 "jump around" the source code. This is analogous to turning up the
9154 optimization level in a regular compiler.
9158 @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>
9159 @anchor{cp/intro/tutorial04 examining-the-generated-code}@anchor{ed}
9160 @subsubsection Examining the generated code
9163 How good is the optimized code?
9165 We can turn up optimizations, by calling
9166 @pxref{d2,,gccjit;;context;;set_int_option()} with
9167 @pxref{1f,,GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL}:
9170 ctxt.set_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL, 3);
9175 One of GCC's internal representations is called "gimple". A dump of the
9176 initial gimple representation of the code can be seen by setting:
9179 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE, 1);
9184 With optimization on and source locations displayed, this gives:
9186 @c We'll use "c" for gimple dumps
9189 factorial (signed int arg)
9191 <unnamed type> D.80;
9199 signed int stack_depth;
9200 signed int stack[8];
9206 stack[stack_depth] = arg;
9207 stack_depth = stack_depth + 1;
9211 stack_depth = stack_depth + -1;
9212 x = stack[stack_depth];
9213 stack[stack_depth] = x;
9214 stack_depth = stack_depth + 1;
9215 stack[stack_depth] = x;
9216 stack_depth = stack_depth + 1;
9220 stack[stack_depth] = 2;
9221 stack_depth = stack_depth + 1;
9229 You can see the generated machine code in assembly form via:
9232 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE, 1);
9233 result = ctxt.compile ();
9238 which shows that (on this x86_64 box) the compiler has unrolled the loop
9239 and is using MMX instructions to perform several multiplications
9248 .type factorial, @@function
9251 .file 1 "factorial.toy"
9262 leal 0(,%rcx,4), %esi
9268 movl %eax, -16(%rsp)
9270 movd -16(%rsp), %xmm0
9271 movl %edi, -16(%rsp)
9272 movl %eax, -12(%rsp)
9273 movd -16(%rsp), %xmm1
9275 movl %edx, -16(%rsp)
9276 movd -12(%rsp), %xmm4
9277 movd -16(%rsp), %xmm6
9278 punpckldq %xmm4, %xmm0
9279 movdqa .LC1(%rip), %xmm4
9280 punpckldq %xmm6, %xmm1
9281 punpcklqdq %xmm0, %xmm1
9282 movdqa .LC0(%rip), %xmm0
9284 # etc - edited for brevity
9289 This is clearly overkill for a function that will likely overflow the
9290 @code{int} type before the vectorization is worthwhile - but then again, this
9293 Turning down the optimization level to 2:
9296 ctxt.set_int_option (GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL, 2);
9301 yields this code, which is simple enough to quote in its entirety:
9308 .type factorial, @@function
9337 .size factorial, .-factorial
9338 .ident "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-%@{gcc_release@})"
9339 .section .note.GNU-stack,"",@@progbits
9344 Note that the stack pushing and popping have been eliminated, as has the
9345 recursive call (in favor of an iteration).
9347 @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>
9348 @anchor{cp/intro/tutorial04 putting-it-all-together}@anchor{ee}
9349 @subsubsection Putting it all together
9352 The complete example can be seen in the source tree at
9353 @code{gcc/jit/docs/examples/tut04-toyvm/toyvm.cc}
9355 along with a Makefile and a couple of sample .toy scripts:
9359 drwxrwxr-x. 2 david david 4096 Sep 19 17:46 .
9360 drwxrwxr-x. 3 david david 4096 Sep 19 15:26 ..
9361 -rw-rw-r--. 1 david david 615 Sep 19 12:43 factorial.toy
9362 -rw-rw-r--. 1 david david 834 Sep 19 13:08 fibonacci.toy
9363 -rw-rw-r--. 1 david david 238 Sep 19 14:22 Makefile
9364 -rw-rw-r--. 1 david david 16457 Sep 19 17:07 toyvm.cc
9367 g++ -Wall -g -o toyvm toyvm.cc -lgccjit
9369 $ ./toyvm factorial.toy 10
9370 interpreter result: 3628800
9371 compiler result: 3628800
9373 $ ./toyvm fibonacci.toy 10
9374 interpreter result: 55
9380 @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>
9381 @anchor{cp/intro/tutorial04 behind-the-curtain-how-does-our-code-get-optimized}@anchor{ef}
9382 @subsubsection Behind the curtain: How does our code get optimized?
9385 Our example is done, but you may be wondering about exactly how the
9386 compiler turned what we gave it into the machine code seen above.
9388 We can examine what the compiler is doing in detail by setting:
9391 state.ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING, 1);
9392 state.ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES, 1);
9397 This will dump detailed information about the compiler's state to a
9398 directory under @code{/tmp}, and keep it from being cleaned up.
9400 The precise names and their formats of these files is subject to change.
9401 Higher optimization levels lead to more files.
9402 Here's what I saw (edited for brevity; there were almost 200 files):
9405 intermediate files written to /tmp/libgccjit-KPQbGw
9406 $ ls /tmp/libgccjit-KPQbGw/
9408 fake.c.000i.type-inheritance
9410 fake.c.007t.omplower
9414 fake.c.014i.visibility
9415 fake.c.015i.early_local_cleanups
9422 The gimple code is converted into Static Single Assignment form,
9423 with annotations for use when generating the debuginfo:
9426 $ less /tmp/libgccjit-KPQbGw/fake.c.016t.ssa
9432 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9434 factorial (signed int arg)
9436 signed int stack[8];
9437 signed int stack_depth;
9449 # DEBUG stack_depth => stack_depth_3
9450 stack[stack_depth_3] = arg_5(D);
9451 stack_depth_7 = stack_depth_3 + 1;
9452 # DEBUG stack_depth => stack_depth_7
9453 # DEBUG instr0 => NULL
9454 # DEBUG /* DUP */ => NULL
9455 stack_depth_8 = stack_depth_7 + -1;
9456 # DEBUG stack_depth => stack_depth_8
9457 x_9 = stack[stack_depth_8];
9459 stack[stack_depth_8] = x_9;
9460 stack_depth_11 = stack_depth_8 + 1;
9461 # DEBUG stack_depth => stack_depth_11
9462 stack[stack_depth_11] = x_9;
9463 stack_depth_13 = stack_depth_11 + 1;
9464 # DEBUG stack_depth => stack_depth_13
9465 # DEBUG instr1 => NULL
9466 # DEBUG /* PUSH_CONST */ => NULL
9467 stack[stack_depth_13] = 2;
9469 /* etc; edited for brevity */
9474 We can perhaps better see the code by turning off
9475 @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} to suppress all those @code{DEBUG}
9479 $ less /tmp/libgccjit-1Hywc0/fake.c.016t.ssa
9485 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9487 factorial (signed int arg)
9489 signed int stack[8];
9490 signed int stack_depth;
9502 stack[stack_depth_3] = arg_5(D);
9503 stack_depth_7 = stack_depth_3 + 1;
9504 stack_depth_8 = stack_depth_7 + -1;
9505 x_9 = stack[stack_depth_8];
9506 stack[stack_depth_8] = x_9;
9507 stack_depth_11 = stack_depth_8 + 1;
9508 stack[stack_depth_11] = x_9;
9509 stack_depth_13 = stack_depth_11 + 1;
9510 stack[stack_depth_13] = 2;
9511 stack_depth_15 = stack_depth_13 + 1;
9512 stack_depth_16 = stack_depth_15 + -1;
9513 y_17 = stack[stack_depth_16];
9514 stack_depth_18 = stack_depth_16 + -1;
9515 x_19 = stack[stack_depth_18];
9517 _21 = (signed int) _20;
9518 stack[stack_depth_18] = _21;
9519 stack_depth_23 = stack_depth_18 + 1;
9520 stack_depth_24 = stack_depth_23 + -1;
9521 x_25 = stack[stack_depth_24];
9523 goto <bb 4> (instr9);
9525 goto <bb 3> (instr4);
9529 stack_depth_26 = stack_depth_24 + -1;
9530 x_27 = stack[stack_depth_26];
9531 stack[stack_depth_26] = x_27;
9532 stack_depth_29 = stack_depth_26 + 1;
9533 stack[stack_depth_29] = x_27;
9534 stack_depth_31 = stack_depth_29 + 1;
9535 stack[stack_depth_31] = 1;
9536 stack_depth_33 = stack_depth_31 + 1;
9537 stack_depth_34 = stack_depth_33 + -1;
9538 y_35 = stack[stack_depth_34];
9539 stack_depth_36 = stack_depth_34 + -1;
9540 x_37 = stack[stack_depth_36];
9542 stack[stack_depth_36] = _38;
9543 stack_depth_40 = stack_depth_36 + 1;
9544 stack_depth_41 = stack_depth_40 + -1;
9545 x_42 = stack[stack_depth_41];
9546 _44 = factorial (x_42);
9547 stack[stack_depth_41] = _44;
9548 stack_depth_46 = stack_depth_41 + 1;
9549 stack_depth_47 = stack_depth_46 + -1;
9550 y_48 = stack[stack_depth_47];
9551 stack_depth_49 = stack_depth_47 + -1;
9552 x_50 = stack[stack_depth_49];
9554 stack[stack_depth_49] = _51;
9555 stack_depth_53 = stack_depth_49 + 1;
9557 # stack_depth_1 = PHI <stack_depth_24(2), stack_depth_53(3)>
9560 stack_depth_54 = stack_depth_1 + -1;
9561 x_55 = stack[stack_depth_54];
9563 stack =@{v@} @{CLOBBER@};
9571 Note in the above how all the @code{gccjit::block} instances we
9572 created have been consolidated into just 3 blocks in GCC's internal
9573 representation: @code{initial}, @code{instr4} and @code{instr9}.
9576 * Optimizing away stack manipulation: Optimizing away stack manipulation<2>.
9577 * Elimination of tail recursion: Elimination of tail recursion<2>.
9581 @node Optimizing away stack manipulation<2>,Elimination of tail recursion<2>,,Behind the curtain How does our code get optimized?<2>
9582 @anchor{cp/intro/tutorial04 optimizing-away-stack-manipulation}@anchor{f0}
9583 @subsubsection Optimizing away stack manipulation
9586 Recall our simple implementation of stack operations. Let's examine
9587 how the stack operations are optimized away.
9589 After a pass of constant-propagation, the depth of the stack at each
9590 opcode can be determined at compile-time:
9593 $ less /tmp/libgccjit-1Hywc0/fake.c.021t.ccp1
9599 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9601 factorial (signed int arg)
9603 signed int stack[8];
9604 signed int stack_depth;
9614 stack[0] = arg_5(D);
9622 _21 = (signed int) _20;
9626 goto <bb 4> (instr9);
9628 goto <bb 3> (instr4);
9641 _44 = factorial (x_42);
9652 stack =@{v@} @{CLOBBER@};
9660 Note how, in the above, all those @code{stack_depth} values are now just
9661 constants: we're accessing specific stack locations at each opcode.
9663 The "esra" pass ("Early Scalar Replacement of Aggregates") breaks
9664 out our "stack" array into individual elements:
9667 $ less /tmp/libgccjit-1Hywc0/fake.c.024t.esra
9673 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9675 Created a replacement for stack offset: 0, size: 32: stack$0
9676 Created a replacement for stack offset: 32, size: 32: stack$1
9677 Created a replacement for stack offset: 64, size: 32: stack$2
9679 Symbols to be put in SSA form
9680 @{ D.89 D.90 D.91 @}
9681 Incremental SSA update started at block: 0
9682 Number of blocks in CFG: 5
9683 Number of blocks to update: 4 ( 80%)
9686 factorial (signed int arg)
9691 signed int stack[8];
9692 signed int stack_depth;
9702 stack$0_45 = arg_5(D);
9710 _21 = (signed int) _20;
9714 goto <bb 4> (instr9);
9716 goto <bb 3> (instr4);
9729 _44 = factorial (x_42);
9736 # stack$0_52 = PHI <stack$0_39(2), stack$0_1(3)>
9741 stack =@{v@} @{CLOBBER@};
9749 Hence at this point, all those pushes and pops of the stack are now
9750 simply assignments to specific temporary variables.
9752 After some copy propagation, the stack manipulation has been completely
9756 $ less /tmp/libgccjit-1Hywc0/fake.c.026t.copyprop1
9762 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9764 factorial (signed int arg)
9769 signed int stack[8];
9770 signed int stack_depth;
9780 stack$0_39 = arg_5(D);
9781 _20 = arg_5(D) <= 1;
9782 _21 = (signed int) _20;
9784 goto <bb 4> (instr9);
9786 goto <bb 3> (instr4);
9790 _38 = arg_5(D) + -1;
9791 _44 = factorial (_38);
9792 _51 = arg_5(D) * _44;
9795 # stack$0_52 = PHI <arg_5(D)(2), _51(3)>
9798 stack =@{v@} @{CLOBBER@};
9806 Later on, another pass finally eliminated @code{stack_depth} local and the
9807 unused parts of the @cite{stack`} array altogether:
9810 $ less /tmp/libgccjit-1Hywc0/fake.c.036t.release_ssa
9816 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9818 Released 44 names, 314.29%, removed 44 holes
9819 factorial (signed int arg)
9822 signed int mult_acc_1;
9826 signed int mul_tmp_10;
9827 signed int mult_acc_11;
9828 signed int mult_acc_13;
9830 # arg_9 = PHI <arg_8(D)(0)>
9831 # mult_acc_13 = PHI <1(0)>
9835 # arg_4 = PHI <arg_9(2), _7(3)>
9836 # mult_acc_1 = PHI <mult_acc_13(2), mult_acc_11(3)>
9838 _6 = (signed int) _5;
9840 goto <bb 4> (instr9);
9842 goto <bb 3> (instr4);
9847 mult_acc_11 = mult_acc_1 * arg_4;
9850 # stack$0_12 = PHI <arg_4(5)>
9853 mul_tmp_10 = mult_acc_1 * stack$0_12;
9861 @node Elimination of tail recursion<2>,,Optimizing away stack manipulation<2>,Behind the curtain How does our code get optimized?<2>
9862 @anchor{cp/intro/tutorial04 elimination-of-tail-recursion}@anchor{f1}
9863 @subsubsection Elimination of tail recursion
9866 Another significant optimization is the detection that the call to
9867 @code{factorial} is tail recursion, which can be eliminated in favor of
9871 $ less /tmp/libgccjit-1Hywc0/fake.c.030t.tailr1
9877 ;; Function factorial (factorial, funcdef_no=0, decl_uid=53, symbol_order=0)
9880 Symbols to be put in SSA form
9882 Incremental SSA update started at block: 0
9883 Number of blocks in CFG: 5
9884 Number of blocks to update: 4 ( 80%)
9887 factorial (signed int arg)
9892 signed int stack[8];
9893 signed int stack_depth;
9896 signed int mult_acc_1;
9900 signed int mul_tmp_44;
9901 signed int mult_acc_51;
9903 # arg_5 = PHI <arg_39(D)(0), _38(3)>
9904 # mult_acc_1 = PHI <1(0), mult_acc_51(3)>
9907 _21 = (signed int) _20;
9909 goto <bb 4> (instr9);
9911 goto <bb 3> (instr4);
9916 mult_acc_51 = mult_acc_1 * arg_5;
9917 goto <bb 2> (initial);
9919 # stack$0_52 = PHI <arg_5(2)>
9922 stack =@{v@} @{CLOBBER@};
9923 mul_tmp_44 = mult_acc_1 * stack$0_52;
9931 @c Copyright (C) 2014 Free Software Foundation, Inc.
9932 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
9934 @c This is free software: you can redistribute it and/or modify it
9935 @c under the terms of the GNU General Public License as published by
9936 @c the Free Software Foundation, either version 3 of the License, or
9937 @c (at your option) any later version.
9939 @c This program is distributed in the hope that it will be useful, but
9940 @c WITHOUT ANY WARRANTY; without even the implied warranty of
9941 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
9942 @c General Public License for more details.
9944 @c You should have received a copy of the GNU General Public License
9945 @c along with this program. If not, see
9946 @c <http://www.gnu.org/licenses/>.
9948 @node Topic Reference<2>,,Tutorial<2>,C++ bindings for libgccjit
9949 @anchor{cp/topics/index doc}@anchor{f2}@anchor{cp/topics/index topic-reference}@anchor{f3}
9950 @section Topic Reference
9953 @c Copyright (C) 2014 Free Software Foundation, Inc.
9954 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
9956 @c This is free software: you can redistribute it and/or modify it
9957 @c under the terms of the GNU General Public License as published by
9958 @c the Free Software Foundation, either version 3 of the License, or
9959 @c (at your option) any later version.
9961 @c This program is distributed in the hope that it will be useful, but
9962 @c WITHOUT ANY WARRANTY; without even the implied warranty of
9963 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
9964 @c General Public License for more details.
9966 @c You should have received a copy of the GNU General Public License
9967 @c along with this program. If not, see
9968 @c <http://www.gnu.org/licenses/>.
9971 * Compilation contexts: Compilation contexts<2>.
9972 * Objects: Objects<2>.
9974 * Expressions: Expressions<2>.
9975 * Creating and using functions: Creating and using functions<2>.
9976 * Source Locations: Source Locations<2>.
9977 * Compilation results: Compilation results<2>.
9979 Compilation contexts
9981 * Lifetime-management: Lifetime-management<2>.
9982 * Thread-safety: Thread-safety<2>.
9983 * Error-handling: Error-handling<3>.
9984 * Debugging: Debugging<2>.
9985 * Options: Options<4>.
9989 * Boolean options: Boolean options<2>.
9990 * Integer options: Integer options<2>.
9994 * Standard types: Standard types<2>.
9995 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile<2>.
9996 * Structures and unions: Structures and unions<2>.
10000 * Rvalues: Rvalues<2>.
10001 * Lvalues: Lvalues<2>.
10002 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions<2>.
10006 * Simple expressions: Simple expressions<2>.
10007 * Unary Operations: Unary Operations<2>.
10008 * Binary Operations: Binary Operations<2>.
10009 * Comparisons: Comparisons<2>.
10010 * Function calls: Function calls<2>.
10011 * Type-coercion: Type-coercion<2>.
10015 * Global variables: Global variables<2>.
10017 Creating and using functions
10019 * Params: Params<2>.
10020 * Functions: Functions<2>.
10021 * Blocks: Blocks<2>.
10022 * Statements: Statements<2>.
10026 * Faking it: Faking it<2>.
10031 @node Compilation contexts<2>,Objects<2>,,Topic Reference<2>
10032 @anchor{cp/topics/contexts compilation-contexts}@anchor{f4}@anchor{cp/topics/contexts doc}@anchor{f5}
10033 @subsection Compilation contexts
10036 @geindex gccjit;;context (C++ class)
10037 @anchor{cp/topics/contexts gccjit context}@anchor{f6}
10038 @deffn {C++ Class} gccjit::context
10041 The top-level of the C++ API is the @pxref{f6,,gccjit;;context} type.
10043 A @pxref{f6,,gccjit;;context} instance encapsulates the state of a
10046 You can set up options on it, and add types, functions and code.
10047 Invoking @pxref{cf,,gccjit;;context;;compile()} on it gives you a
10048 @pxref{16,,gcc_jit_result *}.
10050 It is a thin wrapper around the C API's @pxref{8,,gcc_jit_context *}.
10053 * Lifetime-management: Lifetime-management<2>.
10054 * Thread-safety: Thread-safety<2>.
10055 * Error-handling: Error-handling<3>.
10056 * Debugging: Debugging<2>.
10057 * Options: Options<4>.
10061 @node Lifetime-management<2>,Thread-safety<2>,,Compilation contexts<2>
10062 @anchor{cp/topics/contexts lifetime-management}@anchor{f7}
10063 @subsubsection Lifetime-management
10066 Contexts are the unit of lifetime-management within the API: objects
10067 have their lifetime bounded by the context they are created within, and
10068 cleanup of such objects is done for you when the context is released.
10070 @geindex gccjit;;context;;acquire (C++ function)
10071 @anchor{cp/topics/contexts gccjit context acquire}@anchor{c9}
10072 @deffn {C++ Function} gccjit::context gccjit::context::acquire ()
10074 This function acquires a new @pxref{f6,,gccjit;;context} instance,
10075 which is independent of any others that may be present within this
10079 @geindex gccjit;;context;;release (C++ function)
10080 @anchor{cp/topics/contexts gccjit context release}@anchor{cb}
10081 @deffn {C++ Function} void gccjit::context::release ()
10083 This function releases all resources associated with the given context.
10084 Both the context itself and all of its @code{gccjit::object *}
10085 instances are cleaned up. It should be called exactly once on a given
10088 It is invalid to use the context or any of its "contextual" objects
10089 after calling this.
10098 @geindex gccjit;;context;;new_child_context (C++ function)
10099 @anchor{cp/topics/contexts gccjit context new_child_context}@anchor{f8}
10100 @deffn {C++ Function} gccjit::context gccjit::context::new_child_context ()
10102 Given an existing JIT context, create a child context.
10104 The child inherits a copy of all option-settings from the parent.
10106 The child can reference objects created within the parent, but not
10109 The lifetime of the child context must be bounded by that of the
10110 parent: you should release a child context before releasing the parent
10113 If you use a function from a parent context within a child context,
10114 you have to compile the parent context before you can compile the
10115 child context, and the gccjit::result of the parent context must
10116 outlive the gccjit::result of the child context.
10118 This allows caching of shared initializations. For example, you could
10119 create types and declarations of global functions in a parent context
10120 once within a process, and then create child contexts whenever a
10121 function or loop becomes hot. Each such child context can be used for
10122 JIT-compiling just one function or loop, but can reference types
10123 and helper functions created within the parent context.
10125 Contexts can be arbitrarily nested, provided the above rules are
10126 followed, but it's probably not worth going above 2 or 3 levels, and
10127 there will likely be a performance hit for such nesting.
10130 @node Thread-safety<2>,Error-handling<3>,Lifetime-management<2>,Compilation contexts<2>
10131 @anchor{cp/topics/contexts thread-safety}@anchor{f9}
10132 @subsubsection Thread-safety
10135 Instances of @pxref{f6,,gccjit;;context} created via
10136 @pxref{c9,,gccjit;;context;;acquire()} are independent from each other:
10137 only one thread may use a given context at once, but multiple threads
10138 could each have their own contexts without needing locks.
10140 Contexts created via @pxref{f8,,gccjit;;context;;new_child_context()} are
10141 related to their parent context. They can be partitioned by their
10142 ultimate ancestor into independent "family trees". Only one thread
10143 within a process may use a given "family tree" of such contexts at once,
10144 and if you're using multiple threads you should provide your own locking
10145 around entire such context partitions.
10147 @node Error-handling<3>,Debugging<2>,Thread-safety<2>,Compilation contexts<2>
10148 @anchor{cp/topics/contexts error-handling}@anchor{fa}
10149 @subsubsection Error-handling
10152 @c FIXME: How does error-handling work for C++ API?
10154 You can only compile and get code from a context if no errors occur.
10156 In general, if an error occurs when using an API entrypoint, it returns
10157 NULL. You don't have to check everywhere for NULL results, since the
10158 API gracefully handles a NULL being passed in for any argument.
10160 Errors are printed on stderr and can be queried using
10161 @pxref{fb,,gccjit;;context;;get_first_error()}.
10163 @geindex gccjit;;context;;get_first_error (C++ function)
10164 @anchor{cp/topics/contexts gccjit context get_first_error__gccjit contextP}@anchor{fb}
10165 @deffn {C++ Function} const char* gccjit::context::get_first_error (gccjit::context* ctxt)
10167 Returns the first error message that occurred on the context.
10169 The returned string is valid for the rest of the lifetime of the
10172 If no errors occurred, this will be NULL.
10175 @node Debugging<2>,Options<4>,Error-handling<3>,Compilation contexts<2>
10176 @anchor{cp/topics/contexts debugging}@anchor{fc}
10177 @subsubsection Debugging
10180 @geindex gccjit;;context;;dump_to_file (C++ function)
10181 @anchor{cp/topics/contexts gccjit context dump_to_file__ssCR i}@anchor{fd}
10182 @deffn {C++ Function} void gccjit::context::dump_to_file (const std::string& path, int update_locations)
10184 To help with debugging: dump a C-like representation to the given path,
10185 describing what's been set up on the context.
10187 If "update_locations" is true, then also set up @pxref{fe,,gccjit;;location}
10188 information throughout the context, pointing at the dump file as if it
10189 were a source file. This may be of use in conjunction with
10190 @code{GCCJIT::BOOL_OPTION_DEBUGINFO} to allow stepping through the
10191 code in a debugger.
10194 @node Options<4>,,Debugging<2>,Compilation contexts<2>
10195 @anchor{cp/topics/contexts options}@anchor{ff}
10196 @subsubsection Options
10199 @c FIXME: gccjit::context::set_str_option doesn't seem to exist yet in the
10203 * Boolean options: Boolean options<2>.
10204 * Integer options: Integer options<2>.
10208 @node Boolean options<2>,Integer options<2>,,Options<4>
10209 @anchor{cp/topics/contexts boolean-options}@anchor{100}
10210 @subsubsection Boolean options
10213 @geindex gccjit;;context;;set_bool_option (C++ function)
10214 @anchor{cp/topics/contexts gccjit context set_bool_option__enum i}@anchor{d1}
10215 @deffn {C++ Function} void gccjit::context::set_bool_option (enum gcc_jit_bool_option, int value)
10217 Set a boolean option of the context.
10219 This is a thin wrapper around the C API
10220 @pxref{1b,,gcc_jit_context_set_bool_option()}; the options have the same
10224 @node Integer options<2>,,Boolean options<2>,Options<4>
10225 @anchor{cp/topics/contexts integer-options}@anchor{101}
10226 @subsubsection Integer options
10229 @geindex gccjit;;context;;set_int_option (C++ function)
10230 @anchor{cp/topics/contexts gccjit context set_int_option__enum i}@anchor{d2}
10231 @deffn {C++ Function} void gccjit::context::set_int_option (enum gcc_jit_int_option, int value)
10233 Set an integer option of the context.
10235 This is a thin wrapper around the C API
10236 @pxref{1e,,gcc_jit_context_set_int_option()}; the options have the same
10240 @c Copyright (C) 2014 Free Software Foundation, Inc.
10241 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
10243 @c This is free software: you can redistribute it and/or modify it
10244 @c under the terms of the GNU General Public License as published by
10245 @c the Free Software Foundation, either version 3 of the License, or
10246 @c (at your option) any later version.
10248 @c This program is distributed in the hope that it will be useful, but
10249 @c WITHOUT ANY WARRANTY; without even the implied warranty of
10250 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10251 @c General Public License for more details.
10253 @c You should have received a copy of the GNU General Public License
10254 @c along with this program. If not, see
10255 @c <http://www.gnu.org/licenses/>.
10257 @node Objects<2>,Types<2>,Compilation contexts<2>,Topic Reference<2>
10258 @anchor{cp/topics/objects objects}@anchor{102}@anchor{cp/topics/objects doc}@anchor{103}
10259 @subsection Objects
10262 @geindex gccjit;;object (C++ class)
10263 @anchor{cp/topics/objects gccjit object}@anchor{104}
10264 @deffn {C++ Class} gccjit::object
10267 Almost every entity in the API (with the exception of
10268 @pxref{f6,,gccjit;;context} and @pxref{16,,gcc_jit_result *}) is a
10269 "contextual" object, a @pxref{104,,gccjit;;object}.
10279 is associated with a @pxref{f6,,gccjit;;context}.
10282 is automatically cleaned up for you when its context is released so
10283 you don't need to manually track and cleanup all objects, just the
10288 The C++ class hierarchy within the @code{gccjit} namespace looks like this:
10305 The @pxref{104,,gccjit;;object} base class has the following operations:
10307 @geindex gccjit;;object;;get_context (C++ function)
10308 @anchor{cp/topics/objects gccjit object get_contextC}@anchor{105}
10309 @deffn {C++ Function} gccjit::context gccjit::object::get_context () const
10311 Which context is the obj within?
10314 @geindex gccjit;;object;;get_debug_string (C++ function)
10315 @anchor{cp/topics/objects gccjit object get_debug_stringC}@anchor{cc}
10316 @deffn {C++ Function} std::string gccjit::object::get_debug_string () const
10318 Generate a human-readable description for the given object.
10323 printf ("obj: %s\n", obj.get_debug_string ().c_str ());
10328 might give this text on stdout:
10331 obj: 4.0 * (float)i
10337 @c Copyright (C) 2014 Free Software Foundation, Inc.
10338 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
10340 @c This is free software: you can redistribute it and/or modify it
10341 @c under the terms of the GNU General Public License as published by
10342 @c the Free Software Foundation, either version 3 of the License, or
10343 @c (at your option) any later version.
10345 @c This program is distributed in the hope that it will be useful, but
10346 @c WITHOUT ANY WARRANTY; without even the implied warranty of
10347 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10348 @c General Public License for more details.
10350 @c You should have received a copy of the GNU General Public License
10351 @c along with this program. If not, see
10352 @c <http://www.gnu.org/licenses/>.
10354 @node Types<2>,Expressions<2>,Objects<2>,Topic Reference<2>
10355 @anchor{cp/topics/types doc}@anchor{106}@anchor{cp/topics/types types}@anchor{107}
10359 @geindex gccjit;;type (C++ class)
10360 @anchor{cp/topics/types gccjit type}@anchor{108}
10361 @deffn {C++ Class} gccjit::type
10363 gccjit::type represents a type within the library. It is a subclass
10364 of @pxref{104,,gccjit;;object}.
10367 Types can be created in several ways:
10373 fundamental types can be accessed using
10374 @pxref{ca,,gccjit;;context;;get_type()}:
10377 gccjit::type int_type = ctxt.get_type (GCC_JIT_TYPE_INT);
10382 or using the @code{gccjit::context::get_int_type} template:
10385 gccjit::type t = ctxt.get_int_type <unsigned short> ();
10390 See @pxref{b,,gcc_jit_context_get_type()} for the available types.
10393 derived types can be accessed by using functions such as
10394 @pxref{109,,gccjit;;type;;get_pointer()} and @pxref{10a,,gccjit;;type;;get_const()}:
10397 gccjit::type const_int_star = int_type.get_const ().get_pointer ();
10398 gccjit::type int_const_star = int_type.get_pointer ().get_const ();
10404 by creating structures (see below).
10408 * Standard types: Standard types<2>.
10409 * Pointers@comma{} const@comma{} and volatile: Pointers const and volatile<2>.
10410 * Structures and unions: Structures and unions<2>.
10414 @node Standard types<2>,Pointers const and volatile<2>,,Types<2>
10415 @anchor{cp/topics/types standard-types}@anchor{10b}
10416 @subsubsection Standard types
10419 @geindex gccjit;;context;;get_type (C++ function)
10420 @anchor{cp/topics/types gccjit context get_type__enum}@anchor{ca}
10421 @deffn {C++ Function} gccjit::type gccjit::context::get_type (enum gcc_jit_types)
10423 Access a specific type. This is a thin wrapper around
10424 @pxref{b,,gcc_jit_context_get_type()}; the parameter has the same meaning.
10427 @geindex gccjit;;context;;get_int_type (C++ function)
10428 @anchor{cp/topics/types gccjit context get_int_type__s i}@anchor{10c}
10429 @deffn {C++ Function} gccjit::type gccjit::context::get_int_type (size_t num_bytes, int is_signed)
10431 Access the integer type of the given size.
10434 @geindex gccjit;;context;;get_int_type<T> (C++ function)
10435 @anchor{cp/topics/types gccjit context get_int_type T}@anchor{10d}
10436 @deffn {C++ Function} gccjit::type gccjit::context::get_int_type<T> ()
10438 Access the given integer type. For example, you could map the
10439 @code{unsigned short} type into a gccjit::type via:
10442 gccjit::type t = ctxt.get_int_type <unsigned short> ();
10448 @node Pointers const and volatile<2>,Structures and unions<2>,Standard types<2>,Types<2>
10449 @anchor{cp/topics/types pointers-const-and-volatile}@anchor{10e}
10450 @subsubsection Pointers, @cite{const}, and @cite{volatile}
10453 @geindex gccjit;;type;;get_pointer (C++ function)
10454 @anchor{cp/topics/types gccjit type get_pointer}@anchor{109}
10455 @deffn {C++ Function} gccjit::type gccjit::type::get_pointer ()
10457 Given type "T", get type "T*".
10460 @c FIXME: get_const doesn't seem to exist
10462 @geindex gccjit;;type;;get_const (C++ function)
10463 @anchor{cp/topics/types gccjit type get_const}@anchor{10a}
10464 @deffn {C++ Function} gccjit::type gccjit::type::get_const ()
10466 Given type "T", get type "const T".
10469 @geindex gccjit;;type;;get_volatile (C++ function)
10470 @anchor{cp/topics/types gccjit type get_volatile}@anchor{10f}
10471 @deffn {C++ Function} gccjit::type gccjit::type::get_volatile ()
10473 Given type "T", get type "volatile T".
10476 @geindex gccjit;;context;;new_array_type (C++ function)
10477 @anchor{cp/topics/types gccjit context new_array_type__gccjit type i gccjit location}@anchor{110}
10478 @deffn {C++ Function} gccjit::type gccjit::context::new_array_type (gccjit::type element_type, int num_elements, gccjit::location loc)
10480 Given type "T", get type "T[N]" (for a constant N).
10481 Param "loc" is optional.
10484 @node Structures and unions<2>,,Pointers const and volatile<2>,Types<2>
10485 @anchor{cp/topics/types structures-and-unions}@anchor{111}
10486 @subsubsection Structures and unions
10489 @geindex gccjit;;struct_ (C++ class)
10490 @anchor{cp/topics/types gccjit struct_}@anchor{112}
10491 @deffn {C++ Class} gccjit::struct_
10494 A compound type analagous to a C @cite{struct}.
10496 @pxref{112,,gccjit;;struct_} is a subclass of @pxref{108,,gccjit;;type} (and thus
10497 of @pxref{104,,gccjit;;object} in turn).
10499 @geindex gccjit;;field (C++ class)
10500 @anchor{cp/topics/types gccjit field}@anchor{113}
10501 @deffn {C++ Class} gccjit::field
10504 A field within a @pxref{112,,gccjit;;struct_}.
10506 @pxref{113,,gccjit;;field} is a subclass of @pxref{104,,gccjit;;object}.
10508 You can model C @cite{struct} types by creating @pxref{112,,gccjit;;struct_} and
10509 @pxref{113,,gccjit;;field} instances, in either order:
10515 by creating the fields, then the structure. For example, to model:
10518 struct coord @{double x; double y; @};
10526 gccjit::field field_x = ctxt.new_field (double_type, "x");
10527 gccjit::field field_y = ctxt.new_field (double_type, "y");
10528 std::vector fields;
10529 fields.push_back (field_x);
10530 fields.push_back (field_y);
10531 gccjit::struct_ coord = ctxt.new_struct_type ("coord", fields);
10537 by creating the structure, then populating it with fields, typically
10538 to allow modelling self-referential structs such as:
10541 struct node @{ int m_hash; struct node *m_next; @};
10549 gccjit::struct_ node = ctxt.new_opaque_struct_type ("node");
10550 gccjit::type node_ptr = node.get_pointer ();
10551 gccjit::field field_hash = ctxt.new_field (int_type, "m_hash");
10552 gccjit::field field_next = ctxt.new_field (node_ptr, "m_next");
10553 std::vector fields;
10554 fields.push_back (field_hash);
10555 fields.push_back (field_next);
10556 node.set_fields (fields);
10562 @c FIXME: the above API doesn't seem to exist yet
10564 @geindex gccjit;;context;;new_field (C++ function)
10565 @anchor{cp/topics/types gccjit context new_field__gccjit type cCP gccjit location}@anchor{114}
10566 @deffn {C++ Function} gccjit::field gccjit::context::new_field (gccjit::type type, const char* name, gccjit::location loc)
10568 Construct a new field, with the given type and name.
10571 @geindex gccjit;;context;;new_struct_type (C++ function)
10572 @anchor{cp/topics/types gccjit context new_struct_type__ssCR std vector field R gccjit location}@anchor{115}
10573 @deffn {C++ Function} gccjit::struct_ gccjit::context::new_struct_type (const std::string& name, std::vector<field>& fields, gccjit::location loc)
10577 Construct a new struct type, with the given name and fields.
10581 @geindex gccjit;;context;;new_opaque_struct (C++ function)
10582 @anchor{cp/topics/types gccjit context new_opaque_struct__ssCR gccjit location}@anchor{116}
10583 @deffn {C++ Function} gccjit::struct_ gccjit::context::new_opaque_struct (const std::string& name, gccjit::location loc)
10585 Construct a new struct type, with the given name, but without
10586 specifying the fields. The fields can be omitted (in which case the
10587 size of the struct is not known), or later specified using
10588 @pxref{75,,gcc_jit_struct_set_fields()}.
10591 @c Copyright (C) 2014 Free Software Foundation, Inc.
10592 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
10594 @c This is free software: you can redistribute it and/or modify it
10595 @c under the terms of the GNU General Public License as published by
10596 @c the Free Software Foundation, either version 3 of the License, or
10597 @c (at your option) any later version.
10599 @c This program is distributed in the hope that it will be useful, but
10600 @c WITHOUT ANY WARRANTY; without even the implied warranty of
10601 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10602 @c General Public License for more details.
10604 @c You should have received a copy of the GNU General Public License
10605 @c along with this program. If not, see
10606 @c <http://www.gnu.org/licenses/>.
10608 @node Expressions<2>,Creating and using functions<2>,Types<2>,Topic Reference<2>
10609 @anchor{cp/topics/expressions expressions}@anchor{117}@anchor{cp/topics/expressions doc}@anchor{118}
10610 @subsection Expressions
10614 * Rvalues: Rvalues<2>.
10615 * Lvalues: Lvalues<2>.
10616 * Working with pointers@comma{} structs and unions: Working with pointers structs and unions<2>.
10620 * Simple expressions: Simple expressions<2>.
10621 * Unary Operations: Unary Operations<2>.
10622 * Binary Operations: Binary Operations<2>.
10623 * Comparisons: Comparisons<2>.
10624 * Function calls: Function calls<2>.
10625 * Type-coercion: Type-coercion<2>.
10629 * Global variables: Global variables<2>.
10634 @node Rvalues<2>,Lvalues<2>,,Expressions<2>
10635 @anchor{cp/topics/expressions rvalues}@anchor{119}
10636 @subsubsection Rvalues
10639 @geindex gccjit;;rvalue (C++ class)
10640 @anchor{cp/topics/expressions gccjit rvalue}@anchor{11a}
10641 @deffn {C++ Class} gccjit::rvalue
10644 A @pxref{11a,,gccjit;;rvalue} is an expression that can be computed. It is a
10645 subclass of @pxref{104,,gccjit;;object}, and is a thin wrapper around
10646 @pxref{13,,gcc_jit_rvalue *} from the C API.
10648 It can be simple, e.g.:
10656 an integer value e.g. @cite{0} or @cite{42}
10659 a string literal e.g. @cite{"Hello world"}
10662 a variable e.g. @cite{i}. These are also lvalues (see below).
10674 a unary expression e.g. @cite{!cond}
10677 a binary expression e.g. @cite{(a + b)}
10680 a function call e.g. @cite{get_distance (&player_ship@comma{} &target)}
10687 Every rvalue has an associated type, and the API will check to ensure
10688 that types match up correctly (otherwise the context will emit an error).
10690 @geindex gccjit;;rvalue;;get_type (C++ function)
10691 @anchor{cp/topics/expressions gccjit rvalue get_type}@anchor{11b}
10692 @deffn {C++ Function} gccjit::type gccjit::rvalue::get_type ()
10694 Get the type of this rvalue.
10698 * Simple expressions: Simple expressions<2>.
10699 * Unary Operations: Unary Operations<2>.
10700 * Binary Operations: Binary Operations<2>.
10701 * Comparisons: Comparisons<2>.
10702 * Function calls: Function calls<2>.
10703 * Type-coercion: Type-coercion<2>.
10707 @node Simple expressions<2>,Unary Operations<2>,,Rvalues<2>
10708 @anchor{cp/topics/expressions simple-expressions}@anchor{11c}
10709 @subsubsection Simple expressions
10712 @geindex gccjit;;context;;new_rvalue (C++ function)
10713 @anchor{cp/topics/expressions gccjit context new_rvalue__gccjit type iC}@anchor{de}
10714 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (gccjit::type numeric_type, int value) const
10716 Given a numeric type (integer or floating point), build an rvalue for
10717 the given constant @code{int} value.
10720 @geindex gccjit;;context;;zero (C++ function)
10721 @anchor{cp/topics/expressions gccjit context zero__gccjit typeC}@anchor{da}
10722 @deffn {C++ Function} gccjit::rvalue gccjit::context::zero (gccjit::type numeric_type) const
10724 Given a numeric type (integer or floating point), get the rvalue for
10725 zero. Essentially this is just a shortcut for:
10728 ctxt.new_rvalue (numeric_type, 0)
10734 @geindex gccjit;;context;;one (C++ function)
10735 @anchor{cp/topics/expressions gccjit context one__gccjit typeC}@anchor{11d}
10736 @deffn {C++ Function} gccjit::rvalue gccjit::context::one (gccjit::type numeric_type) const
10738 Given a numeric type (integer or floating point), get the rvalue for
10739 zero. Essentially this is just a shortcut for:
10742 ctxt.new_rvalue (numeric_type, 1)
10748 @geindex gccjit;;context;;new_rvalue (C++ function)
10749 @anchor{cp/topics/expressions gccjit context new_rvalue__gccjit type doubleC}@anchor{11e}
10750 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (gccjit::type numeric_type, double value) const
10752 Given a numeric type (integer or floating point), build an rvalue for
10753 the given constant value.
10756 @geindex gccjit;;context;;new_rvalue (C++ function)
10757 @anchor{cp/topics/expressions gccjit context new_rvalue__gccjit type voidPC}@anchor{11f}
10758 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (gccjit::type pointer_type, void* value) const
10760 Given a pointer type, build an rvalue for the given address.
10763 @geindex gccjit;;context;;new_rvalue (C++ function)
10764 @anchor{cp/topics/expressions gccjit context new_rvalue__ssCRC}@anchor{120}
10765 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_rvalue (const std::string& value) const
10767 Generate an rvalue of type @code{GCC_JIT_TYPE_CONST_CHAR_PTR} for
10768 the given string. This is akin to a string literal.
10771 @node Unary Operations<2>,Binary Operations<2>,Simple expressions<2>,Rvalues<2>
10772 @anchor{cp/topics/expressions unary-operations}@anchor{121}
10773 @subsubsection Unary Operations
10776 @geindex gccjit;;context;;new_unary_op (C++ function)
10777 @anchor{cp/topics/expressions gccjit context new_unary_op__enum gccjit type gccjit rvalue gccjit location}@anchor{122}
10778 @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)
10780 Build a unary operation out of an input rvalue.
10782 Parameter @code{loc} is optional.
10784 This is a thin wrapper around the C API's
10785 @pxref{80,,gcc_jit_context_new_unary_op()} and the available unary
10786 operations are documented there.
10789 There are shorter ways to spell the various specific kinds of unary
10792 @geindex gccjit;;context;;new_minus (C++ function)
10793 @anchor{cp/topics/expressions gccjit context new_minus__gccjit type gccjit rvalue gccjit location}@anchor{123}
10794 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_minus (gccjit::type result_type, gccjit::rvalue a, gccjit::location loc)
10796 Negate an arithmetic value; for example:
10799 gccjit::rvalue negpi = ctxt.new_minus (t_double, pi);
10804 builds the equivalent of this C expression:
10813 @geindex new_bitwise_negate (C++ function)
10814 @anchor{cp/topics/expressions new_bitwise_negate__gccjit type gccjit rvalue gccjit location}@anchor{124}
10815 @deffn {C++ Function} gccjit::rvalue new_bitwise_negate (gccjit::type result_type, gccjit::rvalue a, gccjit::location loc)
10817 Bitwise negation of an integer value (one's complement); for example:
10820 gccjit::rvalue mask = ctxt.new_bitwise_negate (t_int, a);
10825 builds the equivalent of this C expression:
10834 @geindex new_logical_negate (C++ function)
10835 @anchor{cp/topics/expressions new_logical_negate__gccjit type gccjit rvalue gccjit location}@anchor{125}
10836 @deffn {C++ Function} gccjit::rvalue new_logical_negate (gccjit::type result_type, gccjit::rvalue a, gccjit::location loc)
10838 Logical negation of an arithmetic or pointer value; for example:
10841 gccjit::rvalue guard = ctxt.new_logical_negate (t_bool, cond);
10846 builds the equivalent of this C expression:
10855 The most concise way to spell them is with overloaded operators:
10857 @geindex operator- (C++ function)
10858 @anchor{cp/topics/expressions sub-operator__gccjit rvalue}@anchor{126}
10859 @deffn {C++ Function} gccjit::rvalue operator- (gccjit::rvalue a)
10862 gccjit::rvalue negpi = -pi;
10868 @geindex operator~ (C++ function)
10869 @anchor{cp/topics/expressions inv-operator__gccjit rvalue}@anchor{127}
10870 @deffn {C++ Function} gccjit::rvalue operator~ (gccjit::rvalue a)
10873 gccjit::rvalue mask = ~a;
10879 @geindex operator! (C++ function)
10880 @anchor{cp/topics/expressions not-operator__gccjit rvalue}@anchor{128}
10881 @deffn {C++ Function} gccjit::rvalue operator! (gccjit::rvalue a)
10884 gccjit::rvalue guard = !cond;
10890 @node Binary Operations<2>,Comparisons<2>,Unary Operations<2>,Rvalues<2>
10891 @anchor{cp/topics/expressions binary-operations}@anchor{129}
10892 @subsubsection Binary Operations
10895 @geindex gccjit;;context;;new_binary_op (C++ function)
10896 @anchor{cp/topics/expressions gccjit context new_binary_op__enum gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{ce}
10897 @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)
10899 Build a binary operation out of two constituent rvalues.
10901 Parameter @code{loc} is optional.
10903 This is a thin wrapper around the C API's
10904 @pxref{12,,gcc_jit_context_new_binary_op()} and the available binary
10905 operations are documented there.
10908 There are shorter ways to spell the various specific kinds of binary
10911 @geindex gccjit;;context;;new_plus (C++ function)
10912 @anchor{cp/topics/expressions gccjit context new_plus__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{12a}
10913 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_plus (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10916 @geindex gccjit;;context;;new_minus (C++ function)
10917 @anchor{cp/topics/expressions gccjit context new_minus__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{12b}
10918 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_minus (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10921 @geindex gccjit;;context;;new_mult (C++ function)
10922 @anchor{cp/topics/expressions gccjit context new_mult__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{12c}
10923 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_mult (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10926 @geindex gccjit;;context;;new_divide (C++ function)
10927 @anchor{cp/topics/expressions gccjit context new_divide__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{12d}
10928 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_divide (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10931 @geindex gccjit;;context;;new_modulo (C++ function)
10932 @anchor{cp/topics/expressions gccjit context new_modulo__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{12e}
10933 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_modulo (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10936 @geindex gccjit;;context;;new_bitwise_and (C++ function)
10937 @anchor{cp/topics/expressions gccjit context new_bitwise_and__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{12f}
10938 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_bitwise_and (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10941 @geindex gccjit;;context;;new_bitwise_xor (C++ function)
10942 @anchor{cp/topics/expressions gccjit context new_bitwise_xor__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{130}
10943 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_bitwise_xor (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10946 @geindex gccjit;;context;;new_bitwise_or (C++ function)
10947 @anchor{cp/topics/expressions gccjit context new_bitwise_or__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{131}
10948 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_bitwise_or (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10951 @geindex gccjit;;context;;new_logical_and (C++ function)
10952 @anchor{cp/topics/expressions gccjit context new_logical_and__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{132}
10953 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_logical_and (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10956 @geindex gccjit;;context;;new_logical_or (C++ function)
10957 @anchor{cp/topics/expressions gccjit context new_logical_or__gccjit type gccjit rvalue gccjit rvalue gccjit location}@anchor{133}
10958 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_logical_or (gccjit::type result_type, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
10961 The most concise way to spell them is with overloaded operators:
10963 @geindex operator+ (C++ function)
10964 @anchor{cp/topics/expressions add-operator__gccjit rvalue gccjit rvalue}@anchor{134}
10965 @deffn {C++ Function} gccjit::rvalue operator+ (gccjit::rvalue a, gccjit::rvalue b)
10968 gccjit::rvalue sum = a + b;
10974 @geindex operator- (C++ function)
10975 @anchor{cp/topics/expressions sub-operator__gccjit rvalue gccjit rvalue}@anchor{135}
10976 @deffn {C++ Function} gccjit::rvalue operator- (gccjit::rvalue a, gccjit::rvalue b)
10979 gccjit::rvalue diff = a - b;
10985 @geindex operator* (C++ function)
10986 @anchor{cp/topics/expressions mul-operator__gccjit rvalue gccjit rvalue}@anchor{136}
10987 @deffn {C++ Function} gccjit::rvalue operator* (gccjit::rvalue a, gccjit::rvalue b)
10990 gccjit::rvalue prod = a * b;
10996 @geindex operator/ (C++ function)
10997 @anchor{cp/topics/expressions div-operator__gccjit rvalue gccjit rvalue}@anchor{137}
10998 @deffn {C++ Function} gccjit::rvalue operator/ (gccjit::rvalue a, gccjit::rvalue b)
11001 gccjit::rvalue result = a / b;
11007 @geindex operator% (C++ function)
11008 @anchor{cp/topics/expressions mod-operator__gccjit rvalue gccjit rvalue}@anchor{138}
11009 @deffn {C++ Function} gccjit::rvalue operator% (gccjit::rvalue a, gccjit::rvalue b)
11012 gccjit::rvalue mod = a % b;
11018 @geindex operator& (C++ function)
11019 @anchor{cp/topics/expressions and-operator__gccjit rvalue gccjit rvalue}@anchor{139}
11020 @deffn {C++ Function} gccjit::rvalue operator& (gccjit::rvalue a, gccjit::rvalue b)
11023 gccjit::rvalue x = a & b;
11029 @geindex operator^ (C++ function)
11030 @anchor{cp/topics/expressions xor-operator__gccjit rvalue gccjit rvalue}@anchor{13a}
11031 @deffn {C++ Function} gccjit::rvalue operator^ (gccjit::rvalue a, gccjit::rvalue b)
11034 gccjit::rvalue x = a ^ b;
11040 @geindex operator| (C++ function)
11041 @anchor{cp/topics/expressions or-operator__gccjit rvalue gccjit rvalue}@anchor{13b}
11042 @deffn {C++ Function} gccjit::rvalue operator| (gccjit::rvalue a, gccjit::rvalue b)
11045 gccjit::rvalue x = a | b;
11051 @geindex operator&& (C++ function)
11052 @anchor{cp/topics/expressions sand-operator__gccjit rvalue gccjit rvalue}@anchor{13c}
11053 @deffn {C++ Function} gccjit::rvalue operator&& (gccjit::rvalue a, gccjit::rvalue b)
11056 gccjit::rvalue cond = a && b;
11062 @geindex operator|| (C++ function)
11063 @anchor{cp/topics/expressions sor-operator__gccjit rvalue gccjit rvalue}@anchor{13d}
11064 @deffn {C++ Function} gccjit::rvalue operator|| (gccjit::rvalue a, gccjit::rvalue b)
11067 gccjit::rvalue cond = a || b;
11073 These can of course be combined, giving a terse way to build compound
11079 gccjit::rvalue discriminant = (b * b) - (four * a * c);
11085 @node Comparisons<2>,Function calls<2>,Binary Operations<2>,Rvalues<2>
11086 @anchor{cp/topics/expressions comparisons}@anchor{13e}
11087 @subsubsection Comparisons
11090 @geindex gccjit;;context;;new_comparison (C++ function)
11091 @anchor{cp/topics/expressions gccjit context new_comparison__enum gccjit rvalue gccjit rvalue gccjit location}@anchor{db}
11092 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_comparison (enum gcc_jit_comparison, gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11094 Build a boolean rvalue out of the comparison of two other rvalues.
11096 Parameter @code{loc} is optional.
11098 This is a thin wrapper around the C API's
11099 @pxref{2c,,gcc_jit_context_new_comparison()} and the available kinds
11100 of comparison are documented there.
11103 There are shorter ways to spell the various specific kinds of binary
11106 @geindex gccjit;;context;;new_eq (C++ function)
11107 @anchor{cp/topics/expressions gccjit context new_eq__gccjit rvalue gccjit rvalue gccjit location}@anchor{13f}
11108 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_eq (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11111 @geindex gccjit;;context;;new_ne (C++ function)
11112 @anchor{cp/topics/expressions gccjit context new_ne__gccjit rvalue gccjit rvalue gccjit location}@anchor{140}
11113 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_ne (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11116 @geindex gccjit;;context;;new_lt (C++ function)
11117 @anchor{cp/topics/expressions gccjit context new_lt__gccjit rvalue gccjit rvalue gccjit location}@anchor{141}
11118 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_lt (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11121 @geindex gccjit;;context;;new_le (C++ function)
11122 @anchor{cp/topics/expressions gccjit context new_le__gccjit rvalue gccjit rvalue gccjit location}@anchor{142}
11123 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_le (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11126 @geindex gccjit;;context;;new_gt (C++ function)
11127 @anchor{cp/topics/expressions gccjit context new_gt__gccjit rvalue gccjit rvalue gccjit location}@anchor{143}
11128 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_gt (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11131 @geindex gccjit;;context;;new_ge (C++ function)
11132 @anchor{cp/topics/expressions gccjit context new_ge__gccjit rvalue gccjit rvalue gccjit location}@anchor{144}
11133 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_ge (gccjit::rvalue a, gccjit::rvalue b, gccjit::location loc)
11136 The most concise way to spell them is with overloaded operators:
11138 @geindex operator== (C++ function)
11139 @anchor{cp/topics/expressions eq-operator__gccjit rvalue gccjit rvalue}@anchor{145}
11140 @deffn {C++ Function} gccjit::rvalue operator== (gccjit::rvalue a, gccjit::rvalue b)
11143 gccjit::rvalue cond = (a == ctxt.zero (t_int));
11149 @geindex operator!= (C++ function)
11150 @anchor{cp/topics/expressions neq-operator__gccjit rvalue gccjit rvalue}@anchor{146}
11151 @deffn {C++ Function} gccjit::rvalue operator!= (gccjit::rvalue a, gccjit::rvalue b)
11154 gccjit::rvalue cond = (i != j);
11160 @geindex operator< (C++ function)
11161 @anchor{cp/topics/expressions lt-operator__gccjit rvalue gccjit rvalue}@anchor{147}
11162 @deffn {C++ Function} gccjit::rvalue operator< (gccjit::rvalue a, gccjit::rvalue b)
11165 gccjit::rvalue cond = i < n;
11171 @geindex operator<= (C++ function)
11172 @anchor{cp/topics/expressions lte-operator__gccjit rvalue gccjit rvalue}@anchor{148}
11173 @deffn {C++ Function} gccjit::rvalue operator<= (gccjit::rvalue a, gccjit::rvalue b)
11176 gccjit::rvalue cond = i <= n;
11182 @geindex operator> (C++ function)
11183 @anchor{cp/topics/expressions gt-operator__gccjit rvalue gccjit rvalue}@anchor{149}
11184 @deffn {C++ Function} gccjit::rvalue operator> (gccjit::rvalue a, gccjit::rvalue b)
11187 gccjit::rvalue cond = (ch > limit);
11193 @geindex operator>= (C++ function)
11194 @anchor{cp/topics/expressions gte-operator__gccjit rvalue gccjit rvalue}@anchor{14a}
11195 @deffn {C++ Function} gccjit::rvalue operator>= (gccjit::rvalue a, gccjit::rvalue b)
11198 gccjit::rvalue cond = (score >= ctxt.new_rvalue (t_int, 100));
11204 @c TODO: beyond this point
11206 @node Function calls<2>,Type-coercion<2>,Comparisons<2>,Rvalues<2>
11207 @anchor{cp/topics/expressions function-calls}@anchor{14b}
11208 @subsubsection Function calls
11211 @geindex gcc_jit_context_new_call (C++ function)
11212 @anchor{cp/topics/expressions gcc_jit_context_new_call__gcc_jit_contextP gcc_jit_locationP gcc_jit_functionP i gcc_jit_rvaluePP}@anchor{14c}
11213 @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)
11215 Given a function and the given table of argument rvalues, construct a
11216 call to the function, with the result as an rvalue.
11220 @code{gccjit::context::new_call()} merely builds a
11221 @pxref{11a,,gccjit;;rvalue} i.e. an expression that can be evaluated,
11222 perhaps as part of a more complicated expression.
11223 The call @emph{won't} happen unless you add a statement to a function
11224 that evaluates the expression.
11226 For example, if you want to call a function and discard the result
11227 (or to call a function with @code{void} return type), use
11228 @pxref{14d,,gccjit;;block;;add_eval()}:
11231 /* Add "(void)printf (arg0, arg1);". */
11232 block.add_eval (ctxt.new_call (printf_func, arg0, arg1));
11240 @node Type-coercion<2>,,Function calls<2>,Rvalues<2>
11241 @anchor{cp/topics/expressions type-coercion}@anchor{14e}
11242 @subsubsection Type-coercion
11245 @geindex gccjit;;context;;new_cast (C++ function)
11246 @anchor{cp/topics/expressions gccjit context new_cast__gccjit rvalue gccjit type gccjit location}@anchor{14f}
11247 @deffn {C++ Function} gccjit::rvalue gccjit::context::new_cast (gccjit::rvalue rvalue, gccjit::type type, gccjit::location loc)
11249 Given an rvalue of T, construct another rvalue of another type.
11251 Currently only a limited set of conversions are possible:
11265 P* <-> Q*, for pointer types P and Q
11270 @node Lvalues<2>,Working with pointers structs and unions<2>,Rvalues<2>,Expressions<2>
11271 @anchor{cp/topics/expressions lvalues}@anchor{150}
11272 @subsubsection Lvalues
11275 @geindex gccjit;;lvalue (C++ class)
11276 @anchor{cp/topics/expressions gccjit lvalue}@anchor{151}
11277 @deffn {C++ Class} gccjit::lvalue
11280 An lvalue is something that can of the @emph{left}-hand side of an assignment:
11281 a storage area (such as a variable). It is a subclass of
11282 @pxref{11a,,gccjit;;rvalue}, where the rvalue is computed by reading from the
11285 It iss a thin wrapper around @pxref{24,,gcc_jit_lvalue *} from the C API.
11287 @geindex gccjit;;lvalue;;get_address (C++ function)
11288 @anchor{cp/topics/expressions gccjit lvalue get_address__gccjit location}@anchor{152}
11289 @deffn {C++ Function} gccjit::rvalue gccjit::lvalue::get_address (gccjit::location loc)
11291 Take the address of an lvalue; analogous to:
11301 Parameter "loc" is optional.
11305 * Global variables: Global variables<2>.
11309 @node Global variables<2>,,,Lvalues<2>
11310 @anchor{cp/topics/expressions global-variables}@anchor{153}
11311 @subsubsection Global variables
11314 @geindex gccjit;;context;;new_global (C++ function)
11315 @anchor{cp/topics/expressions gccjit context new_global__gccjit type cCP gccjit location}@anchor{154}
11316 @deffn {C++ Function} gccjit::lvalue gccjit::context::new_global (gccjit::type type, const char* name, gccjit::location loc)
11318 Add a new global variable of the given type and name to the context.
11321 @node Working with pointers structs and unions<2>,,Lvalues<2>,Expressions<2>
11322 @anchor{cp/topics/expressions working-with-pointers-structs-and-unions}@anchor{155}
11323 @subsubsection Working with pointers, structs and unions
11326 @geindex gccjit;;rvalue;;dereference (C++ function)
11327 @anchor{cp/topics/expressions gccjit rvalue dereference__gccjit location}@anchor{156}
11328 @deffn {C++ Function} gccjit::lvalue gccjit::rvalue::dereference (gccjit::location loc)
11330 Given an rvalue of pointer type @code{T *}, dereferencing the pointer,
11331 getting an lvalue of type @code{T}. Analogous to:
11341 Parameter "loc" is optional.
11344 If you don't need to specify the location, this can also be expressed using
11345 an overloaded operator:
11348 @deffn {C++ Function} gccjit::lvalue gccjit::rvalue::operator* ();
11351 gccjit::lvalue content = *ptr;
11357 Field access is provided separately for both lvalues and rvalues:
11359 @geindex gccjit;;lvalue;;access_field (C++ function)
11360 @anchor{cp/topics/expressions gccjit lvalue access_field__gccjit field gccjit location}@anchor{157}
11361 @deffn {C++ Function} gccjit::lvalue gccjit::lvalue::access_field (gccjit::field field, gccjit::location loc)
11363 Given an lvalue of struct or union type, access the given field,
11364 getting an lvalue of the field's type. Analogous to:
11367 (EXPR).field = ...;
11375 @geindex gccjit;;rvalue;;access_field (C++ function)
11376 @anchor{cp/topics/expressions gccjit rvalue access_field__gccjit field gccjit location}@anchor{158}
11377 @deffn {C++ Function} gccjit::rvalue gccjit::rvalue::access_field (gccjit::field field, gccjit::location loc)
11379 Given an rvalue of struct or union type, access the given field
11380 as an rvalue. Analogous to:
11391 @geindex gccjit;;rvalue;;dereference_field (C++ function)
11392 @anchor{cp/topics/expressions gccjit rvalue dereference_field__gccjit field gccjit location}@anchor{159}
11393 @deffn {C++ Function} gccjit::lvalue gccjit::rvalue::dereference_field (gccjit::field field, gccjit::location loc)
11395 Given an rvalue of pointer type @code{T *} where T is of struct or union
11396 type, access the given field as an lvalue. Analogous to:
11404 in C, itself equivalent to @code{(*EXPR).FIELD}.
11407 @geindex gccjit;;context;;new_array_access (C++ function)
11408 @anchor{cp/topics/expressions gccjit context new_array_access__gccjit rvalue gccjit rvalue gccjit location}@anchor{15a}
11409 @deffn {C++ Function} gccjit::lvalue gccjit::context::new_array_access (gccjit::rvalue ptr, gccjit::rvalue index, gccjit::location loc)
11411 Given an rvalue of pointer type @code{T *}, get at the element @cite{T} at
11412 the given index, using standard C array indexing rules i.e. each
11413 increment of @code{index} corresponds to @code{sizeof(T)} bytes.
11422 in C (or, indeed, to @code{PTR + INDEX}).
11424 Parameter "loc" is optional.
11427 For array accesses where you don't need to specify a @pxref{fe,,gccjit;;location},
11428 two overloaded operators are available:
11432 gccjit::lvalue gccjit::rvalue::operator[] (gccjit::rvalue index)
11435 gccjit::lvalue element = array[idx];
11440 gccjit::lvalue gccjit::rvalue::operator[] (int index)
11443 gccjit::lvalue element = array[0];
11449 @c Copyright (C) 2014 Free Software Foundation, Inc.
11450 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
11452 @c This is free software: you can redistribute it and/or modify it
11453 @c under the terms of the GNU General Public License as published by
11454 @c the Free Software Foundation, either version 3 of the License, or
11455 @c (at your option) any later version.
11457 @c This program is distributed in the hope that it will be useful, but
11458 @c WITHOUT ANY WARRANTY; without even the implied warranty of
11459 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11460 @c General Public License for more details.
11462 @c You should have received a copy of the GNU General Public License
11463 @c along with this program. If not, see
11464 @c <http://www.gnu.org/licenses/>.
11466 @node Creating and using functions<2>,Source Locations<2>,Expressions<2>,Topic Reference<2>
11467 @anchor{cp/topics/functions doc}@anchor{15b}@anchor{cp/topics/functions creating-and-using-functions}@anchor{15c}
11468 @subsection Creating and using functions
11472 * Params: Params<2>.
11473 * Functions: Functions<2>.
11474 * Blocks: Blocks<2>.
11475 * Statements: Statements<2>.
11479 @node Params<2>,Functions<2>,,Creating and using functions<2>
11480 @anchor{cp/topics/functions params}@anchor{15d}
11481 @subsubsection Params
11484 @geindex gccjit;;param (C++ class)
11485 @anchor{cp/topics/functions gccjit param}@anchor{15e}
11486 @deffn {C++ Class} gccjit::param
11488 A @cite{gccjit::param} represents a parameter to a function.
11491 @geindex gccjit;;context;;new_param (C++ function)
11492 @anchor{cp/topics/functions gccjit context new_param__gccjit type cCP gccjit location}@anchor{cd}
11493 @deffn {C++ Function} gccjit::param gccjit::context::new_param (gccjit::type type, const char* name, gccjit::location loc)
11495 In preparation for creating a function, create a new parameter of the
11496 given type and name.
11499 @pxref{15e,,gccjit;;param} is a subclass of @pxref{151,,gccjit;;lvalue} (and thus
11500 of @pxref{11a,,gccjit;;rvalue} and @pxref{104,,gccjit;;object}). It is a thin
11501 wrapper around the C API's @pxref{25,,gcc_jit_param *}.
11503 @node Functions<2>,Blocks<2>,Params<2>,Creating and using functions<2>
11504 @anchor{cp/topics/functions functions}@anchor{15f}
11505 @subsubsection Functions
11508 @geindex gccjit;;function (C++ class)
11509 @anchor{cp/topics/functions gccjit function}@anchor{160}
11510 @deffn {C++ Class} gccjit::function
11512 A @cite{gccjit::function} represents a function - either one that we're
11513 creating ourselves, or one that we're referencing.
11517 @deffn {C++ Function} gccjit::function gccjit::context::new_function (enum gcc_jit_function_kind, gccjit::type return_type, const char *name, std::vector<param> ¶ms, int is_variadic, gccjit::location loc) \
11519 Create a gcc_jit_function with the given name and parameters.
11521 Parameters "is_variadic" and "loc" are optional.
11523 This is a wrapper around the C API's @pxref{11,,gcc_jit_context_new_function()}.
11526 @geindex gccjit;;context;;get_builtin_function (C++ function)
11527 @anchor{cp/topics/functions gccjit context get_builtin_function__cCP}@anchor{161}
11528 @deffn {C++ Function} gccjit::function gccjit::context::get_builtin_function (const char* name)
11530 This is a wrapper around the C API's
11531 @pxref{b1,,gcc_jit_context_get_builtin_function()}.
11534 @geindex gccjit;;function;;get_param (C++ function)
11535 @anchor{cp/topics/functions gccjit function get_param__iC}@anchor{162}
11536 @deffn {C++ Function} gccjit::param gccjit::function::get_param (int index) const
11538 Get the param of the given index (0-based).
11541 @geindex gccjit;;function;;dump_to_dot (C++ function)
11542 @anchor{cp/topics/functions gccjit function dump_to_dot__cCP}@anchor{e0}
11543 @deffn {C++ Function} void gccjit::function::dump_to_dot (const char* path)
11545 Emit the function in graphviz format to the given path.
11548 @geindex gccjit;;function;;new_local (C++ function)
11549 @anchor{cp/topics/functions gccjit function new_local__gccjit type cCP gccjit location}@anchor{d7}
11550 @deffn {C++ Function} gccjit::lvalue gccjit::function::new_local (gccjit::type type, const char* name, gccjit::location loc)
11552 Create a new local variable within the function, of the given type and
11556 @node Blocks<2>,Statements<2>,Functions<2>,Creating and using functions<2>
11557 @anchor{cp/topics/functions blocks}@anchor{163}
11558 @subsubsection Blocks
11561 @geindex gccjit;;block (C++ class)
11562 @anchor{cp/topics/functions gccjit block}@anchor{164}
11563 @deffn {C++ Class} gccjit::block
11565 A @cite{gccjit::block} represents a basic block within a function i.e. a
11566 sequence of statements with a single entry point and a single exit
11569 @pxref{164,,gccjit;;block} is a subclass of @pxref{104,,gccjit;;object}.
11571 The first basic block that you create within a function will
11574 Each basic block that you create within a function must be
11575 terminated, either with a conditional, a jump, or a return.
11577 It's legal to have multiple basic blocks that return within
11581 @geindex gccjit;;function;;new_block (C++ function)
11582 @anchor{cp/topics/functions gccjit function new_block__cCP}@anchor{165}
11583 @deffn {C++ Function} gccjit::block gccjit::function::new_block (const char* name)
11585 Create a basic block of the given name. The name may be NULL, but
11586 providing meaningful names is often helpful when debugging: it may
11587 show up in dumps of the internal representation, and in error
11591 @node Statements<2>,,Blocks<2>,Creating and using functions<2>
11592 @anchor{cp/topics/functions statements}@anchor{166}
11593 @subsubsection Statements
11596 @geindex gccjit;;block;;add_eval (C++ function)
11597 @anchor{cp/topics/functions gccjit block add_eval__gccjit rvalue gccjit location}@anchor{14d}
11598 @deffn {C++ Function} void gccjit::block::add_eval (gccjit::rvalue rvalue, gccjit::location loc)
11600 Add evaluation of an rvalue, discarding the result
11601 (e.g. a function call that "returns" void).
11603 This is equivalent to this C code:
11612 @geindex gccjit;;block;;add_assignment (C++ function)
11613 @anchor{cp/topics/functions gccjit block add_assignment__gccjit lvalue gccjit rvalue gccjit location}@anchor{d9}
11614 @deffn {C++ Function} void gccjit::block::add_assignment (gccjit::lvalue lvalue, gccjit::rvalue rvalue, gccjit::location loc)
11616 Add evaluation of an rvalue, assigning the result to the given
11619 This is roughly equivalent to this C code:
11628 @geindex gccjit;;block;;add_assignment_op (C++ function)
11629 @anchor{cp/topics/functions gccjit block add_assignment_op__gccjit lvalue enum gccjit rvalue gccjit location}@anchor{dd}
11630 @deffn {C++ Function} void gccjit::block::add_assignment_op (gccjit::lvalue lvalue, enum gcc_jit_binary_op, gccjit::rvalue rvalue, gccjit::location loc)
11632 Add evaluation of an rvalue, using the result to modify an
11635 This is analogous to "+=" and friends:
11649 loop_body.add_assignment_op (
11651 GCC_JIT_BINARY_OP_PLUS,
11652 ctxt.one (int_type));
11658 @geindex gccjit;;block;;add_comment (C++ function)
11659 @anchor{cp/topics/functions gccjit block add_comment__cCP gccjit location}@anchor{e8}
11660 @deffn {C++ Function} void gccjit::block::add_comment (const char* text, gccjit::location loc)
11662 Add a no-op textual comment to the internal representation of the
11663 code. It will be optimized away, but will be visible in the dumps
11664 seen via @pxref{5b,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE}
11665 and @pxref{1c,,GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE},
11666 and thus may be of use when debugging how your project's internal
11667 representation gets converted to the libgccjit IR.
11669 Parameter "loc" is optional.
11672 @geindex gccjit;;block;;end_with_conditional (C++ function)
11673 @anchor{cp/topics/functions gccjit block end_with_conditional__gccjit rvalue gccjit block gccjit block gccjit location}@anchor{dc}
11674 @deffn {C++ Function} void gccjit::block::end_with_conditional (gccjit::rvalue boolval, gccjit::block on_true, gccjit::block on_false, gccjit::location loc)
11676 Terminate a block by adding evaluation of an rvalue, branching on the
11677 result to the appropriate successor block.
11679 This is roughly equivalent to this C code:
11690 block, boolval, on_true, and on_false must be non-NULL.
11693 @geindex gccjit;;block;;end_with_jump (C++ function)
11694 @anchor{cp/topics/functions gccjit block end_with_jump__gccjit block gccjit location}@anchor{167}
11695 @deffn {C++ Function} void gccjit::block::end_with_jump (gccjit::block target, gccjit::location loc)
11697 Terminate a block by adding a jump to the given target block.
11699 This is roughly equivalent to this C code:
11708 @geindex gccjit;;block;;end_with_return (C++ function)
11709 @anchor{cp/topics/functions gccjit block end_with_return__gccjit rvalue gccjit location}@anchor{168}
11710 @deffn {C++ Function} void gccjit::block::end_with_return (gccjit::rvalue rvalue, gccjit::location loc)
11714 Both params are optional.
11716 An rvalue must be provided for a function returning non-void, and
11717 must not be provided by a function "returning" @cite{void}.
11719 If an rvalue is provided, the block is terminated by evaluating the
11720 rvalue and returning the value.
11722 This is roughly equivalent to this C code:
11730 If an rvalue is not provided, the block is terminated by adding a
11731 valueless return, for use within a function with "void" return type.
11733 This is equivalent to this C code:
11742 @c Copyright (C) 2014 Free Software Foundation, Inc.
11743 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
11745 @c This is free software: you can redistribute it and/or modify it
11746 @c under the terms of the GNU General Public License as published by
11747 @c the Free Software Foundation, either version 3 of the License, or
11748 @c (at your option) any later version.
11750 @c This program is distributed in the hope that it will be useful, but
11751 @c WITHOUT ANY WARRANTY; without even the implied warranty of
11752 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11753 @c General Public License for more details.
11755 @c You should have received a copy of the GNU General Public License
11756 @c along with this program. If not, see
11757 @c <http://www.gnu.org/licenses/>.
11759 @node Source Locations<2>,Compilation results<2>,Creating and using functions<2>,Topic Reference<2>
11760 @anchor{cp/topics/locations source-locations}@anchor{169}@anchor{cp/topics/locations doc}@anchor{16a}
11761 @subsection Source Locations
11764 @geindex gccjit;;location (C++ class)
11765 @anchor{cp/topics/locations gccjit location}@anchor{fe}
11766 @deffn {C++ Class} gccjit::location
11768 A @cite{gccjit::location} encapsulates a source code location, so that
11769 you can (optionally) associate locations in your language with
11770 statements in the JIT-compiled code, allowing the debugger to
11771 single-step through your language.
11773 @cite{gccjit::location} instances are optional: you can always omit them
11774 from any C++ API entrypoint accepting one.
11776 You can construct them using @pxref{ec,,gccjit;;context;;new_location()}.
11778 You need to enable @pxref{42,,GCC_JIT_BOOL_OPTION_DEBUGINFO} on the
11779 @pxref{f6,,gccjit;;context} for these locations to actually be usable by
11783 ctxt.set_bool_option (GCC_JIT_BOOL_OPTION_DEBUGINFO, 1);
11789 @geindex gccjit;;context;;new_location (C++ function)
11790 @anchor{cp/topics/locations gccjit context new_location__cCP i i}@anchor{ec}
11791 @deffn {C++ Function} gccjit::location gccjit::context::new_location (const char* filename, int line, int column)
11793 Create a @cite{gccjit::location} instance representing the given source
11798 * Faking it: Faking it<2>.
11802 @node Faking it<2>,,,Source Locations<2>
11803 @anchor{cp/topics/locations faking-it}@anchor{16b}
11804 @subsubsection Faking it
11807 If you don't have source code for your internal representation, but need
11808 to debug, you can generate a C-like representation of the functions in
11809 your context using @pxref{fd,,gccjit;;context;;dump_to_file()}:
11812 ctxt.dump_to_file ("/tmp/something.c",
11813 1 /* update_locations */);
11818 This will dump C-like code to the given path. If the @cite{update_locations}
11819 argument is true, this will also set up @cite{gccjit::location} information
11820 throughout the context, pointing at the dump file as if it were a source
11821 file, giving you @emph{something} you can step through in the debugger.
11823 @c Copyright (C) 2014 Free Software Foundation, Inc.
11824 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
11826 @c This is free software: you can redistribute it and/or modify it
11827 @c under the terms of the GNU General Public License as published by
11828 @c the Free Software Foundation, either version 3 of the License, or
11829 @c (at your option) any later version.
11831 @c This program is distributed in the hope that it will be useful, but
11832 @c WITHOUT ANY WARRANTY; without even the implied warranty of
11833 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11834 @c General Public License for more details.
11836 @c You should have received a copy of the GNU General Public License
11837 @c along with this program. If not, see
11838 @c <http://www.gnu.org/licenses/>.
11840 @node Compilation results<2>,,Source Locations<2>,Topic Reference<2>
11841 @anchor{cp/topics/results compilation-results}@anchor{16c}@anchor{cp/topics/results doc}@anchor{16d}
11842 @subsection Compilation results
11845 @geindex gcc_jit_result (C++ type)
11846 @anchor{cp/topics/results gcc_jit_result}@anchor{16e}
11847 @deffn {C++ Type} gcc_jit_result
11849 A @cite{gcc_jit_result} encapsulates the result of compiling a context.
11852 @geindex gccjit;;context;;compile (C++ function)
11853 @anchor{cp/topics/results gccjit context compile}@anchor{cf}
11854 @deffn {C++ Function} @pxref{16e,,gcc_jit_result*} gccjit::context::compile ()
11856 This calls into GCC and builds the code, returning a
11857 @cite{gcc_jit_result *}.
11860 @geindex gcc_jit_result_get_code (C++ function)
11861 @anchor{cp/topics/results gcc_jit_result_get_code__gcc_jit_resultP cCP}@anchor{16f}
11862 @deffn {C++ Function} void* gcc_jit_result_get_code (gcc_jit_result* result, const char* funcname)
11864 Locate a given function within the built machine code.
11865 This will need to be cast to a function pointer of the
11866 correct type before it can be called.
11869 @geindex gcc_jit_result_release (C++ function)
11870 @anchor{cp/topics/results gcc_jit_result_release__gcc_jit_resultP}@anchor{170}
11871 @deffn {C++ Function} void gcc_jit_result_release (gcc_jit_result* result)
11873 Once we're done with the code, this unloads the built .so file.
11874 This cleans up the result; after calling this, it's no longer
11875 valid to use the result.
11878 @c Copyright (C) 2014 Free Software Foundation, Inc.
11879 @c Originally contributed by David Malcolm <dmalcolm@redhat.com>
11881 @c This is free software: you can redistribute it and/or modify it
11882 @c under the terms of the GNU General Public License as published by
11883 @c the Free Software Foundation, either version 3 of the License, or
11884 @c (at your option) any later version.
11886 @c This program is distributed in the hope that it will be useful, but
11887 @c WITHOUT ANY WARRANTY; without even the implied warranty of
11888 @c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11889 @c General Public License for more details.
11891 @c You should have received a copy of the GNU General Public License
11892 @c along with this program. If not, see
11893 @c <http://www.gnu.org/licenses/>.
11895 @node Internals,Indices and tables,C++ bindings for libgccjit,Top
11896 @anchor{internals/index internals}@anchor{171}@anchor{internals/index doc}@anchor{172}
11901 * Working on the JIT library::
11902 * Running the test suite::
11903 * Environment variables::
11904 * Overview of code structure::
11908 @node Working on the JIT library,Running the test suite,,Internals
11909 @anchor{internals/index working-on-the-jit-library}@anchor{173}
11910 @section Working on the JIT library
11913 Having checked out the source code (to "src"), you can configure and build
11914 the JIT library like this:
11919 PREFIX=$(pwd)/install
11922 --enable-host-shared \
11923 --enable-languages=jit \
11924 --disable-bootstrap \
11925 --enable-checking=release \
11927 nice make -j4 # altering the "4" to however many cores you have
11932 This should build a libgccjit.so within jit/build/gcc:
11935 [build] $ file gcc/libgccjit.so*
11936 gcc/libgccjit.so: symbolic link to `libgccjit.so.0'
11937 gcc/libgccjit.so.0: symbolic link to `libgccjit.so.0.0.1'
11938 gcc/libgccjit.so.0.0.1: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, not stripped
11943 Here's what those configuration options mean:
11945 @geindex command line option; --enable-host-shared
11946 @anchor{internals/index cmdoption--enable-host-shared}@anchor{174}
11947 @deffn {Option} --enable-host-shared
11949 Configuring with this option means that the compiler is built as
11950 position-independent code, which incurs a slight performance hit,
11951 but it necessary for a shared library.
11954 @geindex command line option; --enable-languages=jit
11955 @anchor{internals/index cmdoption--enable-languages}@anchor{175}
11956 @deffn {Option} --enable-languages=jit
11958 This specifies which frontends to build. The JIT library looks like
11959 a frontend to the rest of the code.
11962 @geindex command line option; --disable-bootstrap
11963 @anchor{internals/index cmdoption--disable-bootstrap}@anchor{176}
11964 @deffn {Option} --disable-bootstrap
11966 For hacking on the "jit" subdirectory, performing a full
11967 bootstrap can be overkill, since it's unused by a bootstrap. However,
11968 when submitting patches, you should remove this option, to ensure that
11969 the compiler can still bootstrap itself.
11972 @geindex command line option; --enable-checking=release
11973 @anchor{internals/index cmdoption--enable-checking}@anchor{177}
11974 @deffn {Option} --enable-checking=release
11976 The compile can perform extensive self-checking as it runs, useful when
11977 debugging, but slowing things down.
11979 For maximum speed, configure with @code{--enable-checking=release} to
11980 disable this self-checking.
11983 @node Running the test suite,Environment variables,Working on the JIT library,Internals
11984 @anchor{internals/index running-the-test-suite}@anchor{178}
11985 @section Running the test suite
11990 [gcc] $ make check-jit RUNTESTFLAGS="-v -v -v"
11995 A summary of the tests can then be seen in:
11998 jit/build/gcc/testsuite/jit/jit.sum
12003 and detailed logs in:
12006 jit/build/gcc/testsuite/jit/jit.log
12011 The test executables can be seen as:
12014 jit/build/gcc/testsuite/jit/*.exe
12019 which can be run independently.
12021 You can compile and run individual tests by passing "jit.exp=TESTNAME" to RUNTESTFLAGS e.g.:
12024 [gcc] $ make check-jit RUNTESTFLAGS="-v -v -v jit.exp=test-factorial.c"
12029 and once a test has been compiled, you can debug it directly:
12032 [gcc] $ PATH=.:$PATH \
12033 LD_LIBRARY_PATH=. \
12036 testsuite/jit/test-factorial.exe
12042 * Running under valgrind::
12046 @node Running under valgrind,,,Running the test suite
12047 @anchor{internals/index running-under-valgrind}@anchor{179}
12048 @subsection Running under valgrind
12051 The jit testsuite detects if RUN_UNDER_VALGRIND is present in the
12052 environment (with any value). If it is present, it runs the test client
12053 code under valgrind@footnote{http://valgrind.org},
12054 specifcally, the default
12055 memcheck@footnote{http://valgrind.org/docs/manual/mc-manual.html}
12057 --leak-check=full@footnote{http://valgrind.org/docs/manual/mc-manual.html#opt.leak-check}.
12059 It automatically parses the output from valgrind, injecting XFAIL results if
12060 any issues are found, or PASS results if the output is clean. The output
12061 is saved to @code{TESTNAME.exe.valgrind.txt}.
12063 For example, the following invocation verbosely runs the testcase
12064 @code{test-sum-of-squares.c} under valgrind, showing an issue:
12067 $ RUN_UNDER_VALGRIND= \
12069 RUNTESTFLAGS="-v -v -v jit.exp=test-sum-of-squares.c"
12071 (...verbose log contains detailed valgrind errors, if any...)
12073 === jit Summary ===
12075 # of expected passes 28
12076 # of expected failures 2
12078 $ less testsuite/jit/jit.sum
12079 (...other results...)
12080 XFAIL: jit.dg/test-sum-of-squares.c: test-sum-of-squares.exe.valgrind.txt: definitely lost: 8 bytes in 1 blocks
12081 XFAIL: jit.dg/test-sum-of-squares.c: test-sum-of-squares.exe.valgrind.txt: unsuppressed errors: 1
12082 (...other results...)
12084 $ less testsuite/jit/test-sum-of-squares.exe.valgrind.txt
12085 (...shows full valgrind report for this test case...)
12090 When running under valgrind, it's best to have configured gcc with
12091 @code{--enable-valgrind-annotations}, which automatically suppresses
12092 various known false positives.
12094 @node Environment variables,Overview of code structure,Running the test suite,Internals
12095 @anchor{internals/index environment-variables}@anchor{17a}
12096 @section Environment variables
12099 When running client code against a locally-built libgccjit, three
12100 environment variables need to be set up:
12102 @geindex environment variable; LD_LIBRARY_PATH
12103 @anchor{internals/index envvar-LD_LIBRARY_PATH}@anchor{17b}
12104 @deffn {Environment Variable} LD_LIBRARY_PATH
12108 @cite{libgccjit.so} is dynamically linked into client code, so if running
12109 against a locally-built library, @code{LD_LIBRARY_PATH} needs to be set
12110 up appropriately. The library can be found within the "gcc"
12111 subdirectory of the build tree:
12115 $ file libgccjit.so*
12116 libgccjit.so: symbolic link to `libgccjit.so.0'
12117 libgccjit.so.0: symbolic link to `libgccjit.so.0.0.1'
12118 libgccjit.so.0.0.1: ELF 64-bit LSB shared object, x86-64, version 1 (GNU/Linux), dynamically linked, not stripped
12124 @geindex environment variable; PATH
12125 @anchor{internals/index envvar-PATH}@anchor{17c}
12126 @deffn {Environment Variable} PATH
12128 The library uses a driver executable for converting from .s assembler
12129 files to .so shared libraries. Specifically, it looks for a name
12131 @code{$@{target_noncanonical@}-gcc-$@{gcc_BASEVER@}$@{exeext@}}
12132 such as @code{x86_64-unknown-linux-gnu-gcc-5.0.0}.
12134 Hence @code{PATH} needs to include a directory where the library can
12135 locate this executable.
12137 The executable is normally installed to the installation bindir
12138 (e.g. /usr/bin), but a copy is also created within the "gcc"
12139 subdirectory of the build tree for running the testsuite, and for ease
12143 @geindex environment variable; LIBRARY_PATH
12144 @anchor{internals/index envvar-LIBRARY_PATH}@anchor{17d}
12145 @deffn {Environment Variable} LIBRARY_PATH
12147 The driver executable invokes the linker, and the latter needs to locate
12148 support libraries needed by the generated code, or you will see errors
12152 ld: cannot find crtbeginS.o: No such file or directory
12153 ld: cannot find -lgcc
12154 ld: cannot find -lgcc_s
12159 Hence if running directly from a locally-built copy (without installing),
12160 @code{LIBRARY_PATH} needs to contain the "gcc" subdirectory of the build
12164 For example, to run a binary that uses the library against a non-installed
12165 build of the library in LIBGCCJIT_BUILD_DIR you need an invocation of the
12166 client code like this, to preprend the dir to each of the environment
12170 $ LD_LIBRARY_PATH=$(LIBGCCJIT_BUILD_DIR):$(LD_LIBRARY_PATH) \
12171 PATH=$(LIBGCCJIT_BUILD_DIR):$(PATH) \
12172 LIBRARY_PATH=$(LIBGCCJIT_BUILD_DIR):$(LIBRARY_PATH) \
12179 @node Overview of code structure,,Environment variables,Internals
12180 @anchor{internals/index overview-of-code-structure}@anchor{17e}
12181 @section Overview of code structure
12188 @code{libgccjit.c} implements the API entrypoints. It performs error
12189 checking, then calls into classes of the gcc::jit::recording namespace
12190 within @code{jit-recording.c} and @code{jit-recording.h}.
12193 The gcc::jit::recording classes (within @code{jit-recording.c} and
12194 @code{jit-recording.h}) record the API calls that are made:
12200 /* Indentation indicates inheritance: */
12206 class function_type;
12207 class compound_type;
12228 When the context is compiled, the gcc::jit::playback classes (within
12229 @code{jit-playback.c} and @code{jit-playback.h}) replay the API calls
12230 within langhook:parse_file:
12236 /* Indentation indicates inheritance: */
12240 class compound_type;
12257 Client Code . Generated . libgccjit.so
12259 . . JIT API . JIT "Frontend". (libbackend.a)
12260 ....................................................................................
12262 ──────────────────────────> . .
12265 . . ──> libgccjit.c .
12266 . . │ (error-checking).
12268 . . ──> jit-recording.c
12269 . . (record API calls)
12272 <─────────────────────────── . .
12275 V . . gcc_jit_context_compile .
12276 ──────────────────────────> . .
12277 . . │ start of recording::context::compile ()
12279 . . │ start of playback::context::compile ()
12280 . . │ (create tempdir) .
12282 . . │ ACQUIRE MUTEX .
12284 . . V───────────────────────> toplev::main (for now)
12286 . . . . (various code)
12289 . . . <───────────────── langhook:parse_file
12291 . . . │ (jit_langhook_parse_file)
12293 ..........................................│..................VVVVVVVVVVVVV...
12294 . . . │ . No GC in here
12295 . . . │ jit-playback.c
12296 . . . │ (playback of API calls)
12297 . . . ───────────────> creation of functions,
12298 . . . . types, expression trees
12299 . . . <──────────────── etc
12300 . . . │(handle_locations: add locations to
12301 . . . │ linemap and associate them with trees)
12303 . . . │ . No GC in here
12304 ..........................................│..................AAAAAAAAAAAAA...
12305 . . . │ for each function
12306 . . . ──> postprocess
12308 . . . ────────────> cgraph_finalize_function
12309 . . . <────────────
12312 . . . ──────────────────> (end of
12313 . . . . │ langhook_parse_file)
12315 . . . . (various code)
12318 . . . <───────────────── langhook:write_globals
12320 . . . │ (jit_langhook_write_globals)
12323 . . . ──────────────────> finalize_compilation_unit
12325 . . . . (the middle─end and backend)
12327 . . <───────────────────────────── end of toplev::main
12329 . . V───────────────────────> toplev::finalize
12330 . . . . │ (purge internal state)
12331 . . <──────────────────────── end of toplev::finalize
12333 . . │ Convert assembler to DSO ("fake.so")
12335 . . │ Load DSO (dlopen "fake.so")
12337 . . │ RELEASE MUTEX .
12339 . . │ end of playback::context::compile ()
12341 . . │ playback::context dtor
12343 . . │ Cleanup tempdir .
12344 . . │ ("fake.so" is unlinked from the
12345 . . │ filesystem at this point)
12348 . . │ end of recording::context::compile ()
12349 <─────────────────────────── . .
12351 V . . gcc_jit_result_get_code .
12352 ──────────────────────────> . .
12353 . . │ dlsym () within loaded DSO
12354 <─────────────────────────── . .
12358 ───────────────> . . .
12361 <─────────────── . . .
12365 V . . gcc_jit_result_release .
12366 ──────────────────────────> . .
12367 . . │ dlclose () the loaded DSO
12368 . . │ (code becomes uncallable)
12369 <─────────────────────────── . .
12378 Here is a high-level summary from @code{jit-common.h}:
12382 In order to allow jit objects to be usable outside of a compile
12383 whilst working with the existing structure of GCC's code the
12384 C API is implemented in terms of a gcc::jit::recording::context,
12385 which records the calls made to it.
12387 When a gcc_jit_context is compiled, the recording context creates a
12388 playback context. The playback context invokes the bulk of the GCC
12389 code, and within the "frontend" parsing hook, plays back the recorded
12390 API calls, creating GCC tree objects.
12392 So there are two parallel families of classes: those relating to
12393 recording, and those relating to playback:
12399 Visibility: recording objects are exposed back to client code,
12400 whereas playback objects are internal to the library.
12403 Lifetime: recording objects have a lifetime equal to that of the
12404 recording context that created them, whereas playback objects only
12405 exist within the frontend hook.
12408 Memory allocation: recording objects are allocated by the recording
12409 context, and automatically freed by it when the context is released,
12410 whereas playback objects are allocated within the GC heap, and
12411 garbage-collected; they can own GC-references.
12414 Integration with rest of GCC: recording objects are unrelated to the
12415 rest of GCC, whereas playback objects are wrappers around "tree"
12416 instances. Hence you can't ask a recording rvalue or lvalue what its
12417 type is, whereas you can for a playback rvalue of lvalue (since it
12418 can work with the underlying GCC tree nodes).
12421 Instancing: There can be multiple recording contexts "alive" at once
12422 (albeit it only one compiling at once), whereas there can only be one
12423 playback context alive at one time (since it interacts with the GC).
12426 Ultimately if GCC could support multiple GC heaps and contexts, and
12427 finer-grained initialization, then this recording vs playback
12428 distinction could be eliminated.
12430 During a playback, we associate objects from the recording with
12431 their counterparts during this playback. For simplicity, we store this
12432 within the recording objects, as @code{void *m_playback_obj}, casting it to
12433 the appropriate playback object subclass. For these casts to make
12434 sense, the two class hierarchies need to have the same structure.
12436 Note that the playback objects that @code{m_playback_obj} points to are
12437 GC-allocated, but the recording objects don't own references:
12438 these associations only exist within a part of the code where
12439 the GC doesn't collect, and are set back to NULL before the GC can
12443 @node Indices and tables,Index,Internals,Top
12444 @anchor{index indices-and-tables}@anchor{17f}
12445 @unnumbered Indices and tables
12463 @c The Sphinx C domain appears to lack explicit support for enum values,
12464 @c so I've been using :c:macro: for them.
12466 @c See http://sphinx-doc.org/domains.html#the-c-domain
12468 @node Index,,Indices and tables,Top