5.4 Gimplification: from GENERIC to GIMPLE in SSA form

Source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0).

You compile count.c with -fdump-tree-original and -fdump-tree-gimple and put the two dumps side by side. The first still shows the if from the source, with its &&. In the second, that if is two ifs, each with two gotos, and one v[i] is a run of new statements. You open passes.def to find the pass that did this, and it is not there. The .gimple dump already has names such as _1, but no PHI node appears until the .ssa dump, several passes later.

Gimplification is a recursive rewrite that runs before the pass list, and SSA form arrives in two steps. The gimplifier flattens expressions and makes control flow explicit. Two passes then build the control flow graph and put the function into SSA form.

This chapter assumes Chapter 5.1, for count.c, the three representations and the definition of SSA, and Chapter 5.2 and Chapter 5.3, for dump file names and passes.def.

Where gimplification runs: gimplify_function_tree

The C front end finishes a function in finish_function. It calls c_genericize, then hands the function to the call graph with cgraph_node::finalize_function (c/c-decl.cc:11520-11540). Later, the call graph analyses each function, and that is where the gimplifier runs:

      /* Make sure to gimplify bodies only once.  During analyzing a
	 function we lower it, which will require gimplified nested
	 functions, so we can end up here with an already gimplified
	 body.  */
      if (!gimple_has_body_p (decl))
	gimplify_function_tree (decl);

      /* Lower the function.  */
      if (!lowered)
	{
	  if (first_nested_function (this))
	    lower_nested_functions (decl);

	  gimple_register_cfg_hooks ();
	  bitmap_obstack_initialize (NULL);
	  execute_pass_list (cfun, g->get_passes ()->all_lowering_passes);

Listing 5.4-1: cgraph_node::analyze gimplifies, then runs the first pass list (gcc/cgraphunit.cc:684-699).

gimplify_function_tree is a plain function call. It comes before all_lowering_passes, the first list in passes.def (passes.def:30-46). It writes the .gimple dump itself, as its last statement (gimplify.cc:21160). c_genericize writes the .original dump in the same way (c-family/c-gimplify.cc:785-803). Both dumps are fixed entries in the dump table, not pass dumps (dumpfile.cc:104-105). register_dumps numbers them "before the optimization passes" (dumpfile.cc:255-270). -fdump-passes prints the pass lists from all_lowering_passes onward (passes.cc:1009-1024), so it never lists either of them.

Five dumps show the whole transformation. Two come from function calls and three from passes:

DumpWritten byShows
originalc_genericize, in the front endGENERIC, with C loops already turned into gotos
gimplegimplify_function_treeHigh GIMPLE: flat statements, labels, nested scopes
lowerpass_lower_cf (gimple-low.cc:223)Low GIMPLE: no scopes, one return
cfgpass_build_cfg (tree-cfg.cc:394)basic blocks and edges
ssapass_build_ssa (tree-into-ssa.cc:2461)SSA names for every register variable, and PHI nodes

Ask for all five in one run:

$ gcc -O2 -c count.c -fdump-tree-original -fdump-tree-gimple \
      -fdump-tree-lower -fdump-tree-cfg -fdump-tree-ssa-details
$ ls count.c.*t.*

This book's machine has no GCC, so nobody ran these commands for this chapter. Each dump shape that the chapter describes comes from the code that prints it, cited at that point. The GCC manual documents -fdump-tree-SWITCH and the -details, -vops and -raw suffixes under Developer Options. It does not name the original or gimple dumps.

The loop is gone before the gimplifier starts: genericize_c_loop

The C parser builds a FOR_STMT (c/c-parser.cc:9299), a tree code that c-common.def adds to GENERIC (c-family/c-common.def:63). c_genericize walks the body and replaces every loop before it writes the .original dump (c-family/c-gimplify.cc:765-779):

      /* Expand to gotos.  */
      tree top = build1 (LABEL_EXPR, void_type_node,
			 create_artificial_label (start_locus));
      ...
      if (cond && !integer_nonzerop (cond))
	{
	  /* Canonicalize the loop condition to the end.  This means
	     generating a branch to the loop condition.  Reuse the
	     continue label, if there is no incr expression.  */

Listing 5.4-2: genericize_c_loop, abridged (gcc/c-family/c-gimplify.cc:352-365).

So the for in count.c reaches the gimplifier as a sequence of four parts: a jump to an entry label, the body, the increment, and the condition with a goto back to the top (c-family/c-gimplify.cc:397-438). The .original dump shows that shape. The if is still a COND_EXPR with an && inside it (c/c-typeck.cc:13112-13120). v[i] is an indirection through a pointer sum, because v is a pointer (c/c-typeck.cc:3419-3431). The sum multiplies the index by the element size (c-family/c-common.cc:3477-3500).

That leaves two lowerings for the gimplifier in this function. One flattens the expression v[i]. The other splits the &&.

The contract of gimplify_expr: a predicate and a fallback

gimplify_body gimplifies the saved body of the function with one call to gimplify_stmt and wraps the result in a single GIMPLE_BIND (gimplify.cc:20792-20870). Every expression then goes through one function. Its comment states the contract:

/* Convert the GENERIC expression tree *EXPR_P to GIMPLE.  If the
   expression produces a value to be used as an operand inside a GIMPLE
   statement, the value will be stored back in *EXPR_P.  This value will
   be a tree of class tcc_declaration, tcc_constant, tcc_reference or
   an SSA_NAME.  The corresponding sequence of GIMPLE statements is
   emitted in PRE_P and POST_P.
...
enum gimplify_status
gimplify_expr (tree *expr_p, gimple_seq *pre_p, gimple_seq *post_p,
	       bool (*gimple_test_f) (tree), fallback_t fallback)

Listing 5.4-3: gimplify_expr, abridged (gcc/gimplify.cc:19260-19265 and :19339-19341).

Three of the parameters do the work:

  • pre_p is the statement list that the caller is building. Every statement that the expression needs goes there, in order.
  • gimple_test_f is a predicate, chosen by the caller. It says which form the caller can accept in its slot: is_gimple_val for an operand of an arithmetic statement, is_gimple_reg for an address that is about to be dereferenced, is_gimple_stmt for a whole statement. The full comment lists them and points at gimple.cc (gimplify.cc:19320-19322).
  • fallback says what to make when the result does not pass the predicate: an rvalue, an lvalue, or nothing (gimplify.cc:19324-19333).

The body is a loop. It first offers the node to the front end's lang_hooks.gimplify_expr, then switches on the tree code, and repeats "until the toplevel node remains the same" (gimplify.cc:19416-19445, :20392). After the loop, the predicate decides:

  if (gimple_seq_empty_p (internal_post) && (*gimple_test_f) (*expr_p))
    goto out;
  ...
  else if ((fallback & fb_rvalue) && is_gimple_reg_rhs_or_call (*expr_p))
    {
      /* An rvalue will do.  Assign the gimplified expression into a
	 new temporary TMP and replace the original expression with
	 TMP.  First, make sure that the expression has a type so that
	 it can be assigned into a temporary.  */
      gcc_assert (!VOID_TYPE_P (TREE_TYPE (*expr_p)));
      *expr_p = get_formal_tmp_var (*expr_p, pre_p);
    }

Listing 5.4-4: the predicate check and the temporary, abridged (gcc/gimplify.cc:20556-20591).

This is the whole flattening mechanism. If the result fits the slot, it stays. If it does not, get_formal_tmp_var appends tmp = <expression> to pre_p and returns tmp, which always fits. The lvalue branch that the listing skips does the same with the address of the expression (gimplify.cc:20566-20582).

The temporaries are already SSA names: internal_get_tmp_var

get_formal_tmp_var calls internal_get_tmp_var (gimplify.cc:729-733), and that function decides what kind of temporary to make:

  if (allow_ssa
      && gimplify_ctxp->into_ssa
      && is_gimple_reg_type (TREE_TYPE (val)))
    {
      t = make_ssa_name (TYPE_MAIN_VARIANT (TREE_TYPE (val)));

Listing 5.4-5: a temporary of register type is an SSA name (gcc/gimplify.cc:686-690).

gimplify_body sets into_ssa for every function body, because it calls push_gimplify_context (true) (gimplify.cc:20807-20808, :382-390). So each temporary of scalar type is an SSA_NAME from the start. It is defined once, by the statement that the gimplifier just built. The pretty-printer prints an SSA name as an optional identifier, an underscore and a version number (tree-pretty-print.cc:3740-3755). A temporary gets an identifier only when its value is a named declaration (gimplify.cc:691-696, tree.cc:11912-11936). A computed value, such as a product or a load, has none, and prints as _1, _2 and so on.

Lowering one: v[i] becomes a chain of temporaries

Follow the condition of the outer if, v[i] != 0, through gimplify_expr. Each row is one recursive call. The predicate is the one that the caller in the row above passes:

GENERIC nodeCase in gimplify_exprPredicateResult
v[i] != 0tcc_comparison, then expr_2is_gimple_condexpr_for_condboth operands gimplified for is_gimple_val
*(v + offset)INDIRECT_REFis_gimple_valbecomes a MEM_REF, which fails the predicate: a load into a temporary
v + offsetPOINTER_PLUS_EXPRis_gimple_regfails the predicate: the address goes into a temporary
index * 8tcc_binary, expr_2is_gimple_valfails: the byte offset goes into a temporary
conversion of iCASE_CONVERTis_gimple_valfails: the widened index goes into a temporary
v, i, 8, 0tcc_declaration, tcc_constantis_gimple_valpass unchanged

This table is a trace of the source, not dump output. The cases are at gimplify.cc:19607-19665 for the conversion and the indirection, and at :20284-20356 for the pointer sum, the comparison and the multiplication. The pointer sum is the shortest of them:

	case POINTER_PLUS_EXPR:
	  {
	    enum gimplify_status r0, r1;
	    r0 = gimplify_expr (&TREE_OPERAND (*expr_p, 0), pre_p,
				post_p, is_gimple_val, fb_rvalue);
	    r1 = gimplify_expr (&TREE_OPERAND (*expr_p, 1), pre_p,
				post_p, is_gimple_val, fb_rvalue);
	    recalculate_side_effects (*expr_p);
	    ret = MIN (r0, r1);
	    break;
	  }

Listing 5.4-6: a binary node only asks its operands to be values (gcc/gimplify.cc:20284-20294).

The case never makes a temporary for the sum itself. It only makes its two operands into values. The check in Listing 5.4-4 then finds that a sum is not an is_gimple_reg, and stores it. Because the inner call returns before the outer check runs, the temporaries appear innermost first: the conversion, the multiplication, the address, the load. That is the run of _N lines that the .gimple dump shows before the outer if.

The second operand of the &&, v[i] % d == 0, repeats the same chain for its own v[i], then adds one statement for %. The internals manual says that the gimplifier "tries to always evaluate identical expressions into the same temporary". The table that does that is in lookup_tmp_var (gimplify.cc:629-671). A temporary of register type takes the SSA branch of Listing 5.4-5 instead, so lookup_tmp_var never sees it. In a function body, each v[i] gets its own chain.

Lowering two: && becomes two GIMPLE_CONDs in shortcut_cond_expr

The if reaches gimplify_cond_expr (gimplify.cc:19483-19484). Before it gimplifies the condition, it checks for a short-circuit operator:

  /* Break apart && and || conditions.  */
  if (TREE_CODE (TREE_OPERAND (expr, 0)) == TRUTH_ANDIF_EXPR
      || TREE_CODE (TREE_OPERAND (expr, 0)) == TRUTH_ORIF_EXPR)
    {
      expr = shortcut_cond_expr (expr, next_cond_uid ());

Listing 5.4-7: gimplify_cond_expr hands && and || to shortcut_cond_expr (gcc/gimplify.cc:5547-5551).

count.c's if has no else, and that selects the simplest of the rewrites:

  /* First do simple transformations.  */
  if (!else_se)
    {
      /* If there is no 'else', turn
	   if (a && b) then c
	 into
	   if (a) if (b) then c.  */
      while (TREE_CODE (pred) == TRUTH_ANDIF_EXPR)
	{
	  /* Keep the original source location on the first 'if'.  */
	  location_t locus = EXPR_LOC_OR_LOC (expr, input_location);
	  TREE_OPERAND (expr, 0) = TREE_OPERAND (pred, 1);
	  /* Set the source location of the && on the second 'if'.  */
	  if (rexpr_has_location (pred))
	    SET_EXPR_LOCATION (expr, rexpr_location (pred));
	  then_ = shortcut_cond_expr (expr, condition_uid);
	  then_se = then_ && TREE_SIDE_EFFECTS (then_);
	  pred = TREE_OPERAND (pred, 0);
	  expr = build3 (COND_EXPR, void_type_node, pred, then_, NULL_TREE);
	  SET_EXPR_LOCATION (expr, locus);
	}
    }

Listing 5.4-8: if (a && b) c becomes two nested ifs (gcc/gimplify.cc:5128-5149).

The rewrite is still GENERIC: two COND_EXPRs, the inner one in the then arm of the outer one. When no && or || is left, the function returns the new tree (gimplify.cc:5176-5179), and gimplify_cond_expr gimplifies it as a statement (:5553-5567). Each of the two ifs now takes the ordinary path. Its condition is gimplified for is_gimple_condexpr_for_cond, which produces the chains of the previous section. Then the if becomes one statement with a label for each arm:

  cond_stmt = gimple_build_cond (pred_code, arm1, arm2, label_true,
				 label_false);

Listing 5.4-9: a GIMPLE_COND carries both of its destinations (gcc/gimplify.cc:5624-5625).

The function then emits the true label, the then arm and the false label after the condition (gimplify.cc:5633-5700). The printer writes a GIMPLE_COND that has labels as if (...) goto L; else goto M; (gimple-pretty-print.cc:1124-1140), and an unnamed label as <D. followed by its declaration UID (tree-pretty-print.cc:2693-2709). That is the if (_N != 0) goto <D.…>; else goto <D.…>; shape in the .gimple dump. The two false labels end up next to each other, because the inner if ends where the outer one does.

With an else arm that has side effects, the simple rewrite does not apply. shortcut_cond_r then builds jumps directly, and its comment shows the shape:

      /* Turn if (a && b) into

	 if (a); else goto no;
	 if (b) goto yes; else goto no;
	 (no:) */

Listing 5.4-10: the general form of && in a condition (gcc/gimplify.cc:4950-4954).

An && whose value you store, as in x = a && b, takes one more step. gimplify_expr first turns it into a && b ? true : false (gimplify.cc:19534-19551). gimplify_cond_expr gives that conditional a temporary, assigns the temporary in each arm, and gimplifies the if that results (gimplify.cc:5477-5536). That if goes through Listing 5.4-7 like any other. The internals manual describes the value form under Logical Operators.

One more rewrite in count.c is easy to miss. count++ is a post-increment, but gimplify_self_mod_expr treats it as a pre-increment when nothing uses the value: "Faster to treat as prefix if result is not used" (gimplify.cc:3681-3684). It becomes the assignment count = count + 1 (:3740-3744), with no temporary.

High GIMPLE to Low GIMPLE: pass_lower_cf

The .gimple dump still has nested scopes. The printer writes each GIMPLE_BIND as a pair of braces with its local declarations at the top (gimple-pretty-print.cc:1193-1219). pass_lower_cf removes them. Its file opens with the list of what it does:

/* The differences between High GIMPLE and Low GIMPLE are the
   following:

   1- Lexical scopes are removed (i.e., GIMPLE_BIND disappears).

   2- GIMPLE_TRY and GIMPLE_CATCH are converted to abnormal control
      flow and exception regions are built as an on-the-side region
      hierarchy (See tree-eh.cc:lower_eh_constructs).

   3- Multiple identical return statements are grouped into a single
      return and gotos to the unique return site.  */

Listing 5.4-11: High and Low GIMPLE (gcc/gimple-low.cc:46-56).

The if statements are not in that list. They were already a condition and two gotos when the gimplifier finished.

Basic blocks from labels: pass_build_cfg

pass_build_cfg runs a few passes later in the same list (passes.def:41). build_gimple_cfg cuts the statement list into blocks, removes unused labels, then makes the edges (tree-cfg.cc:220-256). The cutting rule is two functions. stmt_ends_bb_p ends a block after any control statement (tree-cfg.cc:2904-2907). stmt_starts_bb_p starts one at a label, except when the statement before it is an artificial label (tree-cfg.cc:2862-2879). The gimplifier makes its labels with create_artificial_label (gimplify.cc:5597-5613). So the two false labels from the nested ifs open one block, not two.

The edges replace the labels:

  e = make_edge (bb, then_bb, EDGE_TRUE_VALUE);
  e->goto_locus = gimple_location (then_stmt);
  e = make_edge (bb, else_bb, EDGE_FALSE_VALUE);
  if (e)
    e->goto_locus = gimple_location (else_stmt);

  /* We do not need the labels anymore.  */
  gimple_cond_set_true_label (entry, NULL_TREE);
  gimple_cond_set_false_label (entry, NULL_TREE);

Listing 5.4-12: a GIMPLE_COND's labels become two edges (gcc/tree-cfg.cc:1310-1318).

From here on, a GIMPLE_COND has no labels. The printer writes its destinations from the edges, as goto <bb N>; (gimple-pretty-print.cc:3062-3086, :3048), and starts each block with a <bb N> line (:2982). Look for those two changes when you compare the .lower and .cfg dumps.

SSA form and PHI nodes: pass_build_ssa

The CFG pass is in all_lowering_passes. The SSA builder is not. It is the second pass of pass_build_ssa_passes, in the next list, all_small_ipa_passes (passes.def:49-56). The gate of pass_build_ssa_passes tests for errors and for LTO, not for -O (passes.cc:414-418). The entry point of pass_build_ssa states the algorithm:

/* Main entry point into the SSA builder.  The renaming process
   proceeds in four main phases:

   1- Compute dominance frontier and immediate dominators, needed to
      insert PHI nodes and rename the function in dominator tree
      order.

   2- Find and mark all the blocks that define variables.

   3- Insert PHI nodes at dominance frontiers (insert_phi_nodes).

   4- Rename all the blocks (rewrite_blocks) and statements in the program.

   Steps 3 and 4 are done using the dominator tree walker
   (walk_dominator_tree).  */

Listing 5.4-13: the four phases of pass_build_ssa (gcc/tree-into-ssa.cc:2440-2454). The code follows the same four steps at :2490-2528.

Phase 4 explains why the gimplifier's _N names survive unchanged. The renamer skips every operand that is already an SSA name:

	FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_ALL_USES)
	  {
	    tree var = USE_FROM_PTR (use_p);
	    if (TREE_CODE (var) == SSA_NAME)
	      continue;
	    gcc_checking_assert (DECL_P (var));
	    SET_USE (use_p, get_reaching_def (var));
	  }

Listing 5.4-14: only declarations are renamed (gcc/tree-into-ssa.cc:1363-1370).

The definitions get the same treatment (tree-into-ssa.cc:1374-1398). So only the variables that count.c names are renamed: count, i, and the parameters. Each assignment to count gets a new name with the identifier count and a new version. A parameter has no assignment in the body. Its first use gets a default definition (tree-into-ssa.cc:1203-1228), which the printer marks with (D) (tree-pretty-print.cc:3754-3755). So the .ssa dump compares i against n as a name such as n_7(D).

Where the PHIs go: insert_phi_nodes_for

Phase 3 gives insert_phi_nodes_for one variable and the iterated dominance frontier of the blocks that assign it (tree-into-ssa.cc:950-958). The function first drops the blocks where a PHI would be "obviously useless", from the blocks where the variable is live on entry (:974-976). Then it creates a PHI in each block that is left. With -details, it reports each one:

      if (dump_file && (dump_flags & TDF_DETAILS))
	{
	  fprintf (dump_file, "creating PHI node in block #%d for ", bb_index);
	  print_generic_expr (dump_file, var, TDF_SLIM);
	  fprintf (dump_file, "\n");
	}

Listing 5.4-15: the -details trace of PHI insertion (gcc/tree-into-ssa.cc:985-990).

In count.c, i is assigned before the loop and in the increment. Listing 5.4-2 moved the loop condition to the bottom, so both assignments reach the block that tests i < n. That block is where i needs a PHI. count has the same two assignments that reach the test: count = 0, and whatever value leaves the body. It has one more merge inside the body. The block after the two ifs is reached with count incremented, or not incremented on either false edge. By this reasoning, count.c gets three PHIs. The -details lines name the blocks, so you can check the reasoning against your own dump.

A PHI prints with a leading #, as # count_N = PHI <count_A(3), count_B(5)>. The number in parentheses after each argument is the index of the predecessor block that the value comes from (gimple-pretty-print.cc:2438-2487). Memory is not renamed this way. The Tree SSA passes node of the internals manual says that other variables get virtual operands instead. The dump hides virtual PHIs unless you add -vops (gimple-pretty-print.cc:3011-3020).

Three things to carry away

Gimplification is a function call, not a pass. cgraph_node::analyze calls gimplify_function_tree before the first pass list, so passes.def and -fdump-passes never show it.

gimplify_expr flattens with one rule. It rewrites a node until it stops changing. If the result does not fit the caller's predicate, the result goes into a new temporary.

SSA form arrives in two steps. The gimplifier makes its own temporaries SSA names. pass_build_ssa renames the variables that you wrote and inserts the PHI nodes.

Things that surprise people

An && in the .original dump may not short-circuit. When optimising, fold_truth_andor turns a && b into a non-short-circuit TRUTH_AND_EXPR if both sides are simple comparisons that cannot trap (fold-const.cc:9677-9734). It does this only when LOGICAL_OP_NON_SHORT_CIRCUIT is true. A target can define that macro, and the default is a branch cost of at least 2 (:6240-6243). The C parser folds every condition with c_fully_fold (c/c-parser.cc:8423-8433), which folds && (c/c-fold.cc:532-562). The printer writes both codes as && (tree-pretty-print.cc:4739-4741). The gimplifier turns the non-short-circuit form into a bitwise & and one if (gimplify.cc:20225-20270). -fdump-tree-original-raw prints the tree code names, truth_andif_expr or truth_and_expr (c-family/c-gimplify.cc:799-801, tree-dump.cc:261-262). count.c's && stays short-circuit, because a load through v is not a simple operand (fold-const.cc:5072-5095).

count++ has no post-increment in GIMPLE. A post-increment whose value is unused becomes count = count + 1.

Documentation coverage

The internals manual describes the result well. The GIMPLE node (gcc/doc/gimple.texi:6) defines the representation, and its Temporaries (:522), Operands (:553) and Logical Operators (:636) nodes give the flattening rules with examples. Gimplification pass (gcc/doc/passes.texi:107) names gimplify_function_tree and gimplify_expr and documents the language hook's return values. Tree SSA passes (passes.texi:446) has one paragraph each for the lowering, CFG and SSA passes (:472-509). SSA (gcc/doc/tree-ssa.texi:440) explains SSA names and PHI nodes. The GCC manual documents the dump options under Developer Options (gcc/doc/invoke.texi:20895-20975).

What is not documented, or is out of date at 15.2:

  • The predicate and fallback contract of gimplify_expr. It is only in the comment above the function.
  • That cgraph_node::analyze calls the gimplifier. passes.texi:50-52 says that "the C front end manually invokes the gimplifier". At 15.2 the front end calls c_genericize and cgraph_node::finalize_function.
  • That c_genericize lowers C loops to gotos before gimplification. Chapter 5.1 covers the stale gimple.texi text that says the C front end has no genericization step.
  • Which pass makes if statements into jumps. The "Lower control flow" entry (passes.texi:472-480) gives that job to pass_lower_cf. At 15.2 the gimplifier does it, and pass_lower_cf does the three things in Listing 5.4-11.
  • That temporaries of register type are SSA names from the gimplifier, so the reuse that Temporaries describes (gimple.texi:527-532) does not happen in function bodies.
  • The no-else rewrite of && into nested ifs. Logical Operators excludes the condition of a GIMPLE_COND and does not say what happens there.
  • That the original and gimple dumps are not passes. Developer Options does not name them, and -fdump-passes does not list them.
  • That TRUTH_AND_EXPR and TRUTH_ANDIF_EXPR print the same.
  • tree-ssa.texi:464-465 places the renamer in tree-ssa.cc. It is in tree-into-ssa.cc.

Next: expand, where the GIMPLE of this chapter first meets the target, and v[i] % d must become either an instruction or a call.


All source references in this chapter are to GCC 15.2.0 (releases/gcc-15.2.0). Line numbers in other releases will differ; the surrounding code rarely does. Where behaviour itself changed across a major version, it is flagged inline.