1 .. Copyright (C) 2014-2022 Free Software Foundation, Inc.
2 Originally contributed by David Malcolm <dmalcolm@redhat.com>
4 This is free software: you can redistribute it and/or modify it
5 under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful, but
10 WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see
16 <https://www.gnu.org/licenses/>.
18 .. default-domain:: cpp
20 Tutorial part 3: Loops and variables
21 ------------------------------------
22 Consider this C function:
29 for (int i = 0; i < n; i++)
34 This example demonstrates some more features of libgccjit, with local
37 To break this down into libgccjit terms, it's usually easier to reword
38 the `for` loop as a `while` loop, giving:
54 Here's what the final control flow graph will look like:
56 .. figure:: ../../intro/sum-of-squares.png
57 :alt: image of a control flow graph
59 As before, we include the libgccjit++ header and make a
60 :type:`gccjit::context`.
64 #include <libgccjit++.h>
69 ctxt = gccjit::context::acquire ();
71 The function works with the C `int` type.
73 In the previous tutorial we acquired this via
77 gccjit::type the_type = ctxt.get_type (ctxt, GCC_JIT_TYPE_INT);
79 though we could equally well make it work on, say, `double`:
83 gccjit::type the_type = ctxt.get_type (ctxt, GCC_JIT_TYPE_DOUBLE);
85 For integer types we can use :func:`gccjit::context::get_int_type<T>`
86 to directly bind a specific type:
90 gccjit::type the_type = ctxt.get_int_type <int> ();
92 Let's build the function:
96 gcc_jit_param n = ctxt.new_param (the_type, "n");
97 std::vector<gccjit::param> params;
99 gccjit::function func =
100 ctxt.new_function (GCC_JIT_FUNCTION_EXPORTED,
105 Expressions: lvalues and rvalues
106 ********************************
108 The base class of expression is the :type:`gccjit::rvalue`,
109 representing an expression that can be on the *right*-hand side of
110 an assignment: a value that can be computed somehow, and assigned
111 *to* a storage area (such as a variable). It has a specific
112 :type:`gccjit::type`.
114 Anothe important class is :type:`gccjit::lvalue`.
115 A :type:`gccjit::lvalue`. is something that can of the *left*-hand
116 side of an assignment: a storage area (such as a variable).
118 In other words, every assignment can be thought of as:
124 Note that :type:`gccjit::lvalue` is a subclass of
125 :type:`gccjit::rvalue`, where in an assignment of the form:
131 the `LVALUE_B` implies reading the current value of that storage
132 area, assigning it into the `LVALUE_A`.
134 So far the only expressions we've seen are from the previous tutorial:
136 1. the multiplication `i * i`:
140 gccjit::rvalue expr =
142 GCC_JIT_BINARY_OP_MULT, int_type,
145 /* Alternatively, using operator-overloading: */
146 gccjit::rvalue expr = param_i * param_i;
148 which is a :type:`gccjit::rvalue`, and
150 2. the various function parameters: `param_i` and `param_n`, instances of
151 :type:`gccjit::param`, which is a subclass of :type:`gccjit::lvalue`
152 (and, in turn, of :type:`gccjit::rvalue`):
153 we can both read from and write to function parameters within the
156 Our new example has a new kind of expression: we have two local
157 variables. We create them by calling
158 :func:`gccjit::function::new_local`, supplying a type and a name:
163 gccjit::lvalue i = func.new_local (the_type, "i");
164 gccjit::lvalue sum = func.new_local (the_type, "sum");
166 These are instances of :type:`gccjit::lvalue` - they can be read from
169 Note that there is no precanned way to create *and* initialize a variable
176 Instead, having added the local to the function, we have to separately add
177 an assignment of `0` to `local_i` at the beginning of the function.
182 This function has a loop, so we need to build some basic blocks to
183 handle the control flow. In this case, we need 4 blocks:
185 1. before the loop (initializing the locals)
186 2. the conditional at the top of the loop (comparing `i < n`)
187 3. the body of the loop
188 4. after the loop terminates (`return sum`)
190 so we create these as :type:`gccjit::block` instances within the
191 :type:`gccjit::function`:
195 gccjit::block b_initial = func.new_block ("initial");
196 gccjit::block b_loop_cond = func.new_block ("loop_cond");
197 gccjit::block b_loop_body = func.new_block ("loop_body");
198 gccjit::block b_after_loop = func.new_block ("after_loop");
200 We now populate each block with statements.
202 The entry block `b_initial` consists of initializations followed by a jump
203 to the conditional. We assign `0` to `i` and to `sum`, using
204 :func:`gccjit::block::add_assignment` to add
205 an assignment statement, and using :func:`gccjit::context::zero` to get
206 the constant value `0` for the relevant type for the right-hand side of
212 b_initial.add_assignment (sum, ctxt.zero (the_type));
215 b_initial.add_assignment (i, ctxt.zero (the_type));
217 We can then terminate the entry block by jumping to the conditional:
221 b_initial.end_with_jump (b_loop_cond);
223 The conditional block is equivalent to the line `while (i < n)` from our
224 C example. It contains a single statement: a conditional, which jumps to
225 one of two destination blocks depending on a boolean
226 :type:`gccjit::rvalue`, in this case the comparison of `i` and `n`.
228 We could build the comparison using :func:`gccjit::context::new_comparison`:
232 gccjit::rvalue guard =
233 ctxt.new_comparison (GCC_JIT_COMPARISON_GE,
236 and can then use this to add `b_loop_cond`'s sole statement, via
237 :func:`gccjit::block::end_with_conditional`:
241 b_loop_cond.end_with_conditional (guard,
242 b_after_loop, // on_true
243 b_loop_body); // on_false
245 However :type:`gccjit::rvalue` has overloaded operators for this, so we
246 express the conditional as
250 gccjit::rvalue guard = (i >= n);
252 and hence we can write the block more concisely as:
256 b_loop_cond.end_with_conditional (
258 b_after_loop, // on_true
259 b_loop_body); // on_false
261 Next, we populate the body of the loop.
263 The C statement `sum += i * i;` is an assignment operation, where an
264 lvalue is modified "in-place". We use
265 :func:`gccjit::block::add_assignment_op` to handle these operations:
270 b_loop_body.add_assignment_op (sum,
271 GCC_JIT_BINARY_OP_PLUS,
274 The `i++` can be thought of as `i += 1`, and can thus be handled in
275 a similar way. We use :c:func:`gcc_jit_context_one` to get the constant
276 value `1` (for the relevant type) for the right-hand side
282 b_loop_body.add_assignment_op (i,
283 GCC_JIT_BINARY_OP_PLUS,
284 ctxt.one (the_type));
288 For numeric constants other than 0 or 1, we could use
289 :func:`gccjit::context::new_rvalue`, which has overloads
290 for both ``int`` and ``double``.
292 The loop body completes by jumping back to the conditional:
296 b_loop_body.end_with_jump (b_loop_cond);
298 Finally, we populate the `b_after_loop` block, reached when the loop
299 conditional is false. We want to generate the equivalent of:
305 so the block is just one statement:
310 b_after_loop.end_with_return (sum);
314 You can intermingle block creation with statement creation,
315 but given that the terminator statements generally include references
316 to other blocks, I find it's clearer to create all the blocks,
317 *then* all the statements.
319 We've finished populating the function. As before, we can now compile it
324 gcc_jit_result *result;
325 result = ctxt.compile ();
331 fprintf (stderr, "NULL result");
335 typedef int (*loop_test_fn_type) (int);
336 loop_test_fn_type loop_test =
337 (loop_test_fn_type)gcc_jit_result_get_code (result, "loop_test");
340 fprintf (stderr, "NULL loop_test");
341 gcc_jit_result_release (result);
344 printf ("result: %d", loop_test (10));
351 Visualizing the control flow graph
352 **********************************
354 You can see the control flow graph of a function using
355 :func:`gccjit::function::dump_to_dot`:
359 func.dump_to_dot ("/tmp/sum-of-squares.dot");
361 giving a .dot file in GraphViz format.
363 You can convert this to an image using `dot`:
367 $ dot -Tpng /tmp/sum-of-squares.dot -o /tmp/sum-of-squares.png
369 or use a viewer (my preferred one is xdot.py; see
370 https://github.com/jrfonseca/xdot.py; on Fedora you can
371 install it with `yum install python-xdot`):
373 .. figure:: ../../intro/sum-of-squares.png
374 :alt: image of a control flow graph
379 .. literalinclude:: ../../examples/tut03-sum-of-squares.cc
383 Building and running it:
385 .. code-block:: console
388 tut03-sum-of-squares.cc \
389 -o tut03-sum-of-squares \
392 # Run the built program:
393 $ ./tut03-sum-of-squares
394 loop_test returned: 285