OSDN Git Service

* doc/tree-ssa.texi: Remove references to VDEF and add descriptions
[pf3gnuchains/gcc-fork.git] / gcc / doc / tree-ssa.texi
1 @c Copyright (c) 2004 Free Software Foundation, Inc.
2 @c Free Software Foundation, Inc.
3 @c This is part of the GCC manual.
4 @c For copying conditions, see the file gcc.texi.
5
6 @c ---------------------------------------------------------------------
7 @c Tree SSA
8 @c ---------------------------------------------------------------------
9
10 @node Tree SSA
11 @chapter Analysis and Optimization of GIMPLE Trees
12 @cindex Tree SSA
13 @cindex Optimization infrastructure for GIMPLE
14
15 GCC uses three main intermediate languages to represent the program
16 during compilation: GENERIC, GIMPLE and RTL@.  GENERIC is a
17 language-independent representation generated by each front end.  It
18 is used to serve as an interface between the parser and optimizer.
19 GENERIC is a common representation that is able to represent programs
20 written in all the languages supported by GCC@.
21
22 GIMPLE and RTL are used to optimize the program.  GIMPLE is used for
23 target and language independent optimizations (e.g., inlining,
24 constant propagation, tail call elimination, redundancy elimination,
25 etc).  Much like GENERIC, GIMPLE is a language independent, tree based
26 representation. However, it differs from GENERIC in that the GIMPLE
27 grammar is more restrictive: expressions contain no more than 3
28 operands (except function calls), it has no control flow structures
29 and expressions with side-effects are only allowed on the right hand
30 side of assignments.  See the chapter describing GENERIC and GIMPLE
31 for more details.
32
33 This chapter describes the data structures and functions used in the
34 GIMPLE optimizers (also known as ``tree optimizers'' or ``middle
35 end'').  In particular, it focuses on all the macros, data structures,
36 functions and programming constructs needed to implement optimization
37 passes for GIMPLE@.
38
39 @menu
40 * GENERIC::             A high-level language-independent representation.
41 * GIMPLE::              A lower-level factored tree representation.
42 * Annotations::         Attributes for statements and variables.
43 * Statement Operands::  Variables referenced by GIMPLE statements.
44 * SSA::                 Static Single Assignment representation.
45 * Alias analysis::      Representing aliased loads and stores.
46 @end menu
47
48 @node GENERIC
49 @section GENERIC
50 @cindex GENERIC
51
52 The purpose of GENERIC is simply to provide a language-independent way of
53 representing an entire function in trees.  To this end, it was necessary to
54 add a few new tree codes to the back end, but most everything was already
55 there.  If you can express it with the codes in @code{gcc/tree.def}, it's
56 GENERIC.
57
58 Early on, there was a great deal of debate about how to think about
59 statements in a tree IL.  In GENERIC, a statement is defined as any
60 expression whose value, if any, is ignored.  A statement will always
61 have @code{TREE_SIDE_EFFECTS} set (or it will be discarded), but a
62 non-statement expression may also have side effects.  A
63 @code{CALL_EXPR}, for instance.
64
65 It would be possible for some local optimizations to work on the
66 GENERIC form of a function; indeed, the adapted tree inliner works
67 fine on GENERIC, but the current compiler performs inlining after
68 lowering to GIMPLE (a restricted form described in the next section).
69 Indeed, currently the frontends perform this lowering before handing
70 off to @code{tree_rest_of_compilation}, but this seems inelegant.
71
72 If necessary, a front end can use some language-dependent tree codes
73 in its GENERIC representation, so long as it provides a hook for
74 converting them to GIMPLE and doesn't expect them to work with any
75 (hypothetical) optimizers that run before the conversion to GIMPLE.
76 The intermediate representation used while parsing C and C++ looks
77 very little like GENERIC, but the C and C++ gimplifier hooks are
78 perfectly happy to take it as input and spit out GIMPLE.
79
80 @node GIMPLE
81 @section GIMPLE
82 @cindex GIMPLE
83
84 GIMPLE is a simplified subset of GENERIC for use in optimization.  The
85 particular subset chosen (and the name) was heavily influenced by the
86 SIMPLE IL used by the McCAT compiler project at McGill University,
87 though we have made some different choices.  For one thing, SIMPLE
88 doesn't support @code{goto}; a production compiler can't afford that
89 kind of restriction.
90
91 GIMPLE retains much of the structure of the parse trees: lexical
92 scopes are represented as containers, rather than markers.  However,
93 expressions are broken down into a 3-address form, using temporary
94 variables to hold intermediate values.  Also, control structures are
95 lowered to gotos.
96
97 In GIMPLE no container node is ever used for its value; if a
98 @code{COND_EXPR} or @code{BIND_EXPR} has a value, it is stored into a
99 temporary within the controlled blocks, and that temporary is used in
100 place of the container.
101
102 The compiler pass which lowers GENERIC to GIMPLE is referred to as the
103 @samp{gimplifier}.  The gimplifier works recursively, replacing complex
104 statements with sequences of simple statements.  
105
106 @c Currently, the only way to
107 @c tell whether or not an expression is in GIMPLE form is by recursively
108 @c examining it; in the future there will probably be a flag to help avoid
109 @c redundant work.  FIXME FIXME
110
111 @menu
112 * Interfaces::
113 * Temporaries::
114 * GIMPLE Expressions::
115 * Statements::
116 * GIMPLE Example::
117 * Rough GIMPLE Grammar::
118 @end menu
119
120 @node Interfaces
121 @subsection Interfaces
122 @cindex gimplification
123
124 The tree representation of a function is stored in
125 @code{DECL_SAVED_TREE}.  It is lowered to GIMPLE by a call to
126 @code{gimplify_function_tree}.
127
128 If a front end wants to include language-specific tree codes in the tree
129 representation which it provides to the back end, it must provide a
130 definition of @code{LANG_HOOKS_GIMPLIFY_EXPR} which knows how to
131 convert the front end trees to GIMPLE.  Usually such a hook will involve
132 much of the same code for expanding front end trees to RTL.  This function
133 can return fully lowered GIMPLE, or it can return GENERIC trees and let the
134 main gimplifier lower them the rest of the way; this is often simpler.
135
136 The C and C++ front ends currently convert directly from front end
137 trees to GIMPLE, and hand that off to the back end rather than first
138 converting to GENERIC.  Their gimplifier hooks know about all the
139 @code{_STMT} nodes and how to convert them to GENERIC forms.  There
140 was some work done on a genericization pass which would run first, but
141 the existence of @code{STMT_EXPR} meant that in order to convert all
142 of the C statements into GENERIC equivalents would involve walking the
143 entire tree anyway, so it was simpler to lower all the way.  This
144 might change in the future if someone writes an optimization pass
145 which would work better with higher-level trees, but currently the
146 optimizers all expect GIMPLE.
147
148 A front end which wants to use the tree optimizers (and already has
149 some sort of whole-function tree representation) only needs to provide
150 a definition of @code{LANG_HOOKS_GIMPLIFY_EXPR}, call
151 @code{gimplify_function_tree} to lower to GIMPLE, and then hand off to
152 @code{tree_rest_of_compilation} to compile and output the function.
153
154 You can tell the compiler to dump a C-like representation of the GIMPLE
155 form with the flag @code{-fdump-tree-gimple}.
156
157 @node Temporaries
158 @subsection Temporaries
159 @cindex Temporaries
160
161 When gimplification encounters a subexpression which is too complex, it
162 creates a new temporary variable to hold the value of the subexpression,
163 and adds a new statement to initialize it before the current statement.
164 These special temporaries are known as @samp{expression temporaries}, and are
165 allocated using @code{get_formal_tmp_var}.  The compiler tries to
166 always evaluate identical expressions into the same temporary, to simplify
167 elimination of redundant calculations.
168
169 We can only use expression temporaries when we know that it will not be
170 reevaluated before its value is used, and that it will not be otherwise
171 modified@footnote{These restrictions are derived from those in Morgan 4.8.}.
172 Other temporaries can be allocated using
173 @code{get_initialized_tmp_var} or @code{create_tmp_var}.
174
175 Currently, an expression like @code{a = b + 5} is not reduced any
176 further.  We tried converting it to something like
177 @smallexample
178   T1 = b + 5;
179   a = T1;
180 @end smallexample
181 but this bloated the representation for minimal benefit.  However, a
182 variable which must live in memory cannot appear in an expression; its
183 value is explicitly loaded into a temporary first.  Similarly, storing
184 the value of an expression to a memory variable goes through a
185 temporary.
186
187 @node GIMPLE Expressions
188 @subsection Expressions
189 @cindex GIMPLE Expressions
190
191 In general, expressions in GIMPLE consist of an operation and the
192 appropriate number of simple operands; these operands must either be a
193 GIMPLE rvalue (@code{is_gimple_val}), i.e. a constant or a register
194 variable.  More complex operands are factored out into temporaries, so
195 that
196 @smallexample
197   a = b + c + d 
198 @end smallexample
199 becomes
200 @smallexample
201   T1 = b + c;
202   a = T1 + d;
203 @end smallexample
204
205 The same rule holds for arguments to a @code{CALL_EXPR}.
206
207 The target of an assignment is usually a variable, but can also be an
208 @code{INDIRECT_REF} or a compound lvalue as described below.
209
210 @menu
211 * Compound Expressions::
212 * Compound Lvalues::
213 * Conditional Expressions::
214 * Logical Operators::
215 @end menu
216
217 @node Compound Expressions
218 @subsubsection Compound Expressions
219 @cindex Compound Expressions
220
221 The left-hand side of a C comma expression is simply moved into a separate
222 statement.
223
224 @node Compound Lvalues
225 @subsubsection Compound Lvalues
226 @cindex Compound Lvalues
227
228 Currently compound lvalues involving array and structure field references
229 are not broken down; an expression like @code{a.b[2] = 42} is not reduced
230 any further (though complex array subscripts are).  This restriction is a
231 workaround for limitations in later optimizers; if we were to convert this
232 to
233
234 @smallexample
235   T1 = &a.b;
236   T1[2] = 42;
237 @end smallexample
238
239 alias analysis would not remember that the reference to @code{T1[2]} came
240 by way of @code{a.b}, so it would think that the assignment could alias
241 another member of @code{a}; this broke @code{struct-alias-1.c}.  Future
242 optimizer improvements may make this limitation unnecessary.
243
244 @node Conditional Expressions
245 @subsubsection Conditional Expressions
246 @cindex Conditional Expressions
247
248 A C @code{?:} expression is converted into an @code{if} statement with
249 each branch assigning to the same temporary.  So,
250
251 @smallexample
252   a = b ? c : d;
253 @end smallexample
254 becomes
255 @smallexample
256   if (b)
257     T1 = c;
258   else
259     T1 = d;
260   a = T1;
261 @end smallexample
262
263 Note that in GIMPLE, @code{if} statements are also represented using
264 @code{COND_EXPR}, as described below.
265
266 @node Logical Operators
267 @subsubsection Logical Operators
268 @cindex Logical Operators
269
270 Except when they appear in the condition operand of a @code{COND_EXPR},
271 logical `and' and `or' operators are simplified as follows:
272 @code{a = b && c} becomes
273
274 @smallexample
275   T1 = (bool)b;
276   if (T1)
277     T1 = (bool)c;
278   a = T1;
279 @end smallexample
280
281 Note that @code{T1} in this example cannot be an expression temporary,
282 because it has two different assignments.
283
284 @node Statements
285 @subsection Statements
286 @cindex Statements
287
288 Most statements will be assignment statements, represented by
289 @code{MODIFY_EXPR}.  A @code{CALL_EXPR} whose value is ignored can
290 also be a statement.  No other C expressions can appear at statement level;
291 a reference to a volatile object is converted into a @code{MODIFY_EXPR}.
292
293 There are also several varieties of complex statements.
294
295 @menu
296 * Blocks::
297 * Statement Sequences::
298 * Empty Statements::
299 * Loops::
300 * Selection Statements::
301 * Jumps::
302 * Cleanups::
303 * GIMPLE Exception Handling::
304 @end menu
305
306 @node Blocks
307 @subsubsection Blocks
308 @cindex Blocks
309
310 Block scopes and the variables they declare in GENERIC and GIMPLE are
311 expressed using the @code{BIND_EXPR} code, which in previous versions of
312 GCC was primarily used for the C statement-expression extension.
313
314 Variables in a block are collected into @code{BIND_EXPR_VARS} in
315 declaration order.  Any runtime initialization is moved out of 
316 @code{DECL_INITIAL} and into a statement in the controlled block.  When
317 gimplifying from C or C++, this initialization replaces the
318 @code{DECL_STMT}.
319
320 Variable-length arrays (VLAs) complicate this process, as their size often
321 refers to variables initialized earlier in the block.  To handle this, we
322 currently split the block at that point, and move the VLA into a new, inner
323 @code{BIND_EXPR}.  This strategy may change in the future.
324
325 @code{DECL_SAVED_TREE} for a GIMPLE function will always be a 
326 @code{BIND_EXPR} which contains declarations for the temporary variables
327 used in the function.
328
329 A C++ program will usually contain more @code{BIND_EXPR}s than there are
330 syntactic blocks in the source code, since several C++ constructs have
331 implicit scopes associated with them.  On the other hand, although the C++
332 front end uses pseudo-scopes to handle cleanups for objects with
333 destructors, these don't translate into the GIMPLE form; multiple
334 declarations at the same level use the same BIND_EXPR.
335
336 @node Statement Sequences
337 @subsubsection Statement Sequences
338 @cindex Statement Sequences
339
340 Multiple statements at the same nesting level are collected into a
341 @code{STATEMENT_LIST}.  Statement lists are modified and traversed
342 using the interface in @samp{tree-iterator.h}.
343
344 @node Empty Statements
345 @subsubsection Empty Statements
346 @cindex Empty Statements
347
348 Whenever possible, statements with no effect are discarded.  But if they
349 are nested within another construct which cannot be discarded for some
350 reason, they are instead replaced with an empty statement, generated by
351 @code{build_empty_stmt}.  Initially, all empty statements were shared,
352 after the pattern of the Java front end, but this caused a lot of trouble in
353 practice.
354
355 An empty statement is represented as @code{(void)0}.
356
357 @node Loops
358 @subsubsection Loops
359 @cindex Loops
360
361 At one time loops were expressed in GIMPLE using @code{LOOP_EXPR}, but
362 now they are lowered to explicit gotos.
363
364 @node Selection Statements
365 @subsubsection Selection Statements
366 @cindex Selection Statements
367
368 A simple selection statement, such as the C @code{if} statement, is
369 expressed in GIMPLE using a void @code{COND_EXPR}.  If only one branch is
370 used, the other is filled with an empty statement.
371
372 Normally, the condition expression is reduced to a simple comparison.  If
373 it is a shortcut (@code{&&} or @code{||}) expression, however, we try to
374 break up the @code{if} into multiple @code{if}s so that the implied shortcut
375 is taken directly, much like the transformation done by @code{do_jump} in
376 the RTL expander.
377
378 A @code{SWITCH_EXPR} in GIMPLE contains the condition and a
379 @code{TREE_VEC} of @code{CASE_LABEL_EXPR}s describing the case values
380 and corresponding @code{LABEL_DECL}s to jump to.  The body of the
381 @code{switch} is moved after the @code{SWITCH_EXPR}.
382
383 @node Jumps
384 @subsubsection Jumps
385 @cindex Jumps
386
387 Other jumps are expressed by either @code{GOTO_EXPR} or @code{RETURN_EXPR}.
388
389 The operand of a @code{GOTO_EXPR} must be either a label or a variable
390 containing the address to jump to.
391
392 The operand of a @code{RETURN_EXPR} is either @code{NULL_TREE} or a
393 @code{MODIFY_EXPR} which sets the return value.  It would be nice to
394 move the @code{MODIFY_EXPR} into a separate statement, but the special
395 return semantics in @code{expand_return} make that difficult.  It may
396 still happen in the future, perhaps by moving most of that logic into
397 @code{expand_assignment}.
398
399 @node Cleanups
400 @subsubsection Cleanups
401 @cindex Cleanups
402
403 Destructors for local C++ objects and similar dynamic cleanups are
404 represented in GIMPLE by a @code{TRY_FINALLY_EXPR}.  When the controlled
405 block exits, the cleanup is run.
406
407 @code{TRY_FINALLY_EXPR} complicates the flow graph, since the cleanup
408 needs to appear on every edge out of the controlled block; this
409 reduces our freedom to move code across these edges.  Therefore, the
410 EH lowering pass which runs before most of the optimization passes
411 eliminates these expressions by explicitly adding the cleanup to each
412 edge.
413
414 @node GIMPLE Exception Handling
415 @subsubsection Exception Handling
416 @cindex GIMPLE Exception Handling
417
418 Other exception handling constructs are represented using
419 @code{TRY_CATCH_EXPR}.  The handler operand of a @code{TRY_CATCH_EXPR} 
420 can be a normal statement to be executed if the controlled block throws an
421 exception, or it can have one of two special forms:
422
423 @enumerate
424 @item A @code{CATCH_EXPR} executes its handler if the thrown exception
425   matches one of the allowed types.  Multiple handlers can be
426   expressed by a sequence of @code{CATCH_EXPR} statements.
427 @item An @code{EH_FILTER_EXPR} executes its handler if the thrown
428   exception does not match one of the allowed types.
429 @end enumerate
430
431 Currently throwing an exception is not directly represented in GIMPLE,
432 since it is implemented by calling a function.  At some point in the future
433 we will want to add some way to express that the call will throw an
434 exception of a known type.
435
436 Just before running the optimizers, the compiler lowers the high-level
437 EH constructs above into a set of @samp{goto}s, magic labels, and EH
438 regions.  Continuing to unwind at the end of a cleanup is represented
439 with a @code{RESX_EXPR}.
440
441 @node GIMPLE Example
442 @subsection GIMPLE Example
443 @cindex GIMPLE Example
444
445 @smallexample
446 struct A @{ A(); ~A(); @};
447
448 int i;
449 int g();
450 void f()
451 @{
452   A a;
453   int j = (--i, i ? 0 : 1);
454
455   for (int x = 42; x > 0; --x)
456     @{
457       i += g()*4 + 32;
458     @}
459 @}
460 @end smallexample
461
462 becomes
463
464 @smallexample
465 void f()
466 @{
467   int i.0;
468   int T.1;
469   int iftmp.2;
470   int T.3;
471   int T.4;
472   int T.5;
473   int T.6;
474
475   @{
476     struct A a;
477     int j;
478
479     __comp_ctor (&a);
480     try
481       @{
482         i.0 = i;
483         T.1 = i.0 - 1;
484         i = T.1;
485         i.0 = i;
486         if (i.0 == 0)
487           iftmp.2 = 1;
488         else
489           iftmp.2 = 0;
490         j = iftmp.2;
491         @{
492           int x;
493
494           x = 42;
495           goto test;
496           loop:;
497
498           T.3 = g ();
499           T.4 = T.3 * 4;
500           i.0 = i;
501           T.5 = T.4 + i.0;
502           T.6 = T.5 + 32;
503           i = T.6;
504           x = x - 1;
505
506           test:;
507           if (x > 0)
508             goto loop;
509           else
510             goto break_;
511           break_:;
512         @}
513       @}
514     finally
515       @{
516         __comp_dtor (&a);
517       @}
518   @}
519 @}
520 @end smallexample
521
522 @node Rough GIMPLE Grammar
523 @subsection Rough GIMPLE Grammar
524 @cindex Rough GIMPLE Grammar
525
526 @smallexample
527 function:
528   FUNCTION_DECL
529     DECL_SAVED_TREE -> block
530 block:
531   BIND_EXPR
532     BIND_EXPR_VARS -> DECL chain
533     BIND_EXPR_BLOCK -> BLOCK
534     BIND_EXPR_BODY 
535       -> compound-stmt
536 compound-stmt:
537   COMPOUND_EXPR
538     op0 -> non-compound-stmt
539     op1 -> stmt
540 stmt: compound-stmt
541   | non-compound-stmt
542 non-compound-stmt:
543   block
544   | if-stmt
545   | switch-stmt
546   | jump-stmt
547   | label-stmt
548   | try-stmt
549   | modify-stmt
550   | call-stmt
551 if-stmt:
552   COND_EXPR
553     op0 -> condition
554     op1 -> stmt
555     op2 -> stmt
556 switch-stmt:
557   SWITCH_EXPR
558     op0 -> val
559     op1 -> NULL_TREE
560     op2 -> TREE_VEC of CASE_LABEL_EXPRs
561 jump-stmt:
562     GOTO_EXPR
563       op0 -> LABEL_DECL | '*' ID
564   | RETURN_EXPR
565       op0 -> modify-stmt
566              | NULL_TREE
567 label-stmt:
568   LABEL_EXPR
569       op0 -> LABEL_DECL
570 try-stmt:
571   TRY_CATCH_EXPR
572     op0 -> stmt
573     op1 -> handler
574   | TRY_FINALLY_EXPR
575     op0 -> stmt
576     op1 -> stmt
577 handler:
578   catch-seq
579   | EH_FILTER_EXPR
580   | stmt
581 catch-seq:
582   CATCH_EXPR
583   | COMPOUND_EXPR
584       op0 -> CATCH_EXPR
585       op1 -> catch-seq
586 modify-stmt:
587   MODIFY_EXPR
588     op0 -> lhs
589     op1 -> rhs
590 call-stmt: CALL_EXPR
591   op0 -> _DECL | '&' _DECL
592   op1 -> arglist
593 arglist:
594   NULL_TREE
595   | TREE_LIST
596       op0 -> val
597       op1 -> arglist
598
599 varname : compref | _DECL
600 lhs: varname | '*' _DECL
601 pseudo-lval: _DECL | '*' _DECL
602 compref :
603   COMPONENT_REF
604     op0 -> compref | pseudo-lval
605   | ARRAY_REF
606     op0 -> compref | pseudo-lval
607     op1 -> val
608
609 condition : val | val relop val
610 val : _DECL | CONST
611
612 rhs: varname | CONST
613    | '*' _DECL
614    | '&' varname
615    | call_expr
616    | unop val
617    | val binop val
618    | '(' cast ')' val
619
620 unop: '+' | '-' | '!' | '~'
621
622 binop: relop | '-' | '+' | '/' | '*'
623   | '%' | '&' | '|' | '<<' | '>>' | '^'
624
625 relop: All tree codes of class '<'
626 @end smallexample
627
628 @node Annotations
629 @section Annotations
630 @cindex annotations
631
632 The optimizers need to associate attributes with statements and
633 variables during the optimization process.  For instance, we need to
634 know what basic block does a statement belong to or whether a variable
635 has aliases.  All these attributes are stored in data structures
636 called annotations which are then linked to the field @code{ann} in
637 @code{struct tree_common}.
638
639 Presently, we define annotations for statements (@code{stmt_ann_t}),
640 variables (@code{var_ann_t}) and SSA names (@code{ssa_name_ann_t}).
641 Annotations are defined and documented in @file{tree-flow.h}.
642
643
644 @node Statement Operands
645 @section Statement Operands
646 @cindex operands
647 @cindex virtual operands
648 @cindex real operands
649 @findex get_stmt_operands
650 @findex modify_stmt
651
652 Almost every GIMPLE statement will contain a reference to a variable
653 or memory location.  Since statements come in different shapes and
654 sizes, their operands are going to be located at various spots inside
655 the statement's tree.  To facilitate access to the statement's
656 operands, they are organized into arrays associated inside each
657 statement's annotation.  Each element in an operand array is a pointer
658 to a @code{VAR_DECL}, @code{PARM_DECL} or @code{SSA_NAME} tree node.
659 This provides a very convenient way of examining and replacing
660 operands.  
661
662 Data flow analysis and optimization is done on all tree nodes
663 representing variables.  Any node for which @code{SSA_VAR_P} returns
664 nonzero is considered when scanning statement operands.  However, not
665 all @code{SSA_VAR_P} variables are processed in the same way.  For the
666 purposes of optimization, we need to distinguish between references to
667 local scalar variables and references to globals, statics, structures,
668 arrays, aliased variables, etc.  The reason is simple, the compiler
669 can gather complete data flow information for a local scalar.  On the
670 other hand, a global variable may be modified by a function call, it
671 may not be possible to keep track of all the elements of an array or
672 the fields of a structure, etc.
673
674 The operand scanner gathers two kinds of operands: @dfn{real} and
675 @dfn{virtual}.  An operand for which @code{is_gimple_reg} returns true
676 is considered real, otherwise it is a virtual operand.  We also
677 distinguish between uses and definitions.  An operand is used if its
678 value is loaded by the statement (e.g., the operand at the RHS of an
679 assignment).  If the statement assigns a new value to the operand, the
680 operand is considered a definition (e.g., the operand at the LHS of
681 an assignment).
682
683 Virtual and real operands also have very different data flow
684 properties.  Real operands are unambiguous references to the
685 full object that they represent.  For instance, given
686
687 @smallexample
688 @{
689   int a, b;
690   a = b
691 @}
692 @end smallexample
693
694 Since @code{a} and @code{b} are non-aliased locals, the statement
695 @code{a = b} will have one real definition and one real use because
696 variable @code{b} is completely modified with the contents of
697 variable @code{a}.  Real definition are also known as @dfn{killing
698 definitions}.  Similarly, the use of @code{a} reads all its bits.
699
700 In contrast, virtual operands are used with variables that can have
701 a partial or ambiguous reference. This includes structures, arrays,
702 globals, and aliased variables. In these cases, we have two types of
703 definitions. For globals, structures, and arrays, we can determine from
704 a statement whether a variable of these types has a killing definition. 
705 If the variable does, then the statement is marked as having a
706 @dfn{must definition} of that variable. However, if a statement is only
707 defining a part of the variable (ie. a field in a structure), or if we
708 know that a statement might define the variable but we cannot say for sure,
709 then we mark that statement as having a @dfn{may definition}.  For 
710 instance, given
711
712 @smallexample
713 @{
714   int a, b, *p;
715
716   if (...)
717     p = &a;
718   else
719     p = &b;
720   *p = 5;
721   return *p;
722 @}
723 @end smallexample
724
725 The assignment @code{*p = 5} may be a definition of @code{a} or
726 @code{b}.  If we cannot determine statically where @code{p} is
727 pointing to at the time of the store operation, we create virtual
728 definitions to mark that statement as a potential definition site for
729 @code{a} and @code{b}.  Memory loads are similarly marked with virtual
730 use operands.  Virtual operands are shown in tree dumps right before
731 the statement that contains them.  To request a tree dump with virtual
732 operands, use the @option{-vops} option to @option{-fdump-tree}:
733
734 @smallexample
735 @{
736   int a, b, *p;
737
738   if (...)
739     p = &a;
740   else
741     p = &b;
742   # a = V_MAY_DEF <a>
743   # b = V_MAY_DEF <b>
744   *p = 5;
745
746   # VUSE <a>
747   # VUSE <b>
748   return *p;
749 @}
750 @end smallexample
751
752 Notice that @code{V_MAY_DEF} operands have two copies of the referenced
753 variable.  This indicates that this is not a killing definition of
754 that variable.  In this case we refer to it as a @dfn{may definition}
755 or @dfn{aliased store}.  The presence of the second copy of the
756 variable in the @code{V_MAY_DEF} operand will become important when the
757 function is converted into SSA form.  This will be used to link all
758 the non-killing definitions to prevent optimizations from making
759 incorrect assumptions about them.
760
761 Operands are collected by @file{tree-ssa-operands.c}.  They are stored
762 inside each statement's annotation and can be accessed with
763 @code{DEF_OPS}, @code{USE_OPS}, @code{V_MAY_DEF_OPS}, 
764 @code{V_MUST_DEF_OPS} and @code{VUSE_OPS}. The following are all the 
765 accessor macros available to access USE operands.  To access all the 
766 other operand arrays, just change the name accordingly:
767
768 @defmac USE_OPS (@var{ann})
769 Returns the array of operands used by the statement with annotation
770 @var{ann}.
771 @end defmac
772
773 @defmac STMT_USE_OPS (@var{stmt})
774 Alternate version of USE_OPS that takes the statement @var{stmt} as
775 input.
776 @end defmac
777
778 @defmac NUM_USES (@var{ops})
779 Return the number of USE operands in array @var{ops}.
780 @end defmac
781
782 @defmac USE_OP_PTR (@var{ops}, @var{i})
783 Return a pointer to the @var{i}th operand in array @var{ops}.
784 @end defmac
785
786 @defmac USE_OP (@var{ops}, @var{i})
787 Return the @var{i}th operand in array @var{ops}.
788 @end defmac
789
790 The following function shows how to print all the operands of a given
791 statement:
792
793 @smallexample
794 void
795 print_ops (tree stmt)
796 @{
797   vuse_optype vuses;
798   v_may_def_optype v_may_defs;
799   v_must_def_optype v_must_defs;
800   def_optype defs;
801   use_optype uses;
802   stmt_ann_t ann;
803   size_t i;
804
805   get_stmt_operands (stmt);
806   ann = stmt_ann (stmt);
807   
808   defs = DEF_OPS (ann);
809   for (i = 0; i < NUM_DEFS (defs); i++)
810     print_generic_expr (stderr, DEF_OP (defs, i), 0);
811
812   uses = USE_OPS (ann);
813   for (i = 0; i < NUM_USES (uses); i++)
814     print_generic_expr (stderr, USE_OP (uses, i), 0);
815   
816   v_may_defs = V_MAY_DEF_OPS (ann);
817   for (i = 0; i < NUM_V_MAY_DEFS (v_may_defs); i++)
818     print_generic_expr (stderr, V_MAY_DEF_OP (v_may_defs, i), 0);
819
820   v_must_defs = V_MUST_DEF_OPS (ann);
821   for (i = 0; i < NUM_V_MUST_DEFS (v_must_defs); i++)
822     print_generic_expr (stderr, V_MUST_DEF_OP (v_must_defs, i), 0);
823   
824   vuses = VUSE_OPS (ann);
825   for (i = 0; i < NUM_VUSES (vuses); i++)
826     print_generic_expr (stderr, VUSE_OP (vuses, i), 0);
827 @}
828 @end smallexample
829
830 To collect the operands, you first need to call
831 @code{get_stmt_operands}.  Since that is a potentially expensive
832 operation, statements are only scanned if they have been marked
833 modified by a call to @code{modify_stmt}.  So, if your pass replaces
834 operands in a statement, make sure to call @code{modify_stmt}.
835
836
837 @node SSA
838 @section Static Single Assignment
839 @cindex SSA
840 @cindex static single assignment
841
842 Most of the tree optimizers rely on the data flow information provided
843 by the Static Single Assignment (SSA) form.  We implement the SSA form
844 as described in @cite{R. Cytron, J. Ferrante, B. Rosen, M. Wegman, and
845 K. Zadeck. Efficiently Computing Static Single Assignment Form and the
846 Control Dependence Graph. ACM Transactions on Programming Languages
847 and Systems, 13(4):451-490, October 1991}.
848
849 The SSA form is based on the premise that program variables are
850 assigned in exactly one location in the program.  Multiple assignments
851 to the same variable create new versions of that variable.  Naturally,
852 actual programs are seldom in SSA form initially because variables
853 tend to be assigned multiple times.  The compiler modifies the program
854 representation so that every time a variable is assigned in the code,
855 a new version of the variable is created.  Different versions of the
856 same variable are distinguished by subscripting the variable name with
857 its version number.  Variables used in the right-hand side of
858 expressions are renamed so that their version number matches that of
859 the most recent assignment.
860
861 We represent variable versions using @code{SSA_NAME} nodes.  The
862 renaming process in @file{tree-ssa.c} wraps every real and
863 virtual operand with an @code{SSA_NAME} node which contains
864 the version number and the statement that created the
865 @code{SSA_NAME}.  Only definitions and virtual definitions may
866 create new @code{SSA_NAME} nodes.
867
868 Sometimes, flow of control makes it impossible to determine what is the
869 most recent version of a variable.  In these cases, the compiler
870 inserts an artificial definition for that variable called
871 @dfn{PHI function} or @dfn{PHI node}.  This new definition merges
872 all the incoming versions of the variable to create a new name
873 for it.  For instance,
874
875 @smallexample
876 if (...)
877   a_1 = 5;
878 else if (...)
879   a_2 = 2;
880 else
881   a_3 = 13;
882
883 # a_4 = PHI <a_1, a_2, a_3>
884 return a_4;
885 @end smallexample
886
887 Since it is not possible to determine which of the three branches
888 will be taken at runtime, we don't know which of @code{a_1},
889 @code{a_2} or @code{a_3} to use at the return statement.  So, the
890 SSA renamer creates a new version @code{a_4} which is assigned
891 the result of ``merging'' @code{a_1}, @code{a_2} and @code{a_3}.
892 Hence, PHI nodes mean ``one of these operands.  I don't know
893 which''.
894
895 The following macros can be used to examine PHI nodes
896
897 @defmac PHI_RESULT (@var{phi})
898 Returns the @code{SSA_NAME} created by PHI node @var{phi} (i.e.,
899 @var{phi}'s LHS).
900 @end defmac
901
902 @defmac PHI_NUM_ARGS (@var{phi})
903 Returns the number of arguments in @var{phi}.  This number is exactly
904 the number of incoming edges to the basic block holding @var{phi}@.
905 @end defmac
906
907 @defmac PHI_ARG_ELT (@var{phi}, @var{i})
908 Returns a tuple representing the @var{i}th argument of @var{phi}@.
909 Each element of this tuple contains an @code{SSA_NAME} @var{var} and
910 the incoming edge through which @var{var} flows.
911 @end defmac
912
913 @defmac PHI_ARG_EDGE (@var{phi}, @var{i})
914 Returns the incoming edge for the @var{i}th argument of @var{phi}.
915 @end defmac
916
917 @defmac PHI_ARG_DEF (@var{phi}, @var{i})
918 Returns the @code{SSA_NAME} for the @var{i}th argument of @var{phi}.
919 @end defmac
920
921
922 @subsection Preserving the SSA form
923 @findex vars_to_rename
924 @cindex preserving SSA form
925 Some optimization passes make changes to the function that
926 invalidate the SSA property.  This can happen when a pass has
927 added new variables or changed the program so that variables that
928 were previously aliased aren't anymore.
929
930 Whenever something like this happens, the affected variables must
931 be renamed into SSA form again.  To do this, you should mark the
932 new variables in the global bitmap @code{vars_to_rename}.  Once
933 your pass has finished, the pass manager will invoke the SSA
934 renamer to put the program into SSA once more.
935
936 @subsection Examining @code{SSA_NAME} nodes
937 @cindex examining SSA_NAMEs
938
939 The following macros can be used to examine @code{SSA_NAME} nodes
940
941 @defmac SSA_NAME_DEF_STMT (@var{var})
942 Returns the statement @var{s} that creates the @code{SSA_NAME}
943 @var{var}.  If @var{s} is an empty statement (i.e., @code{IS_EMPTY_STMT
944 (@var{s})} returns @code{true}), it means that the first reference to
945 this variable is a USE or a VUSE@.
946 @end defmac
947
948 @defmac SSA_NAME_VERSION (@var{var})
949 Returns the version number of the @code{SSA_NAME} object @var{var}.
950 @end defmac
951
952
953 @subsection Walking use-def chains
954
955 @deftypefn {Tree SSA function} void walk_use_def_chains (@var{var}, @var{fn}, @var{data})
956
957 Walks use-def chains starting at the @code{SSA_NAME} node @var{var}.
958 Calls function @var{fn} at each reaching definition found.  Function
959 @var{FN} takes three arguments: @var{var}, its defining statement
960 (@var{def_stmt}) and a generic pointer to whatever state information
961 that @var{fn} may want to maintain (@var{data}).  Function @var{fn} is
962 able to stop the walk by returning @code{true}, otherwise in order to
963 continue the walk, @var{fn} should return @code{false}.  
964
965 Note, that if @var{def_stmt} is a @code{PHI} node, the semantics are
966 slightly different.  For each argument @var{arg} of the PHI node, this
967 function will:
968
969 @enumerate
970 @item   Walk the use-def chains for @var{arg}.
971 @item   Call @code{FN (@var{arg}, @var{phi}, @var{data})}.
972 @end enumerate
973
974 Note how the first argument to @var{fn} is no longer the original
975 variable @var{var}, but the PHI argument currently being examined.
976 If @var{fn} wants to get at @var{var}, it should call
977 @code{PHI_RESULT} (@var{phi}).
978 @end deftypefn
979
980 @subsection Walking the dominator tree
981
982 @deftypefn {Tree SSA function} void walk_dominator_tree (@var{walk_data}, @var{bb})
983
984 This function walks the dominator tree for the current CFG calling a
985 set of callback functions defined in @var{struct dom_walk_data} in
986 @file{domwalk.h}.  The call back functions you need to define give you
987 hooks to execute custom code at various points during traversal:
988
989 @enumerate
990 @item Once to initialize any local data needed while processing
991       @var{bb} and its children.  This local data is pushed into an
992       internal stack which is automatically pushed and popped as the
993       walker traverses the dominator tree.
994
995 @item Once before traversing all the statements in the @var{bb}.
996
997 @item Once for every statement inside @var{bb}.
998
999 @item Once after traversing all the statements and before recursing
1000       into @var{bb}'s dominator children.
1001
1002 @item It then recurses into all the dominator children of @var{bb}.
1003
1004 @item After recursing into all the dominator children of @var{bb} it
1005       can, optionally, traverse every statement in @var{bb} again
1006       (i.e., repeating steps 2 and 3).
1007
1008 @item Once after walking the statements in @var{bb} and @var{bb}'s
1009       dominator children.  At this stage, the block local data stack
1010       is popped.
1011 @end enumerate
1012 @end deftypefn
1013
1014 @node Alias analysis
1015 @section Alias analysis
1016 @cindex alias
1017 @cindex flow-sensitive alias analysis
1018 @cindex flow-insensitive alias analysis
1019
1020 Alias analysis proceeds in 3 main phases:
1021
1022 @enumerate
1023 @item   Points-to and escape analysis.
1024
1025 This phase walks the use-def chains in the SSA web looking for
1026 three things:
1027
1028         @itemize @bullet
1029         @item   Assignments of the form @code{P_i = &VAR}
1030         @item   Assignments of the form P_i = malloc()
1031         @item   Pointers and ADDR_EXPR that escape the current function.
1032         @end itemize
1033
1034 The concept of `escaping' is the same one used in the Java world.
1035 When a pointer or an ADDR_EXPR escapes, it means that it has been
1036 exposed outside of the current function.  So, assignment to
1037 global variables, function arguments and returning a pointer are
1038 all escape sites.
1039
1040 This is where we are currently limited.  Since not everything is
1041 renamed into SSA, we lose track of escape properties when a
1042 pointer is stashed inside a field in a structure, for instance.
1043 In those cases, we are assuming that the pointer does escape.
1044
1045 We use escape analysis to determine whether a variable is
1046 call-clobbered.  Simply put, if an ADDR_EXPR escapes, then the
1047 variable is call-clobbered.  If a pointer P_i escapes, then all
1048 the variables pointed-to by P_i (and its memory tag) also escape.
1049
1050 @item   Compute flow-sensitive aliases
1051
1052 We have two classes of memory tags.  Memory tags associated with
1053 the pointed-to data type of the pointers in the program.  These
1054 tags are called ``type memory tag'' (TMT).  The other class are
1055 those associated with SSA_NAMEs, called ``name memory tag'' (NMT).
1056 The basic idea is that when adding operands for an INDIRECT_REF
1057 *P_i, we will first check whether P_i has a name tag, if it does
1058 we use it, because that will have more precise aliasing
1059 information.  Otherwise, we use the standard type tag.
1060
1061 In this phase, we go through all the pointers we found in
1062 points-to analysis and create alias sets for the name memory tags
1063 associated with each pointer P_i.  If P_i escapes, we mark
1064 call-clobbered the variables it points to and its tag.
1065
1066
1067 @item   Compute flow-insensitive aliases
1068
1069 This pass will compare the alias set of every type memory tag and
1070 every addressable variable found in the program.  Given a type
1071 memory tag TMT and an addressable variable V@.  If the alias sets
1072 of TMT and V conflict (as computed by may_alias_p), then V is
1073 marked as an alias tag and added to the alias set of TMT@.
1074 @end enumerate
1075
1076 For instance, consider the following function:
1077
1078 @example
1079 foo (int i)
1080 @{
1081   int *p, *q, a, b;
1082
1083   if (i > 10)
1084     p = &a;
1085   else
1086     q = &b;
1087
1088   *p = 3;
1089   *q = 5;
1090   a = b + 2;
1091   return *p;
1092 @}
1093 @end example
1094
1095 After aliasing analysis has finished, the type memory tag for
1096 pointer @code{p} will have two aliases, namely variables @code{a} and
1097 @code{b}.
1098 Every time pointer @code{p} is dereferenced, we want to mark the
1099 operation as a potential reference to @code{a} and @code{b}.
1100
1101 @example
1102 foo (int i)
1103 @{
1104   int *p, a, b;
1105
1106   if (i_2 > 10)
1107     p_4 = &a;
1108   else
1109     p_6 = &b;
1110   # p_1 = PHI <p_4(1), p_6(2)>;
1111
1112   # a_7 = V_MAY_DEF <a_3>;
1113   # b_8 = V_MAY_DEF <b_5>;
1114   *p_1 = 3;
1115
1116   # a_9 = V_MAY_DEF <a_7>
1117   # VUSE <b_8>
1118   a_9 = b_8 + 2;
1119
1120   # VUSE <a_9>;
1121   # VUSE <b_8>;
1122   return *p_1;
1123 @}
1124 @end example
1125
1126 In certain cases, the list of may aliases for a pointer may grow
1127 too large.  This may cause an explosion in the number of virtual
1128 operands inserted in the code.  Resulting in increased memory
1129 consumption and compilation time.
1130
1131 When the number of virtual operands needed to represent aliased
1132 loads and stores grows too large (configurable with @option{--param
1133 max-aliased-vops}), alias sets are grouped to avoid severe
1134 compile-time slow downs and memory consumption.  The alias
1135 grouping heuristic proceeds as follows:
1136
1137 @enumerate
1138 @item Sort the list of pointers in decreasing number of contributed
1139 virtual operands.
1140
1141 @item Take the first pointer from the list and reverse the role
1142 of the memory tag and its aliases.  Usually, whenever an
1143 aliased variable Vi is found to alias with a memory tag
1144 T, we add Vi to the may-aliases set for T@.  Meaning that
1145 after alias analysis, we will have:
1146
1147 @smallexample
1148 may-aliases(T) = @{ V1, V2, V3, ..., Vn @}
1149 @end smallexample
1150
1151 This means that every statement that references T, will get
1152 @code{n} virtual operands for each of the Vi tags.  But, when
1153 alias grouping is enabled, we make T an alias tag and add it
1154 to the alias set of all the Vi variables:
1155
1156 @smallexample
1157 may-aliases(V1) = @{ T @}
1158 may-aliases(V2) = @{ T @}
1159 ...
1160 may-aliases(Vn) = @{ T @}
1161 @end smallexample
1162
1163 This has two effects: (a) statements referencing T will only get
1164 a single virtual operand, and, (b) all the variables Vi will now
1165 appear to alias each other.  So, we lose alias precision to
1166 improve compile time.  But, in theory, a program with such a high
1167 level of aliasing should not be very optimizable in the first
1168 place.
1169
1170 @item Since variables may be in the alias set of more than one
1171 memory tag, the grouping done in step (2) needs to be extended
1172 to all the memory tags that have a non-empty intersection with
1173 the may-aliases set of tag T@.  For instance, if we originally
1174 had these may-aliases sets:
1175
1176 @smallexample
1177 may-aliases(T) = @{ V1, V2, V3 @}
1178 may-aliases(R) = @{ V2, V4 @}
1179 @end smallexample
1180
1181 In step (2) we would have reverted the aliases for T as:
1182
1183 @smallexample
1184 may-aliases(V1) = @{ T @}
1185 may-aliases(V2) = @{ T @}
1186 may-aliases(V3) = @{ T @}
1187 @end smallexample
1188
1189 But note that now V2 is no longer aliased with R@.  We could
1190 add R to may-aliases(V2), but we are in the process of
1191 grouping aliases to reduce virtual operands so what we do is
1192 add V4 to the grouping to obtain:
1193
1194 @smallexample
1195 may-aliases(V1) = @{ T @}
1196 may-aliases(V2) = @{ T @}
1197 may-aliases(V3) = @{ T @}
1198 may-aliases(V4) = @{ T @}
1199 @end smallexample
1200
1201 @item If the total number of virtual operands due to aliasing is
1202 still above the threshold set by max-alias-vops, go back to (2).
1203 @end enumerate