2013-10-11 Marc Glisse <marc.glisse@inria.fr>
[official-gcc.git] / gcc / doc / tree-ssa.texi
blobaaf741b33f1cce8128c2bfa0b20e97cd66ca2541
1 @c Copyright (C) 2004-2013 Free Software Foundation, Inc.
2 @c This is part of the GCC manual.
3 @c For copying conditions, see the file gcc.texi.
5 @c ---------------------------------------------------------------------
6 @c Tree SSA
7 @c ---------------------------------------------------------------------
9 @node Tree SSA
10 @chapter Analysis and Optimization of GIMPLE tuples
11 @cindex Tree SSA
12 @cindex Optimization infrastructure for GIMPLE
14 GCC uses three main intermediate languages to represent the program
15 during compilation: GENERIC, GIMPLE and RTL@.  GENERIC is a
16 language-independent representation generated by each front end.  It
17 is used to serve as an interface between the parser and optimizer.
18 GENERIC is a common representation that is able to represent programs
19 written in all the languages supported by GCC@.
21 GIMPLE and RTL are used to optimize the program.  GIMPLE is used for
22 target and language independent optimizations (e.g., inlining,
23 constant propagation, tail call elimination, redundancy elimination,
24 etc).  Much like GENERIC, GIMPLE is a language independent, tree based
25 representation.  However, it differs from GENERIC in that the GIMPLE
26 grammar is more restrictive: expressions contain no more than 3
27 operands (except function calls), it has no control flow structures
28 and expressions with side-effects are only allowed on the right hand
29 side of assignments.  See the chapter describing GENERIC and GIMPLE
30 for more details.
32 This chapter describes the data structures and functions used in the
33 GIMPLE optimizers (also known as ``tree optimizers'' or ``middle
34 end'').  In particular, it focuses on all the macros, data structures,
35 functions and programming constructs needed to implement optimization
36 passes for GIMPLE@.
38 @menu
39 * Annotations::         Attributes for variables.
40 * SSA Operands::        SSA names referenced by GIMPLE statements.
41 * SSA::                 Static Single Assignment representation.
42 * Alias analysis::      Representing aliased loads and stores.
43 * Memory model::        Memory model used by the middle-end.
44 @end menu
46 @node Annotations
47 @section Annotations
48 @cindex annotations
50 The optimizers need to associate attributes with variables during the
51 optimization process.  For instance, we need to know whether a
52 variable has aliases.  All these attributes are stored in data
53 structures called annotations which are then linked to the field
54 @code{ann} in @code{struct tree_common}.
56 Presently, we define annotations for variables (@code{var_ann_t}).
57 Annotations are defined and documented in @file{tree-flow.h}.
60 @node SSA Operands
61 @section SSA Operands
62 @cindex operands
63 @cindex virtual operands
64 @cindex real operands
65 @findex update_stmt
67 Almost every GIMPLE statement will contain a reference to a variable
68 or memory location.  Since statements come in different shapes and
69 sizes, their operands are going to be located at various spots inside
70 the statement's tree.  To facilitate access to the statement's
71 operands, they are organized into lists associated inside each
72 statement's annotation.  Each element in an operand list is a pointer
73 to a @code{VAR_DECL}, @code{PARM_DECL} or @code{SSA_NAME} tree node.
74 This provides a very convenient way of examining and replacing
75 operands.
77 Data flow analysis and optimization is done on all tree nodes
78 representing variables.  Any node for which @code{SSA_VAR_P} returns
79 nonzero is considered when scanning statement operands.  However, not
80 all @code{SSA_VAR_P} variables are processed in the same way.  For the
81 purposes of optimization, we need to distinguish between references to
82 local scalar variables and references to globals, statics, structures,
83 arrays, aliased variables, etc.  The reason is simple, the compiler
84 can gather complete data flow information for a local scalar.  On the
85 other hand, a global variable may be modified by a function call, it
86 may not be possible to keep track of all the elements of an array or
87 the fields of a structure, etc.
89 The operand scanner gathers two kinds of operands: @dfn{real} and
90 @dfn{virtual}.  An operand for which @code{is_gimple_reg} returns true
91 is considered real, otherwise it is a virtual operand.  We also
92 distinguish between uses and definitions.  An operand is used if its
93 value is loaded by the statement (e.g., the operand at the RHS of an
94 assignment).  If the statement assigns a new value to the operand, the
95 operand is considered a definition (e.g., the operand at the LHS of
96 an assignment).
98 Virtual and real operands also have very different data flow
99 properties.  Real operands are unambiguous references to the
100 full object that they represent.  For instance, given
102 @smallexample
104   int a, b;
105   a = b
107 @end smallexample
109 Since @code{a} and @code{b} are non-aliased locals, the statement
110 @code{a = b} will have one real definition and one real use because
111 variable @code{a} is completely modified with the contents of
112 variable @code{b}.  Real definition are also known as @dfn{killing
113 definitions}.  Similarly, the use of @code{b} reads all its bits.
115 In contrast, virtual operands are used with variables that can have
116 a partial or ambiguous reference.  This includes structures, arrays,
117 globals, and aliased variables.  In these cases, we have two types of
118 definitions.  For globals, structures, and arrays, we can determine from
119 a statement whether a variable of these types has a killing definition.
120 If the variable does, then the statement is marked as having a
121 @dfn{must definition} of that variable.  However, if a statement is only
122 defining a part of the variable (i.e.@: a field in a structure), or if we
123 know that a statement might define the variable but we cannot say for sure,
124 then we mark that statement as having a @dfn{may definition}.  For
125 instance, given
127 @smallexample
129   int a, b, *p;
131   if (@dots{})
132     p = &a;
133   else
134     p = &b;
135   *p = 5;
136   return *p;
138 @end smallexample
140 The assignment @code{*p = 5} may be a definition of @code{a} or
141 @code{b}.  If we cannot determine statically where @code{p} is
142 pointing to at the time of the store operation, we create virtual
143 definitions to mark that statement as a potential definition site for
144 @code{a} and @code{b}.  Memory loads are similarly marked with virtual
145 use operands.  Virtual operands are shown in tree dumps right before
146 the statement that contains them.  To request a tree dump with virtual
147 operands, use the @option{-vops} option to @option{-fdump-tree}:
149 @smallexample
151   int a, b, *p;
153   if (@dots{})
154     p = &a;
155   else
156     p = &b;
157   # a = VDEF <a>
158   # b = VDEF <b>
159   *p = 5;
161   # VUSE <a>
162   # VUSE <b>
163   return *p;
165 @end smallexample
167 Notice that @code{VDEF} operands have two copies of the referenced
168 variable.  This indicates that this is not a killing definition of
169 that variable.  In this case we refer to it as a @dfn{may definition}
170 or @dfn{aliased store}.  The presence of the second copy of the
171 variable in the @code{VDEF} operand will become important when the
172 function is converted into SSA form.  This will be used to link all
173 the non-killing definitions to prevent optimizations from making
174 incorrect assumptions about them.
176 Operands are updated as soon as the statement is finished via a call
177 to @code{update_stmt}.  If statement elements are changed via
178 @code{SET_USE} or @code{SET_DEF}, then no further action is required
179 (i.e., those macros take care of updating the statement).  If changes
180 are made by manipulating the statement's tree directly, then a call
181 must be made to @code{update_stmt} when complete.  Calling one of the
182 @code{bsi_insert} routines or @code{bsi_replace} performs an implicit
183 call to @code{update_stmt}.
185 @subsection Operand Iterators And Access Routines
186 @cindex Operand Iterators
187 @cindex Operand Access Routines
189 Operands are collected by @file{tree-ssa-operands.c}.  They are stored
190 inside each statement's annotation and can be accessed through either the
191 operand iterators or an access routine.
193 The following access routines are available for examining operands:
195 @enumerate
196 @item @code{SINGLE_SSA_@{USE,DEF,TREE@}_OPERAND}: These accessors will return
197 NULL unless there is exactly one operand matching the specified flags.  If
198 there is exactly one operand, the operand is returned as either a @code{tree},
199 @code{def_operand_p}, or @code{use_operand_p}.
201 @smallexample
202 tree t = SINGLE_SSA_TREE_OPERAND (stmt, flags);
203 use_operand_p u = SINGLE_SSA_USE_OPERAND (stmt, SSA_ALL_VIRTUAL_USES);
204 def_operand_p d = SINGLE_SSA_DEF_OPERAND (stmt, SSA_OP_ALL_DEFS);
205 @end smallexample
207 @item @code{ZERO_SSA_OPERANDS}: This macro returns true if there are no
208 operands matching the specified flags.
210 @smallexample
211 if (ZERO_SSA_OPERANDS (stmt, SSA_OP_ALL_VIRTUALS))
212   return;
213 @end smallexample
215 @item @code{NUM_SSA_OPERANDS}: This macro Returns the number of operands
216 matching 'flags'.  This actually executes a loop to perform the count, so
217 only use this if it is really needed.
219 @smallexample
220 int count = NUM_SSA_OPERANDS (stmt, flags)
221 @end smallexample
222 @end enumerate
225 If you wish to iterate over some or all operands, use the
226 @code{FOR_EACH_SSA_@{USE,DEF,TREE@}_OPERAND} iterator.  For example, to print
227 all the operands for a statement:
229 @smallexample
230 void
231 print_ops (tree stmt)
233   ssa_op_iter;
234   tree var;
236   FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, SSA_OP_ALL_OPERANDS)
237     print_generic_expr (stderr, var, TDF_SLIM);
239 @end smallexample
242 How to choose the appropriate iterator:
244 @enumerate
245 @item Determine whether you are need to see the operand pointers, or just the
246 trees, and choose the appropriate macro:
248 @smallexample
249 Need            Macro:
250 ----            -------
251 use_operand_p   FOR_EACH_SSA_USE_OPERAND
252 def_operand_p   FOR_EACH_SSA_DEF_OPERAND
253 tree            FOR_EACH_SSA_TREE_OPERAND
254 @end smallexample
256 @item You need to declare a variable of the type you are interested
257 in, and an ssa_op_iter structure which serves as the loop controlling
258 variable.
260 @item Determine which operands you wish to use, and specify the flags of
261 those you are interested in.  They are documented in
262 @file{tree-ssa-operands.h}:
264 @smallexample
265 #define SSA_OP_USE              0x01    /* @r{Real USE operands.}  */
266 #define SSA_OP_DEF              0x02    /* @r{Real DEF operands.}  */
267 #define SSA_OP_VUSE             0x04    /* @r{VUSE operands.}  */
268 #define SSA_OP_VMAYUSE          0x08    /* @r{USE portion of VDEFS.}  */
269 #define SSA_OP_VDEF             0x10    /* @r{DEF portion of VDEFS.}  */
271 /* @r{These are commonly grouped operand flags.}  */
272 #define SSA_OP_VIRTUAL_USES     (SSA_OP_VUSE | SSA_OP_VMAYUSE)
273 #define SSA_OP_VIRTUAL_DEFS     (SSA_OP_VDEF)
274 #define SSA_OP_ALL_USES         (SSA_OP_VIRTUAL_USES | SSA_OP_USE)
275 #define SSA_OP_ALL_DEFS         (SSA_OP_VIRTUAL_DEFS | SSA_OP_DEF)
276 #define SSA_OP_ALL_OPERANDS     (SSA_OP_ALL_USES | SSA_OP_ALL_DEFS)
277 @end smallexample
278 @end enumerate
280 So if you want to look at the use pointers for all the @code{USE} and
281 @code{VUSE} operands, you would do something like:
283 @smallexample
284   use_operand_p use_p;
285   ssa_op_iter iter;
287   FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, (SSA_OP_USE | SSA_OP_VUSE))
288     @{
289       process_use_ptr (use_p);
290     @}
291 @end smallexample
293 The @code{TREE} macro is basically the same as the @code{USE} and
294 @code{DEF} macros, only with the use or def dereferenced via
295 @code{USE_FROM_PTR (use_p)} and @code{DEF_FROM_PTR (def_p)}.  Since we
296 aren't using operand pointers, use and defs flags can be mixed.
298 @smallexample
299   tree var;
300   ssa_op_iter iter;
302   FOR_EACH_SSA_TREE_OPERAND (var, stmt, iter, SSA_OP_VUSE)
303     @{
304        print_generic_expr (stderr, var, TDF_SLIM);
305     @}
306 @end smallexample
308 @code{VDEF}s are broken into two flags, one for the
309 @code{DEF} portion (@code{SSA_OP_VDEF}) and one for the USE portion
310 (@code{SSA_OP_VMAYUSE}).  If all you want to look at are the
311 @code{VDEF}s together, there is a fourth iterator macro for this,
312 which returns both a def_operand_p and a use_operand_p for each
313 @code{VDEF} in the statement.  Note that you don't need any flags for
314 this one.
316 @smallexample
317   use_operand_p use_p;
318   def_operand_p def_p;
319   ssa_op_iter iter;
321   FOR_EACH_SSA_MAYDEF_OPERAND (def_p, use_p, stmt, iter)
322     @{
323       my_code;
324     @}
325 @end smallexample
327 There are many examples in the code as well, as well as the
328 documentation in @file{tree-ssa-operands.h}.
330 There are also a couple of variants on the stmt iterators regarding PHI
331 nodes.
333 @code{FOR_EACH_PHI_ARG} Works exactly like
334 @code{FOR_EACH_SSA_USE_OPERAND}, except it works over @code{PHI} arguments
335 instead of statement operands.
337 @smallexample
338 /* Look at every virtual PHI use.  */
339 FOR_EACH_PHI_ARG (use_p, phi_stmt, iter, SSA_OP_VIRTUAL_USES)
341    my_code;
344 /* Look at every real PHI use.  */
345 FOR_EACH_PHI_ARG (use_p, phi_stmt, iter, SSA_OP_USES)
346   my_code;
348 /* Look at every PHI use.  */
349 FOR_EACH_PHI_ARG (use_p, phi_stmt, iter, SSA_OP_ALL_USES)
350   my_code;
351 @end smallexample
353 @code{FOR_EACH_PHI_OR_STMT_@{USE,DEF@}} works exactly like
354 @code{FOR_EACH_SSA_@{USE,DEF@}_OPERAND}, except it will function on
355 either a statement or a @code{PHI} node.  These should be used when it is
356 appropriate but they are not quite as efficient as the individual
357 @code{FOR_EACH_PHI} and @code{FOR_EACH_SSA} routines.
359 @smallexample
360 FOR_EACH_PHI_OR_STMT_USE (use_operand_p, stmt, iter, flags)
361   @{
362      my_code;
363   @}
365 FOR_EACH_PHI_OR_STMT_DEF (def_operand_p, phi, iter, flags)
366   @{
367      my_code;
368   @}
369 @end smallexample
371 @subsection Immediate Uses
372 @cindex Immediate Uses
374 Immediate use information is now always available.  Using the immediate use
375 iterators, you may examine every use of any @code{SSA_NAME}. For instance,
376 to change each use of @code{ssa_var} to @code{ssa_var2} and call fold_stmt on
377 each stmt after that is done:
379 @smallexample
380   use_operand_p imm_use_p;
381   imm_use_iterator iterator;
382   tree ssa_var, stmt;
385   FOR_EACH_IMM_USE_STMT (stmt, iterator, ssa_var)
386     @{
387       FOR_EACH_IMM_USE_ON_STMT (imm_use_p, iterator)
388         SET_USE (imm_use_p, ssa_var_2);
389       fold_stmt (stmt);
390     @}
391 @end smallexample
393 There are 2 iterators which can be used. @code{FOR_EACH_IMM_USE_FAST} is
394 used when the immediate uses are not changed, i.e., you are looking at the
395 uses, but not setting them.
397 If they do get changed, then care must be taken that things are not changed
398 under the iterators, so use the @code{FOR_EACH_IMM_USE_STMT} and
399 @code{FOR_EACH_IMM_USE_ON_STMT} iterators.  They attempt to preserve the
400 sanity of the use list by moving all the uses for a statement into
401 a controlled position, and then iterating over those uses.  Then the
402 optimization can manipulate the stmt when all the uses have been
403 processed.  This is a little slower than the FAST version since it adds a
404 placeholder element and must sort through the list a bit for each statement.
405 This placeholder element must be also be removed if the loop is
406 terminated early.  The macro @code{BREAK_FROM_IMM_USE_SAFE} is provided
407 to do this :
409 @smallexample
410   FOR_EACH_IMM_USE_STMT (stmt, iterator, ssa_var)
411     @{
412       if (stmt == last_stmt)
413         BREAK_FROM_SAFE_IMM_USE (iter);
415       FOR_EACH_IMM_USE_ON_STMT (imm_use_p, iterator)
416         SET_USE (imm_use_p, ssa_var_2);
417       fold_stmt (stmt);
418     @}
419 @end smallexample
421 There are checks in @code{verify_ssa} which verify that the immediate use list
422 is up to date, as well as checking that an optimization didn't break from the
423 loop without using this macro.  It is safe to simply 'break'; from a
424 @code{FOR_EACH_IMM_USE_FAST} traverse.
426 Some useful functions and macros:
427 @enumerate
428 @item  @code{has_zero_uses (ssa_var)} : Returns true if there are no uses of
429 @code{ssa_var}.
430 @item   @code{has_single_use (ssa_var)} : Returns true if there is only a
431 single use of @code{ssa_var}.
432 @item   @code{single_imm_use (ssa_var, use_operand_p *ptr, tree *stmt)} :
433 Returns true if there is only a single use of @code{ssa_var}, and also returns
434 the use pointer and statement it occurs in, in the second and third parameters.
435 @item   @code{num_imm_uses (ssa_var)} : Returns the number of immediate uses of
436 @code{ssa_var}. It is better not to use this if possible since it simply
437 utilizes a loop to count the uses.
438 @item  @code{PHI_ARG_INDEX_FROM_USE (use_p)} : Given a use within a @code{PHI}
439 node, return the index number for the use.  An assert is triggered if the use
440 isn't located in a @code{PHI} node.
441 @item  @code{USE_STMT (use_p)} : Return the statement a use occurs in.
442 @end enumerate
444 Note that uses are not put into an immediate use list until their statement is
445 actually inserted into the instruction stream via a @code{bsi_*} routine.
447 It is also still possible to utilize lazy updating of statements, but this
448 should be used only when absolutely required.  Both alias analysis and the
449 dominator optimizations currently do this.
451 When lazy updating is being used, the immediate use information is out of date
452 and cannot be used reliably.  Lazy updating is achieved by simply marking
453 statements modified via calls to @code{mark_stmt_modified} instead of
454 @code{update_stmt}.  When lazy updating is no longer required, all the
455 modified statements must have @code{update_stmt} called in order to bring them
456 up to date.  This must be done before the optimization is finished, or
457 @code{verify_ssa} will trigger an abort.
459 This is done with a simple loop over the instruction stream:
460 @smallexample
461   block_stmt_iterator bsi;
462   basic_block bb;
463   FOR_EACH_BB (bb)
464     @{
465       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
466         update_stmt_if_modified (bsi_stmt (bsi));
467     @}
468 @end smallexample
470 @node SSA
471 @section Static Single Assignment
472 @cindex SSA
473 @cindex static single assignment
475 Most of the tree optimizers rely on the data flow information provided
476 by the Static Single Assignment (SSA) form.  We implement the SSA form
477 as described in @cite{R. Cytron, J. Ferrante, B. Rosen, M. Wegman, and
478 K. Zadeck.  Efficiently Computing Static Single Assignment Form and the
479 Control Dependence Graph.  ACM Transactions on Programming Languages
480 and Systems, 13(4):451-490, October 1991}.
482 The SSA form is based on the premise that program variables are
483 assigned in exactly one location in the program.  Multiple assignments
484 to the same variable create new versions of that variable.  Naturally,
485 actual programs are seldom in SSA form initially because variables
486 tend to be assigned multiple times.  The compiler modifies the program
487 representation so that every time a variable is assigned in the code,
488 a new version of the variable is created.  Different versions of the
489 same variable are distinguished by subscripting the variable name with
490 its version number.  Variables used in the right-hand side of
491 expressions are renamed so that their version number matches that of
492 the most recent assignment.
494 We represent variable versions using @code{SSA_NAME} nodes.  The
495 renaming process in @file{tree-ssa.c} wraps every real and
496 virtual operand with an @code{SSA_NAME} node which contains
497 the version number and the statement that created the
498 @code{SSA_NAME}.  Only definitions and virtual definitions may
499 create new @code{SSA_NAME} nodes.
501 @cindex PHI nodes
502 Sometimes, flow of control makes it impossible to determine the
503 most recent version of a variable.  In these cases, the compiler
504 inserts an artificial definition for that variable called
505 @dfn{PHI function} or @dfn{PHI node}.  This new definition merges
506 all the incoming versions of the variable to create a new name
507 for it.  For instance,
509 @smallexample
510 if (@dots{})
511   a_1 = 5;
512 else if (@dots{})
513   a_2 = 2;
514 else
515   a_3 = 13;
517 # a_4 = PHI <a_1, a_2, a_3>
518 return a_4;
519 @end smallexample
521 Since it is not possible to determine which of the three branches
522 will be taken at runtime, we don't know which of @code{a_1},
523 @code{a_2} or @code{a_3} to use at the return statement.  So, the
524 SSA renamer creates a new version @code{a_4} which is assigned
525 the result of ``merging'' @code{a_1}, @code{a_2} and @code{a_3}.
526 Hence, PHI nodes mean ``one of these operands.  I don't know
527 which''.
529 The following macros can be used to examine PHI nodes
531 @defmac PHI_RESULT (@var{phi})
532 Returns the @code{SSA_NAME} created by PHI node @var{phi} (i.e.,
533 @var{phi}'s LHS)@.
534 @end defmac
536 @defmac PHI_NUM_ARGS (@var{phi})
537 Returns the number of arguments in @var{phi}.  This number is exactly
538 the number of incoming edges to the basic block holding @var{phi}@.
539 @end defmac
541 @defmac PHI_ARG_ELT (@var{phi}, @var{i})
542 Returns a tuple representing the @var{i}th argument of @var{phi}@.
543 Each element of this tuple contains an @code{SSA_NAME} @var{var} and
544 the incoming edge through which @var{var} flows.
545 @end defmac
547 @defmac PHI_ARG_EDGE (@var{phi}, @var{i})
548 Returns the incoming edge for the @var{i}th argument of @var{phi}.
549 @end defmac
551 @defmac PHI_ARG_DEF (@var{phi}, @var{i})
552 Returns the @code{SSA_NAME} for the @var{i}th argument of @var{phi}.
553 @end defmac
556 @subsection Preserving the SSA form
557 @findex update_ssa
558 @cindex preserving SSA form
559 Some optimization passes make changes to the function that
560 invalidate the SSA property.  This can happen when a pass has
561 added new symbols or changed the program so that variables that
562 were previously aliased aren't anymore.  Whenever something like this
563 happens, the affected symbols must be renamed into SSA form again.
564 Transformations that emit new code or replicate existing statements
565 will also need to update the SSA form@.
567 Since GCC implements two different SSA forms for register and virtual
568 variables, keeping the SSA form up to date depends on whether you are
569 updating register or virtual names.  In both cases, the general idea
570 behind incremental SSA updates is similar: when new SSA names are
571 created, they typically are meant to replace other existing names in
572 the program@.
574 For instance, given the following code:
576 @smallexample
577      1  L0:
578      2  x_1 = PHI (0, x_5)
579      3  if (x_1 < 10)
580      4    if (x_1 > 7)
581      5      y_2 = 0
582      6    else
583      7      y_3 = x_1 + x_7
584      8    endif
585      9    x_5 = x_1 + 1
586      10   goto L0;
587      11 endif
588 @end smallexample
590 Suppose that we insert new names @code{x_10} and @code{x_11} (lines
591 @code{4} and @code{8})@.
593 @smallexample
594      1  L0:
595      2  x_1 = PHI (0, x_5)
596      3  if (x_1 < 10)
597      4    x_10 = @dots{}
598      5    if (x_1 > 7)
599      6      y_2 = 0
600      7    else
601      8      x_11 = @dots{}
602      9      y_3 = x_1 + x_7
603      10   endif
604      11   x_5 = x_1 + 1
605      12   goto L0;
606      13 endif
607 @end smallexample
609 We want to replace all the uses of @code{x_1} with the new definitions
610 of @code{x_10} and @code{x_11}.  Note that the only uses that should
611 be replaced are those at lines @code{5}, @code{9} and @code{11}.
612 Also, the use of @code{x_7} at line @code{9} should @emph{not} be
613 replaced (this is why we cannot just mark symbol @code{x} for
614 renaming)@.
616 Additionally, we may need to insert a PHI node at line @code{11}
617 because that is a merge point for @code{x_10} and @code{x_11}.  So the
618 use of @code{x_1} at line @code{11} will be replaced with the new PHI
619 node.  The insertion of PHI nodes is optional.  They are not strictly
620 necessary to preserve the SSA form, and depending on what the caller
621 inserted, they may not even be useful for the optimizers@.
623 Updating the SSA form is a two step process.  First, the pass has to
624 identify which names need to be updated and/or which symbols need to
625 be renamed into SSA form for the first time.  When new names are
626 introduced to replace existing names in the program, the mapping
627 between the old and the new names are registered by calling
628 @code{register_new_name_mapping} (note that if your pass creates new
629 code by duplicating basic blocks, the call to @code{tree_duplicate_bb}
630 will set up the necessary mappings automatically).
632 After the replacement mappings have been registered and new symbols
633 marked for renaming, a call to @code{update_ssa} makes the registered
634 changes.  This can be done with an explicit call or by creating
635 @code{TODO} flags in the @code{tree_opt_pass} structure for your pass.
636 There are several @code{TODO} flags that control the behavior of
637 @code{update_ssa}:
639 @itemize @bullet
640 @item @code{TODO_update_ssa}.  Update the SSA form inserting PHI nodes
641 for newly exposed symbols and virtual names marked for updating.
642 When updating real names, only insert PHI nodes for a real name
643 @code{O_j} in blocks reached by all the new and old definitions for
644 @code{O_j}.  If the iterated dominance frontier for @code{O_j}
645 is not pruned, we may end up inserting PHI nodes in blocks that
646 have one or more edges with no incoming definition for
647 @code{O_j}.  This would lead to uninitialized warnings for
648 @code{O_j}'s symbol@.
650 @item @code{TODO_update_ssa_no_phi}.  Update the SSA form without
651 inserting any new PHI nodes at all.  This is used by passes that
652 have either inserted all the PHI nodes themselves or passes that
653 need only to patch use-def and def-def chains for virtuals
654 (e.g., DCE)@.
657 @item @code{TODO_update_ssa_full_phi}.  Insert PHI nodes everywhere
658 they are needed.  No pruning of the IDF is done.  This is used
659 by passes that need the PHI nodes for @code{O_j} even if it
660 means that some arguments will come from the default definition
661 of @code{O_j}'s symbol (e.g., @code{pass_linear_transform})@.
663 WARNING: If you need to use this flag, chances are that your
664 pass may be doing something wrong.  Inserting PHI nodes for an
665 old name where not all edges carry a new replacement may lead to
666 silent codegen errors or spurious uninitialized warnings@.
668 @item @code{TODO_update_ssa_only_virtuals}.  Passes that update the
669 SSA form on their own may want to delegate the updating of
670 virtual names to the generic updater.  Since FUD chains are
671 easier to maintain, this simplifies the work they need to do.
672 NOTE: If this flag is used, any OLD->NEW mappings for real names
673 are explicitly destroyed and only the symbols marked for
674 renaming are processed@.
675 @end itemize
677 @subsection Preserving the virtual SSA form
678 @cindex preserving virtual SSA form
680 The virtual SSA form is harder to preserve than the non-virtual SSA form
681 mainly because the set of virtual operands for a statement may change at
682 what some would consider unexpected times.  In general, statement
683 modifications should be bracketed between calls to
684 @code{push_stmt_changes} and @code{pop_stmt_changes}.  For example,
686 @smallexample
687     munge_stmt (tree stmt)
688     @{
689        push_stmt_changes (&stmt);
690        @dots{} rewrite STMT @dots{}
691        pop_stmt_changes (&stmt);
692     @}
693 @end smallexample
695 The call to @code{push_stmt_changes} saves the current state of the
696 statement operands and the call to @code{pop_stmt_changes} compares
697 the saved state with the current one and does the appropriate symbol
698 marking for the SSA renamer.
700 It is possible to modify several statements at a time, provided that
701 @code{push_stmt_changes} and @code{pop_stmt_changes} are called in
702 LIFO order, as when processing a stack of statements.
704 Additionally, if the pass discovers that it did not need to make
705 changes to the statement after calling @code{push_stmt_changes}, it
706 can simply discard the topmost change buffer by calling
707 @code{discard_stmt_changes}.  This will avoid the expensive operand
708 re-scan operation and the buffer comparison that determines if symbols
709 need to be marked for renaming.
711 @subsection Examining @code{SSA_NAME} nodes
712 @cindex examining SSA_NAMEs
714 The following macros can be used to examine @code{SSA_NAME} nodes
716 @defmac SSA_NAME_DEF_STMT (@var{var})
717 Returns the statement @var{s} that creates the @code{SSA_NAME}
718 @var{var}.  If @var{s} is an empty statement (i.e., @code{IS_EMPTY_STMT
719 (@var{s})} returns @code{true}), it means that the first reference to
720 this variable is a USE or a VUSE@.
721 @end defmac
723 @defmac SSA_NAME_VERSION (@var{var})
724 Returns the version number of the @code{SSA_NAME} object @var{var}.
725 @end defmac
728 @subsection Walking the dominator tree
730 @deftypefn {Tree SSA function} void walk_dominator_tree (@var{walk_data}, @var{bb})
732 This function walks the dominator tree for the current CFG calling a
733 set of callback functions defined in @var{struct dom_walk_data} in
734 @file{domwalk.h}.  The call back functions you need to define give you
735 hooks to execute custom code at various points during traversal:
737 @enumerate
738 @item Once to initialize any local data needed while processing
739 @var{bb} and its children.  This local data is pushed into an
740 internal stack which is automatically pushed and popped as the
741 walker traverses the dominator tree.
743 @item Once before traversing all the statements in the @var{bb}.
745 @item Once for every statement inside @var{bb}.
747 @item Once after traversing all the statements and before recursing
748 into @var{bb}'s dominator children.
750 @item It then recurses into all the dominator children of @var{bb}.
752 @item After recursing into all the dominator children of @var{bb} it
753 can, optionally, traverse every statement in @var{bb} again
754 (i.e., repeating steps 2 and 3).
756 @item Once after walking the statements in @var{bb} and @var{bb}'s
757 dominator children.  At this stage, the block local data stack
758 is popped.
759 @end enumerate
760 @end deftypefn
762 @node Alias analysis
763 @section Alias analysis
764 @cindex alias
765 @cindex flow-sensitive alias analysis
766 @cindex flow-insensitive alias analysis
768 Alias analysis in GIMPLE SSA form consists of two pieces.  First
769 the virtual SSA web ties conflicting memory accesses and provides
770 a SSA use-def chain and SSA immediate-use chains for walking
771 possibly dependent memory accesses.  Second an alias-oracle can
772 be queried to disambiguate explicit and implicit memory references.
774 @enumerate
775 @item Memory SSA form.
777 All statements that may use memory have exactly one accompanied use of
778 a virtual SSA name that represents the state of memory at the
779 given point in the IL.
781 All statements that may define memory have exactly one accompanied
782 definition of a virtual SSA name using the previous state of memory
783 and defining the new state of memory after the given point in the IL.
785 @smallexample
786 int i;
787 int foo (void)
789   # .MEM_3 = VDEF <.MEM_2(D)>
790   i = 1;
791   # VUSE <.MEM_3>
792   return i;
794 @end smallexample
796 The virtual SSA names in this case are @code{.MEM_2(D)} and
797 @code{.MEM_3}.  The store to the global variable @code{i}
798 defines @code{.MEM_3} invalidating @code{.MEM_2(D)}.  The
799 load from @code{i} uses that new state @code{.MEM_3}.
801 The virtual SSA web serves as constraints to SSA optimizers
802 preventing illegitimate code-motion and optimization.  It
803 also provides a way to walk related memory statements.
805 @item Points-to and escape analysis.
807 Points-to analysis builds a set of constraints from the GIMPLE
808 SSA IL representing all pointer operations and facts we do
809 or do not know about pointers.  Solving this set of constraints
810 yields a conservatively correct solution for each pointer
811 variable in the program (though we are only interested in
812 SSA name pointers) as to what it may possibly point to.
814 This points-to solution for a given SSA name pointer is stored
815 in the @code{pt_solution} sub-structure of the
816 @code{SSA_NAME_PTR_INFO} record.  The following accessor
817 functions are available:
819 @itemize @bullet
820 @item @code{pt_solution_includes}
821 @item @code{pt_solutions_intersect}
822 @end itemize
824 Points-to analysis also computes the solution for two special
825 set of pointers, @code{ESCAPED} and @code{CALLUSED}.  Those
826 represent all memory that has escaped the scope of analysis
827 or that is used by pure or nested const calls.
829 @item Type-based alias analysis
831 Type-based alias analysis is frontend dependent though generic
832 support is provided by the middle-end in @code{alias.c}.  TBAA
833 code is used by both tree optimizers and RTL optimizers.
835 Every language that wishes to perform language-specific alias analysis
836 should define a function that computes, given a @code{tree}
837 node, an alias set for the node.  Nodes in different alias sets are not
838 allowed to alias.  For an example, see the C front-end function
839 @code{c_get_alias_set}.
841 @item Tree alias-oracle
843 The tree alias-oracle provides means to disambiguate two memory
844 references and memory references against statements.  The following
845 queries are available:
847 @itemize @bullet
848 @item @code{refs_may_alias_p}
849 @item @code{ref_maybe_used_by_stmt_p}
850 @item @code{stmt_may_clobber_ref_p}
851 @end itemize
853 In addition to those two kind of statement walkers are available
854 walking statements related to a reference ref.
855 @code{walk_non_aliased_vuses} walks over dominating memory defining
856 statements and calls back if the statement does not clobber ref
857 providing the non-aliased VUSE.  The walk stops at
858 the first clobbering statement or if asked to.
859 @code{walk_aliased_vdefs} walks over dominating memory defining
860 statements and calls back on each statement clobbering ref
861 providing its aliasing VDEF.  The walk stops if asked to.
863 @end enumerate
866 @node Memory model
867 @section Memory model
868 @cindex memory model
870 The memory model used by the middle-end models that of the C/C++
871 languages.  The middle-end has the notion of an effective type
872 of a memory region which is used for type-based alias analysis.
874 The following is a refinement of ISO C99 6.5/6, clarifying the block copy case
875 to follow common sense and extending the concept of a dynamic effective
876 type to objects with a declared type as required for C++.
878 @smallexample
879 The effective type of an object for an access to its stored value is
880 the declared type of the object or the effective type determined by
881 a previous store to it.  If a value is stored into an object through
882 an lvalue having a type that is not a character type, then the
883 type of the lvalue becomes the effective type of the object for that
884 access and for subsequent accesses that do not modify the stored value.
885 If a value is copied into an object using @code{memcpy} or @code{memmove},
886 or is copied as an array of character type, then the effective type
887 of the modified object for that access and for subsequent accesses that
888 do not modify the value is undetermined.  For all other accesses to an
889 object, the effective type of the object is simply the type of the
890 lvalue used for the access.
891 @end smallexample