1 /* Usage example for libgccjit.so's C++ API
2 Copyright (C) 2014-2021 Free Software Foundation, Inc.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
11 GCC is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 #include <libgccjit++.h>
26 create_code (gccjit::context ctxt
)
29 Simple sum-of-squares, to test conditionals and looping
35 for (i = 0; i < n ; i ++)
41 gccjit::type the_type
= ctxt
.get_int_type
<int> ();
42 gccjit::type return_type
= the_type
;
44 gccjit::param n
= ctxt
.new_param (the_type
, "n");
45 std::vector
<gccjit::param
> params
;
47 gccjit::function func
=
48 ctxt
.new_function (GCC_JIT_FUNCTION_EXPORTED
,
54 gccjit::lvalue i
= func
.new_local (the_type
, "i");
55 gccjit::lvalue sum
= func
.new_local (the_type
, "sum");
57 gccjit::block b_initial
= func
.new_block ("initial");
58 gccjit::block b_loop_cond
= func
.new_block ("loop_cond");
59 gccjit::block b_loop_body
= func
.new_block ("loop_body");
60 gccjit::block b_after_loop
= func
.new_block ("after_loop");
63 b_initial
.add_assignment (sum
, ctxt
.zero (the_type
));
66 b_initial
.add_assignment (i
, ctxt
.zero (the_type
));
68 b_initial
.end_with_jump (b_loop_cond
);
71 b_loop_cond
.end_with_conditional (
77 b_loop_body
.add_assignment_op (sum
,
78 GCC_JIT_BINARY_OP_PLUS
,
82 b_loop_body
.add_assignment_op (i
,
83 GCC_JIT_BINARY_OP_PLUS
,
86 b_loop_body
.end_with_jump (b_loop_cond
);
89 b_after_loop
.end_with_return (sum
);
93 main (int argc
, char **argv
)
96 gcc_jit_result
*result
= NULL
;
98 /* Get a "context" object for working with the library. */
99 ctxt
= gccjit::context::acquire ();
101 /* Set some options on the context.
102 Turn this on to see the code being generated, in assembler form. */
103 ctxt
.set_bool_option (GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE
,
106 /* Populate the context. */
109 /* Compile the code. */
110 result
= ctxt
.compile ();
116 fprintf (stderr
, "NULL result");
120 /* Extract the generated code from "result". */
121 typedef int (*loop_test_fn_type
) (int);
122 loop_test_fn_type loop_test
=
123 (loop_test_fn_type
)gcc_jit_result_get_code (result
, "loop_test");
126 fprintf (stderr
, "NULL loop_test");
127 gcc_jit_result_release (result
);
131 /* Run the generated code. */
132 int val
= loop_test (10);
133 printf("loop_test returned: %d\n", val
);
135 gcc_jit_result_release (result
);