OSDN Git Service

2011-07-14 Matthias Klose <doko@ubuntu.com>
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-structalias.c
1 /* Tree based points-to analysis
2    Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011
3    Free Software Foundation, Inc.
4    Contributed by Daniel Berlin <dberlin@dberlin.org>
5
6    This file is part of GCC.
7
8    GCC is free software; you can redistribute it and/or modify
9    under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    GCC is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with GCC; see the file COPYING3.  If not see
20    <http://www.gnu.org/licenses/>.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "ggc.h"
27 #include "obstack.h"
28 #include "bitmap.h"
29 #include "flags.h"
30 #include "basic-block.h"
31 #include "output.h"
32 #include "tree.h"
33 #include "tree-flow.h"
34 #include "tree-inline.h"
35 #include "diagnostic-core.h"
36 #include "gimple.h"
37 #include "hashtab.h"
38 #include "function.h"
39 #include "cgraph.h"
40 #include "tree-pass.h"
41 #include "timevar.h"
42 #include "alloc-pool.h"
43 #include "splay-tree.h"
44 #include "params.h"
45 #include "cgraph.h"
46 #include "alias.h"
47 #include "pointer-set.h"
48
49 /* The idea behind this analyzer is to generate set constraints from the
50    program, then solve the resulting constraints in order to generate the
51    points-to sets.
52
53    Set constraints are a way of modeling program analysis problems that
54    involve sets.  They consist of an inclusion constraint language,
55    describing the variables (each variable is a set) and operations that
56    are involved on the variables, and a set of rules that derive facts
57    from these operations.  To solve a system of set constraints, you derive
58    all possible facts under the rules, which gives you the correct sets
59    as a consequence.
60
61    See  "Efficient Field-sensitive pointer analysis for C" by "David
62    J. Pearce and Paul H. J. Kelly and Chris Hankin, at
63    http://citeseer.ist.psu.edu/pearce04efficient.html
64
65    Also see "Ultra-fast Aliasing Analysis using CLA: A Million Lines
66    of C Code in a Second" by ""Nevin Heintze and Olivier Tardieu" at
67    http://citeseer.ist.psu.edu/heintze01ultrafast.html
68
69    There are three types of real constraint expressions, DEREF,
70    ADDRESSOF, and SCALAR.  Each constraint expression consists
71    of a constraint type, a variable, and an offset.
72
73    SCALAR is a constraint expression type used to represent x, whether
74    it appears on the LHS or the RHS of a statement.
75    DEREF is a constraint expression type used to represent *x, whether
76    it appears on the LHS or the RHS of a statement.
77    ADDRESSOF is a constraint expression used to represent &x, whether
78    it appears on the LHS or the RHS of a statement.
79
80    Each pointer variable in the program is assigned an integer id, and
81    each field of a structure variable is assigned an integer id as well.
82
83    Structure variables are linked to their list of fields through a "next
84    field" in each variable that points to the next field in offset
85    order.
86    Each variable for a structure field has
87
88    1. "size", that tells the size in bits of that field.
89    2. "fullsize, that tells the size in bits of the entire structure.
90    3. "offset", that tells the offset in bits from the beginning of the
91    structure to this field.
92
93    Thus,
94    struct f
95    {
96      int a;
97      int b;
98    } foo;
99    int *bar;
100
101    looks like
102
103    foo.a -> id 1, size 32, offset 0, fullsize 64, next foo.b
104    foo.b -> id 2, size 32, offset 32, fullsize 64, next NULL
105    bar -> id 3, size 32, offset 0, fullsize 32, next NULL
106
107
108   In order to solve the system of set constraints, the following is
109   done:
110
111   1. Each constraint variable x has a solution set associated with it,
112   Sol(x).
113
114   2. Constraints are separated into direct, copy, and complex.
115   Direct constraints are ADDRESSOF constraints that require no extra
116   processing, such as P = &Q
117   Copy constraints are those of the form P = Q.
118   Complex constraints are all the constraints involving dereferences
119   and offsets (including offsetted copies).
120
121   3. All direct constraints of the form P = &Q are processed, such
122   that Q is added to Sol(P)
123
124   4. All complex constraints for a given constraint variable are stored in a
125   linked list attached to that variable's node.
126
127   5. A directed graph is built out of the copy constraints. Each
128   constraint variable is a node in the graph, and an edge from
129   Q to P is added for each copy constraint of the form P = Q
130
131   6. The graph is then walked, and solution sets are
132   propagated along the copy edges, such that an edge from Q to P
133   causes Sol(P) <- Sol(P) union Sol(Q).
134
135   7.  As we visit each node, all complex constraints associated with
136   that node are processed by adding appropriate copy edges to the graph, or the
137   appropriate variables to the solution set.
138
139   8. The process of walking the graph is iterated until no solution
140   sets change.
141
142   Prior to walking the graph in steps 6 and 7, We perform static
143   cycle elimination on the constraint graph, as well
144   as off-line variable substitution.
145
146   TODO: Adding offsets to pointer-to-structures can be handled (IE not punted
147   on and turned into anything), but isn't.  You can just see what offset
148   inside the pointed-to struct it's going to access.
149
150   TODO: Constant bounded arrays can be handled as if they were structs of the
151   same number of elements.
152
153   TODO: Modeling heap and incoming pointers becomes much better if we
154   add fields to them as we discover them, which we could do.
155
156   TODO: We could handle unions, but to be honest, it's probably not
157   worth the pain or slowdown.  */
158
159 /* IPA-PTA optimizations possible.
160
161    When the indirect function called is ANYTHING we can add disambiguation
162    based on the function signatures (or simply the parameter count which
163    is the varinfo size).  We also do not need to consider functions that
164    do not have their address taken.
165
166    The is_global_var bit which marks escape points is overly conservative
167    in IPA mode.  Split it to is_escape_point and is_global_var - only
168    externally visible globals are escape points in IPA mode.  This is
169    also needed to fix the pt_solution_includes_global predicate
170    (and thus ptr_deref_may_alias_global_p).
171
172    The way we introduce DECL_PT_UID to avoid fixing up all points-to
173    sets in the translation unit when we copy a DECL during inlining
174    pessimizes precision.  The advantage is that the DECL_PT_UID keeps
175    compile-time and memory usage overhead low - the points-to sets
176    do not grow or get unshared as they would during a fixup phase.
177    An alternative solution is to delay IPA PTA until after all
178    inlining transformations have been applied.
179
180    The way we propagate clobber/use information isn't optimized.
181    It should use a new complex constraint that properly filters
182    out local variables of the callee (though that would make
183    the sets invalid after inlining).  OTOH we might as well
184    admit defeat to WHOPR and simply do all the clobber/use analysis
185    and propagation after PTA finished but before we threw away
186    points-to information for memory variables.  WHOPR and PTA
187    do not play along well anyway - the whole constraint solving
188    would need to be done in WPA phase and it will be very interesting
189    to apply the results to local SSA names during LTRANS phase.
190
191    We probably should compute a per-function unit-ESCAPE solution
192    propagating it simply like the clobber / uses solutions.  The
193    solution can go alongside the non-IPA espaced solution and be
194    used to query which vars escape the unit through a function.
195
196    We never put function decls in points-to sets so we do not
197    keep the set of called functions for indirect calls.
198
199    And probably more.  */
200
201 static bool use_field_sensitive = true;
202 static int in_ipa_mode = 0;
203
204 /* Used for predecessor bitmaps. */
205 static bitmap_obstack predbitmap_obstack;
206
207 /* Used for points-to sets.  */
208 static bitmap_obstack pta_obstack;
209
210 /* Used for oldsolution members of variables. */
211 static bitmap_obstack oldpta_obstack;
212
213 /* Used for per-solver-iteration bitmaps.  */
214 static bitmap_obstack iteration_obstack;
215
216 static unsigned int create_variable_info_for (tree, const char *);
217 typedef struct constraint_graph *constraint_graph_t;
218 static void unify_nodes (constraint_graph_t, unsigned int, unsigned int, bool);
219
220 struct constraint;
221 typedef struct constraint *constraint_t;
222
223 DEF_VEC_P(constraint_t);
224 DEF_VEC_ALLOC_P(constraint_t,heap);
225
226 #define EXECUTE_IF_IN_NONNULL_BITMAP(a, b, c, d)        \
227   if (a)                                                \
228     EXECUTE_IF_SET_IN_BITMAP (a, b, c, d)
229
230 static struct constraint_stats
231 {
232   unsigned int total_vars;
233   unsigned int nonpointer_vars;
234   unsigned int unified_vars_static;
235   unsigned int unified_vars_dynamic;
236   unsigned int iterations;
237   unsigned int num_edges;
238   unsigned int num_implicit_edges;
239   unsigned int points_to_sets_created;
240 } stats;
241
242 struct variable_info
243 {
244   /* ID of this variable  */
245   unsigned int id;
246
247   /* True if this is a variable created by the constraint analysis, such as
248      heap variables and constraints we had to break up.  */
249   unsigned int is_artificial_var : 1;
250
251   /* True if this is a special variable whose solution set should not be
252      changed.  */
253   unsigned int is_special_var : 1;
254
255   /* True for variables whose size is not known or variable.  */
256   unsigned int is_unknown_size_var : 1;
257
258   /* True for (sub-)fields that represent a whole variable.  */
259   unsigned int is_full_var : 1;
260
261   /* True if this is a heap variable.  */
262   unsigned int is_heap_var : 1;
263
264   /* True if this is a variable tracking a restrict pointer source.  */
265   unsigned int is_restrict_var : 1;
266
267   /* True if this field may contain pointers.  */
268   unsigned int may_have_pointers : 1;
269
270   /* True if this field has only restrict qualified pointers.  */
271   unsigned int only_restrict_pointers : 1;
272
273   /* True if this represents a global variable.  */
274   unsigned int is_global_var : 1;
275
276   /* True if this represents a IPA function info.  */
277   unsigned int is_fn_info : 1;
278
279   /* A link to the variable for the next field in this structure.  */
280   struct variable_info *next;
281
282   /* Offset of this variable, in bits, from the base variable  */
283   unsigned HOST_WIDE_INT offset;
284
285   /* Size of the variable, in bits.  */
286   unsigned HOST_WIDE_INT size;
287
288   /* Full size of the base variable, in bits.  */
289   unsigned HOST_WIDE_INT fullsize;
290
291   /* Name of this variable */
292   const char *name;
293
294   /* Tree that this variable is associated with.  */
295   tree decl;
296
297   /* Points-to set for this variable.  */
298   bitmap solution;
299
300   /* Old points-to set for this variable.  */
301   bitmap oldsolution;
302 };
303 typedef struct variable_info *varinfo_t;
304
305 static varinfo_t first_vi_for_offset (varinfo_t, unsigned HOST_WIDE_INT);
306 static varinfo_t first_or_preceding_vi_for_offset (varinfo_t,
307                                                    unsigned HOST_WIDE_INT);
308 static varinfo_t lookup_vi_for_tree (tree);
309
310 /* Pool of variable info structures.  */
311 static alloc_pool variable_info_pool;
312
313 DEF_VEC_P(varinfo_t);
314
315 DEF_VEC_ALLOC_P(varinfo_t, heap);
316
317 /* Table of variable info structures for constraint variables.
318    Indexed directly by variable info id.  */
319 static VEC(varinfo_t,heap) *varmap;
320
321 /* Return the varmap element N */
322
323 static inline varinfo_t
324 get_varinfo (unsigned int n)
325 {
326   return VEC_index (varinfo_t, varmap, n);
327 }
328
329 /* Static IDs for the special variables.  */
330 enum { nothing_id = 0, anything_id = 1, readonly_id = 2,
331        escaped_id = 3, nonlocal_id = 4,
332        storedanything_id = 5, integer_id = 6 };
333
334 /* Return a new variable info structure consisting for a variable
335    named NAME, and using constraint graph node NODE.  Append it
336    to the vector of variable info structures.  */
337
338 static varinfo_t
339 new_var_info (tree t, const char *name)
340 {
341   unsigned index = VEC_length (varinfo_t, varmap);
342   varinfo_t ret = (varinfo_t) pool_alloc (variable_info_pool);
343
344   ret->id = index;
345   ret->name = name;
346   ret->decl = t;
347   /* Vars without decl are artificial and do not have sub-variables.  */
348   ret->is_artificial_var = (t == NULL_TREE);
349   ret->is_special_var = false;
350   ret->is_unknown_size_var = false;
351   ret->is_full_var = (t == NULL_TREE);
352   ret->is_heap_var = false;
353   ret->is_restrict_var = false;
354   ret->may_have_pointers = true;
355   ret->only_restrict_pointers = false;
356   ret->is_global_var = (t == NULL_TREE);
357   ret->is_fn_info = false;
358   if (t && DECL_P (t))
359     ret->is_global_var = (is_global_var (t)
360                           /* We have to treat even local register variables
361                              as escape points.  */
362                           || (TREE_CODE (t) == VAR_DECL
363                               && DECL_HARD_REGISTER (t)));
364   ret->solution = BITMAP_ALLOC (&pta_obstack);
365   ret->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
366   ret->next = NULL;
367
368   stats.total_vars++;
369
370   VEC_safe_push (varinfo_t, heap, varmap, ret);
371
372   return ret;
373 }
374
375
376 /* A map mapping call statements to per-stmt variables for uses
377    and clobbers specific to the call.  */
378 struct pointer_map_t *call_stmt_vars;
379
380 /* Lookup or create the variable for the call statement CALL.  */
381
382 static varinfo_t
383 get_call_vi (gimple call)
384 {
385   void **slot_p;
386   varinfo_t vi, vi2;
387
388   slot_p = pointer_map_insert (call_stmt_vars, call);
389   if (*slot_p)
390     return (varinfo_t) *slot_p;
391
392   vi = new_var_info (NULL_TREE, "CALLUSED");
393   vi->offset = 0;
394   vi->size = 1;
395   vi->fullsize = 2;
396   vi->is_full_var = true;
397
398   vi->next = vi2 = new_var_info (NULL_TREE, "CALLCLOBBERED");
399   vi2->offset = 1;
400   vi2->size = 1;
401   vi2->fullsize = 2;
402   vi2->is_full_var = true;
403
404   *slot_p = (void *) vi;
405   return vi;
406 }
407
408 /* Lookup the variable for the call statement CALL representing
409    the uses.  Returns NULL if there is nothing special about this call.  */
410
411 static varinfo_t
412 lookup_call_use_vi (gimple call)
413 {
414   void **slot_p;
415
416   slot_p = pointer_map_contains (call_stmt_vars, call);
417   if (slot_p)
418     return (varinfo_t) *slot_p;
419
420   return NULL;
421 }
422
423 /* Lookup the variable for the call statement CALL representing
424    the clobbers.  Returns NULL if there is nothing special about this call.  */
425
426 static varinfo_t
427 lookup_call_clobber_vi (gimple call)
428 {
429   varinfo_t uses = lookup_call_use_vi (call);
430   if (!uses)
431     return NULL;
432
433   return uses->next;
434 }
435
436 /* Lookup or create the variable for the call statement CALL representing
437    the uses.  */
438
439 static varinfo_t
440 get_call_use_vi (gimple call)
441 {
442   return get_call_vi (call);
443 }
444
445 /* Lookup or create the variable for the call statement CALL representing
446    the clobbers.  */
447
448 static varinfo_t ATTRIBUTE_UNUSED
449 get_call_clobber_vi (gimple call)
450 {
451   return get_call_vi (call)->next;
452 }
453
454
455 typedef enum {SCALAR, DEREF, ADDRESSOF} constraint_expr_type;
456
457 /* An expression that appears in a constraint.  */
458
459 struct constraint_expr
460 {
461   /* Constraint type.  */
462   constraint_expr_type type;
463
464   /* Variable we are referring to in the constraint.  */
465   unsigned int var;
466
467   /* Offset, in bits, of this constraint from the beginning of
468      variables it ends up referring to.
469
470      IOW, in a deref constraint, we would deref, get the result set,
471      then add OFFSET to each member.   */
472   HOST_WIDE_INT offset;
473 };
474
475 /* Use 0x8000... as special unknown offset.  */
476 #define UNKNOWN_OFFSET ((HOST_WIDE_INT)-1 << (HOST_BITS_PER_WIDE_INT-1))
477
478 typedef struct constraint_expr ce_s;
479 DEF_VEC_O(ce_s);
480 DEF_VEC_ALLOC_O(ce_s, heap);
481 static void get_constraint_for_1 (tree, VEC(ce_s, heap) **, bool, bool);
482 static void get_constraint_for (tree, VEC(ce_s, heap) **);
483 static void get_constraint_for_rhs (tree, VEC(ce_s, heap) **);
484 static void do_deref (VEC (ce_s, heap) **);
485
486 /* Our set constraints are made up of two constraint expressions, one
487    LHS, and one RHS.
488
489    As described in the introduction, our set constraints each represent an
490    operation between set valued variables.
491 */
492 struct constraint
493 {
494   struct constraint_expr lhs;
495   struct constraint_expr rhs;
496 };
497
498 /* List of constraints that we use to build the constraint graph from.  */
499
500 static VEC(constraint_t,heap) *constraints;
501 static alloc_pool constraint_pool;
502
503 /* The constraint graph is represented as an array of bitmaps
504    containing successor nodes.  */
505
506 struct constraint_graph
507 {
508   /* Size of this graph, which may be different than the number of
509      nodes in the variable map.  */
510   unsigned int size;
511
512   /* Explicit successors of each node. */
513   bitmap *succs;
514
515   /* Implicit predecessors of each node (Used for variable
516      substitution). */
517   bitmap *implicit_preds;
518
519   /* Explicit predecessors of each node (Used for variable substitution).  */
520   bitmap *preds;
521
522   /* Indirect cycle representatives, or -1 if the node has no indirect
523      cycles.  */
524   int *indirect_cycles;
525
526   /* Representative node for a node.  rep[a] == a unless the node has
527      been unified. */
528   unsigned int *rep;
529
530   /* Equivalence class representative for a label.  This is used for
531      variable substitution.  */
532   int *eq_rep;
533
534   /* Pointer equivalence label for a node.  All nodes with the same
535      pointer equivalence label can be unified together at some point
536      (either during constraint optimization or after the constraint
537      graph is built).  */
538   unsigned int *pe;
539
540   /* Pointer equivalence representative for a label.  This is used to
541      handle nodes that are pointer equivalent but not location
542      equivalent.  We can unite these once the addressof constraints
543      are transformed into initial points-to sets.  */
544   int *pe_rep;
545
546   /* Pointer equivalence label for each node, used during variable
547      substitution.  */
548   unsigned int *pointer_label;
549
550   /* Location equivalence label for each node, used during location
551      equivalence finding.  */
552   unsigned int *loc_label;
553
554   /* Pointed-by set for each node, used during location equivalence
555      finding.  This is pointed-by rather than pointed-to, because it
556      is constructed using the predecessor graph.  */
557   bitmap *pointed_by;
558
559   /* Points to sets for pointer equivalence.  This is *not* the actual
560      points-to sets for nodes.  */
561   bitmap *points_to;
562
563   /* Bitmap of nodes where the bit is set if the node is a direct
564      node.  Used for variable substitution.  */
565   sbitmap direct_nodes;
566
567   /* Bitmap of nodes where the bit is set if the node is address
568      taken.  Used for variable substitution.  */
569   bitmap address_taken;
570
571   /* Vector of complex constraints for each graph node.  Complex
572      constraints are those involving dereferences or offsets that are
573      not 0.  */
574   VEC(constraint_t,heap) **complex;
575 };
576
577 static constraint_graph_t graph;
578
579 /* During variable substitution and the offline version of indirect
580    cycle finding, we create nodes to represent dereferences and
581    address taken constraints.  These represent where these start and
582    end.  */
583 #define FIRST_REF_NODE (VEC_length (varinfo_t, varmap))
584 #define LAST_REF_NODE (FIRST_REF_NODE + (FIRST_REF_NODE - 1))
585
586 /* Return the representative node for NODE, if NODE has been unioned
587    with another NODE.
588    This function performs path compression along the way to finding
589    the representative.  */
590
591 static unsigned int
592 find (unsigned int node)
593 {
594   gcc_assert (node < graph->size);
595   if (graph->rep[node] != node)
596     return graph->rep[node] = find (graph->rep[node]);
597   return node;
598 }
599
600 /* Union the TO and FROM nodes to the TO nodes.
601    Note that at some point in the future, we may want to do
602    union-by-rank, in which case we are going to have to return the
603    node we unified to.  */
604
605 static bool
606 unite (unsigned int to, unsigned int from)
607 {
608   gcc_assert (to < graph->size && from < graph->size);
609   if (to != from && graph->rep[from] != to)
610     {
611       graph->rep[from] = to;
612       return true;
613     }
614   return false;
615 }
616
617 /* Create a new constraint consisting of LHS and RHS expressions.  */
618
619 static constraint_t
620 new_constraint (const struct constraint_expr lhs,
621                 const struct constraint_expr rhs)
622 {
623   constraint_t ret = (constraint_t) pool_alloc (constraint_pool);
624   ret->lhs = lhs;
625   ret->rhs = rhs;
626   return ret;
627 }
628
629 /* Print out constraint C to FILE.  */
630
631 static void
632 dump_constraint (FILE *file, constraint_t c)
633 {
634   if (c->lhs.type == ADDRESSOF)
635     fprintf (file, "&");
636   else if (c->lhs.type == DEREF)
637     fprintf (file, "*");
638   fprintf (file, "%s", get_varinfo (c->lhs.var)->name);
639   if (c->lhs.offset == UNKNOWN_OFFSET)
640     fprintf (file, " + UNKNOWN");
641   else if (c->lhs.offset != 0)
642     fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->lhs.offset);
643   fprintf (file, " = ");
644   if (c->rhs.type == ADDRESSOF)
645     fprintf (file, "&");
646   else if (c->rhs.type == DEREF)
647     fprintf (file, "*");
648   fprintf (file, "%s", get_varinfo (c->rhs.var)->name);
649   if (c->rhs.offset == UNKNOWN_OFFSET)
650     fprintf (file, " + UNKNOWN");
651   else if (c->rhs.offset != 0)
652     fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->rhs.offset);
653 }
654
655
656 void debug_constraint (constraint_t);
657 void debug_constraints (void);
658 void debug_constraint_graph (void);
659 void debug_solution_for_var (unsigned int);
660 void debug_sa_points_to_info (void);
661
662 /* Print out constraint C to stderr.  */
663
664 DEBUG_FUNCTION void
665 debug_constraint (constraint_t c)
666 {
667   dump_constraint (stderr, c);
668   fprintf (stderr, "\n");
669 }
670
671 /* Print out all constraints to FILE */
672
673 static void
674 dump_constraints (FILE *file, int from)
675 {
676   int i;
677   constraint_t c;
678   for (i = from; VEC_iterate (constraint_t, constraints, i, c); i++)
679     if (c)
680       {
681         dump_constraint (file, c);
682         fprintf (file, "\n");
683       }
684 }
685
686 /* Print out all constraints to stderr.  */
687
688 DEBUG_FUNCTION void
689 debug_constraints (void)
690 {
691   dump_constraints (stderr, 0);
692 }
693
694 /* Print the constraint graph in dot format.  */
695
696 static void
697 dump_constraint_graph (FILE *file)
698 {
699   unsigned int i;
700
701   /* Only print the graph if it has already been initialized:  */
702   if (!graph)
703     return;
704
705   /* Prints the header of the dot file:  */
706   fprintf (file, "strict digraph {\n");
707   fprintf (file, "  node [\n    shape = box\n  ]\n");
708   fprintf (file, "  edge [\n    fontsize = \"12\"\n  ]\n");
709   fprintf (file, "\n  // List of nodes and complex constraints in "
710            "the constraint graph:\n");
711
712   /* The next lines print the nodes in the graph together with the
713      complex constraints attached to them.  */
714   for (i = 0; i < graph->size; i++)
715     {
716       if (find (i) != i)
717         continue;
718       if (i < FIRST_REF_NODE)
719         fprintf (file, "\"%s\"", get_varinfo (i)->name);
720       else
721         fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
722       if (graph->complex[i])
723         {
724           unsigned j;
725           constraint_t c;
726           fprintf (file, " [label=\"\\N\\n");
727           for (j = 0; VEC_iterate (constraint_t, graph->complex[i], j, c); ++j)
728             {
729               dump_constraint (file, c);
730               fprintf (file, "\\l");
731             }
732           fprintf (file, "\"]");
733         }
734       fprintf (file, ";\n");
735     }
736
737   /* Go over the edges.  */
738   fprintf (file, "\n  // Edges in the constraint graph:\n");
739   for (i = 0; i < graph->size; i++)
740     {
741       unsigned j;
742       bitmap_iterator bi;
743       if (find (i) != i)
744         continue;
745       EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i], 0, j, bi)
746         {
747           unsigned to = find (j);
748           if (i == to)
749             continue;
750           if (i < FIRST_REF_NODE)
751             fprintf (file, "\"%s\"", get_varinfo (i)->name);
752           else
753             fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
754           fprintf (file, " -> ");
755           if (to < FIRST_REF_NODE)
756             fprintf (file, "\"%s\"", get_varinfo (to)->name);
757           else
758             fprintf (file, "\"*%s\"", get_varinfo (to - FIRST_REF_NODE)->name);
759           fprintf (file, ";\n");
760         }
761     }
762
763   /* Prints the tail of the dot file.  */
764   fprintf (file, "}\n");
765 }
766
767 /* Print out the constraint graph to stderr.  */
768
769 DEBUG_FUNCTION void
770 debug_constraint_graph (void)
771 {
772   dump_constraint_graph (stderr);
773 }
774
775 /* SOLVER FUNCTIONS
776
777    The solver is a simple worklist solver, that works on the following
778    algorithm:
779
780    sbitmap changed_nodes = all zeroes;
781    changed_count = 0;
782    For each node that is not already collapsed:
783        changed_count++;
784        set bit in changed nodes
785
786    while (changed_count > 0)
787    {
788      compute topological ordering for constraint graph
789
790      find and collapse cycles in the constraint graph (updating
791      changed if necessary)
792
793      for each node (n) in the graph in topological order:
794        changed_count--;
795
796        Process each complex constraint associated with the node,
797        updating changed if necessary.
798
799        For each outgoing edge from n, propagate the solution from n to
800        the destination of the edge, updating changed as necessary.
801
802    }  */
803
804 /* Return true if two constraint expressions A and B are equal.  */
805
806 static bool
807 constraint_expr_equal (struct constraint_expr a, struct constraint_expr b)
808 {
809   return a.type == b.type && a.var == b.var && a.offset == b.offset;
810 }
811
812 /* Return true if constraint expression A is less than constraint expression
813    B.  This is just arbitrary, but consistent, in order to give them an
814    ordering.  */
815
816 static bool
817 constraint_expr_less (struct constraint_expr a, struct constraint_expr b)
818 {
819   if (a.type == b.type)
820     {
821       if (a.var == b.var)
822         return a.offset < b.offset;
823       else
824         return a.var < b.var;
825     }
826   else
827     return a.type < b.type;
828 }
829
830 /* Return true if constraint A is less than constraint B.  This is just
831    arbitrary, but consistent, in order to give them an ordering.  */
832
833 static bool
834 constraint_less (const constraint_t a, const constraint_t b)
835 {
836   if (constraint_expr_less (a->lhs, b->lhs))
837     return true;
838   else if (constraint_expr_less (b->lhs, a->lhs))
839     return false;
840   else
841     return constraint_expr_less (a->rhs, b->rhs);
842 }
843
844 /* Return true if two constraints A and B are equal.  */
845
846 static bool
847 constraint_equal (struct constraint a, struct constraint b)
848 {
849   return constraint_expr_equal (a.lhs, b.lhs)
850     && constraint_expr_equal (a.rhs, b.rhs);
851 }
852
853
854 /* Find a constraint LOOKFOR in the sorted constraint vector VEC */
855
856 static constraint_t
857 constraint_vec_find (VEC(constraint_t,heap) *vec,
858                      struct constraint lookfor)
859 {
860   unsigned int place;
861   constraint_t found;
862
863   if (vec == NULL)
864     return NULL;
865
866   place = VEC_lower_bound (constraint_t, vec, &lookfor, constraint_less);
867   if (place >= VEC_length (constraint_t, vec))
868     return NULL;
869   found = VEC_index (constraint_t, vec, place);
870   if (!constraint_equal (*found, lookfor))
871     return NULL;
872   return found;
873 }
874
875 /* Union two constraint vectors, TO and FROM.  Put the result in TO.  */
876
877 static void
878 constraint_set_union (VEC(constraint_t,heap) **to,
879                       VEC(constraint_t,heap) **from)
880 {
881   int i;
882   constraint_t c;
883
884   FOR_EACH_VEC_ELT (constraint_t, *from, i, c)
885     {
886       if (constraint_vec_find (*to, *c) == NULL)
887         {
888           unsigned int place = VEC_lower_bound (constraint_t, *to, c,
889                                                 constraint_less);
890           VEC_safe_insert (constraint_t, heap, *to, place, c);
891         }
892     }
893 }
894
895 /* Expands the solution in SET to all sub-fields of variables included.
896    Union the expanded result into RESULT.  */
897
898 static void
899 solution_set_expand (bitmap result, bitmap set)
900 {
901   bitmap_iterator bi;
902   bitmap vars = NULL;
903   unsigned j;
904
905   /* In a first pass record all variables we need to add all
906      sub-fields off.  This avoids quadratic behavior.  */
907   EXECUTE_IF_SET_IN_BITMAP (set, 0, j, bi)
908     {
909       varinfo_t v = get_varinfo (j);
910       if (v->is_artificial_var
911           || v->is_full_var)
912         continue;
913       v = lookup_vi_for_tree (v->decl);
914       if (vars == NULL)
915         vars = BITMAP_ALLOC (NULL);
916       bitmap_set_bit (vars, v->id);
917     }
918
919   /* In the second pass now do the addition to the solution and
920      to speed up solving add it to the delta as well.  */
921   if (vars != NULL)
922     {
923       EXECUTE_IF_SET_IN_BITMAP (vars, 0, j, bi)
924         {
925           varinfo_t v = get_varinfo (j);
926           for (; v != NULL; v = v->next)
927             bitmap_set_bit (result, v->id);
928         }
929       BITMAP_FREE (vars);
930     }
931 }
932
933 /* Take a solution set SET, add OFFSET to each member of the set, and
934    overwrite SET with the result when done.  */
935
936 static void
937 solution_set_add (bitmap set, HOST_WIDE_INT offset)
938 {
939   bitmap result = BITMAP_ALLOC (&iteration_obstack);
940   unsigned int i;
941   bitmap_iterator bi;
942
943   /* If the offset is unknown we have to expand the solution to
944      all subfields.  */
945   if (offset == UNKNOWN_OFFSET)
946     {
947       solution_set_expand (set, set);
948       return;
949     }
950
951   EXECUTE_IF_SET_IN_BITMAP (set, 0, i, bi)
952     {
953       varinfo_t vi = get_varinfo (i);
954
955       /* If this is a variable with just one field just set its bit
956          in the result.  */
957       if (vi->is_artificial_var
958           || vi->is_unknown_size_var
959           || vi->is_full_var)
960         bitmap_set_bit (result, i);
961       else
962         {
963           unsigned HOST_WIDE_INT fieldoffset = vi->offset + offset;
964
965           /* If the offset makes the pointer point to before the
966              variable use offset zero for the field lookup.  */
967           if (offset < 0
968               && fieldoffset > vi->offset)
969             fieldoffset = 0;
970
971           if (offset != 0)
972             vi = first_or_preceding_vi_for_offset (vi, fieldoffset);
973
974           bitmap_set_bit (result, vi->id);
975           /* If the result is not exactly at fieldoffset include the next
976              field as well.  See get_constraint_for_ptr_offset for more
977              rationale.  */
978           if (vi->offset != fieldoffset
979               && vi->next != NULL)
980             bitmap_set_bit (result, vi->next->id);
981         }
982     }
983
984   bitmap_copy (set, result);
985   BITMAP_FREE (result);
986 }
987
988 /* Union solution sets TO and FROM, and add INC to each member of FROM in the
989    process.  */
990
991 static bool
992 set_union_with_increment  (bitmap to, bitmap from, HOST_WIDE_INT inc)
993 {
994   if (inc == 0)
995     return bitmap_ior_into (to, from);
996   else
997     {
998       bitmap tmp;
999       bool res;
1000
1001       tmp = BITMAP_ALLOC (&iteration_obstack);
1002       bitmap_copy (tmp, from);
1003       solution_set_add (tmp, inc);
1004       res = bitmap_ior_into (to, tmp);
1005       BITMAP_FREE (tmp);
1006       return res;
1007     }
1008 }
1009
1010 /* Insert constraint C into the list of complex constraints for graph
1011    node VAR.  */
1012
1013 static void
1014 insert_into_complex (constraint_graph_t graph,
1015                      unsigned int var, constraint_t c)
1016 {
1017   VEC (constraint_t, heap) *complex = graph->complex[var];
1018   unsigned int place = VEC_lower_bound (constraint_t, complex, c,
1019                                         constraint_less);
1020
1021   /* Only insert constraints that do not already exist.  */
1022   if (place >= VEC_length (constraint_t, complex)
1023       || !constraint_equal (*c, *VEC_index (constraint_t, complex, place)))
1024     VEC_safe_insert (constraint_t, heap, graph->complex[var], place, c);
1025 }
1026
1027
1028 /* Condense two variable nodes into a single variable node, by moving
1029    all associated info from SRC to TO.  */
1030
1031 static void
1032 merge_node_constraints (constraint_graph_t graph, unsigned int to,
1033                         unsigned int from)
1034 {
1035   unsigned int i;
1036   constraint_t c;
1037
1038   gcc_assert (find (from) == to);
1039
1040   /* Move all complex constraints from src node into to node  */
1041   FOR_EACH_VEC_ELT (constraint_t, graph->complex[from], i, c)
1042     {
1043       /* In complex constraints for node src, we may have either
1044          a = *src, and *src = a, or an offseted constraint which are
1045          always added to the rhs node's constraints.  */
1046
1047       if (c->rhs.type == DEREF)
1048         c->rhs.var = to;
1049       else if (c->lhs.type == DEREF)
1050         c->lhs.var = to;
1051       else
1052         c->rhs.var = to;
1053     }
1054   constraint_set_union (&graph->complex[to], &graph->complex[from]);
1055   VEC_free (constraint_t, heap, graph->complex[from]);
1056   graph->complex[from] = NULL;
1057 }
1058
1059
1060 /* Remove edges involving NODE from GRAPH.  */
1061
1062 static void
1063 clear_edges_for_node (constraint_graph_t graph, unsigned int node)
1064 {
1065   if (graph->succs[node])
1066     BITMAP_FREE (graph->succs[node]);
1067 }
1068
1069 /* Merge GRAPH nodes FROM and TO into node TO.  */
1070
1071 static void
1072 merge_graph_nodes (constraint_graph_t graph, unsigned int to,
1073                    unsigned int from)
1074 {
1075   if (graph->indirect_cycles[from] != -1)
1076     {
1077       /* If we have indirect cycles with the from node, and we have
1078          none on the to node, the to node has indirect cycles from the
1079          from node now that they are unified.
1080          If indirect cycles exist on both, unify the nodes that they
1081          are in a cycle with, since we know they are in a cycle with
1082          each other.  */
1083       if (graph->indirect_cycles[to] == -1)
1084         graph->indirect_cycles[to] = graph->indirect_cycles[from];
1085     }
1086
1087   /* Merge all the successor edges.  */
1088   if (graph->succs[from])
1089     {
1090       if (!graph->succs[to])
1091         graph->succs[to] = BITMAP_ALLOC (&pta_obstack);
1092       bitmap_ior_into (graph->succs[to],
1093                        graph->succs[from]);
1094     }
1095
1096   clear_edges_for_node (graph, from);
1097 }
1098
1099
1100 /* Add an indirect graph edge to GRAPH, going from TO to FROM if
1101    it doesn't exist in the graph already.  */
1102
1103 static void
1104 add_implicit_graph_edge (constraint_graph_t graph, unsigned int to,
1105                          unsigned int from)
1106 {
1107   if (to == from)
1108     return;
1109
1110   if (!graph->implicit_preds[to])
1111     graph->implicit_preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1112
1113   if (bitmap_set_bit (graph->implicit_preds[to], from))
1114     stats.num_implicit_edges++;
1115 }
1116
1117 /* Add a predecessor graph edge to GRAPH, going from TO to FROM if
1118    it doesn't exist in the graph already.
1119    Return false if the edge already existed, true otherwise.  */
1120
1121 static void
1122 add_pred_graph_edge (constraint_graph_t graph, unsigned int to,
1123                      unsigned int from)
1124 {
1125   if (!graph->preds[to])
1126     graph->preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1127   bitmap_set_bit (graph->preds[to], from);
1128 }
1129
1130 /* Add a graph edge to GRAPH, going from FROM to TO if
1131    it doesn't exist in the graph already.
1132    Return false if the edge already existed, true otherwise.  */
1133
1134 static bool
1135 add_graph_edge (constraint_graph_t graph, unsigned int to,
1136                 unsigned int from)
1137 {
1138   if (to == from)
1139     {
1140       return false;
1141     }
1142   else
1143     {
1144       bool r = false;
1145
1146       if (!graph->succs[from])
1147         graph->succs[from] = BITMAP_ALLOC (&pta_obstack);
1148       if (bitmap_set_bit (graph->succs[from], to))
1149         {
1150           r = true;
1151           if (to < FIRST_REF_NODE && from < FIRST_REF_NODE)
1152             stats.num_edges++;
1153         }
1154       return r;
1155     }
1156 }
1157
1158
1159 /* Return true if {DEST.SRC} is an existing graph edge in GRAPH.  */
1160
1161 static bool
1162 valid_graph_edge (constraint_graph_t graph, unsigned int src,
1163                   unsigned int dest)
1164 {
1165   return (graph->succs[dest]
1166           && bitmap_bit_p (graph->succs[dest], src));
1167 }
1168
1169 /* Initialize the constraint graph structure to contain SIZE nodes.  */
1170
1171 static void
1172 init_graph (unsigned int size)
1173 {
1174   unsigned int j;
1175
1176   graph = XCNEW (struct constraint_graph);
1177   graph->size = size;
1178   graph->succs = XCNEWVEC (bitmap, graph->size);
1179   graph->indirect_cycles = XNEWVEC (int, graph->size);
1180   graph->rep = XNEWVEC (unsigned int, graph->size);
1181   graph->complex = XCNEWVEC (VEC(constraint_t, heap) *, size);
1182   graph->pe = XCNEWVEC (unsigned int, graph->size);
1183   graph->pe_rep = XNEWVEC (int, graph->size);
1184
1185   for (j = 0; j < graph->size; j++)
1186     {
1187       graph->rep[j] = j;
1188       graph->pe_rep[j] = -1;
1189       graph->indirect_cycles[j] = -1;
1190     }
1191 }
1192
1193 /* Build the constraint graph, adding only predecessor edges right now.  */
1194
1195 static void
1196 build_pred_graph (void)
1197 {
1198   int i;
1199   constraint_t c;
1200   unsigned int j;
1201
1202   graph->implicit_preds = XCNEWVEC (bitmap, graph->size);
1203   graph->preds = XCNEWVEC (bitmap, graph->size);
1204   graph->pointer_label = XCNEWVEC (unsigned int, graph->size);
1205   graph->loc_label = XCNEWVEC (unsigned int, graph->size);
1206   graph->pointed_by = XCNEWVEC (bitmap, graph->size);
1207   graph->points_to = XCNEWVEC (bitmap, graph->size);
1208   graph->eq_rep = XNEWVEC (int, graph->size);
1209   graph->direct_nodes = sbitmap_alloc (graph->size);
1210   graph->address_taken = BITMAP_ALLOC (&predbitmap_obstack);
1211   sbitmap_zero (graph->direct_nodes);
1212
1213   for (j = 0; j < FIRST_REF_NODE; j++)
1214     {
1215       if (!get_varinfo (j)->is_special_var)
1216         SET_BIT (graph->direct_nodes, j);
1217     }
1218
1219   for (j = 0; j < graph->size; j++)
1220     graph->eq_rep[j] = -1;
1221
1222   for (j = 0; j < VEC_length (varinfo_t, varmap); j++)
1223     graph->indirect_cycles[j] = -1;
1224
1225   FOR_EACH_VEC_ELT (constraint_t, constraints, i, c)
1226     {
1227       struct constraint_expr lhs = c->lhs;
1228       struct constraint_expr rhs = c->rhs;
1229       unsigned int lhsvar = lhs.var;
1230       unsigned int rhsvar = rhs.var;
1231
1232       if (lhs.type == DEREF)
1233         {
1234           /* *x = y.  */
1235           if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1236             add_pred_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1237         }
1238       else if (rhs.type == DEREF)
1239         {
1240           /* x = *y */
1241           if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1242             add_pred_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1243           else
1244             RESET_BIT (graph->direct_nodes, lhsvar);
1245         }
1246       else if (rhs.type == ADDRESSOF)
1247         {
1248           varinfo_t v;
1249
1250           /* x = &y */
1251           if (graph->points_to[lhsvar] == NULL)
1252             graph->points_to[lhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1253           bitmap_set_bit (graph->points_to[lhsvar], rhsvar);
1254
1255           if (graph->pointed_by[rhsvar] == NULL)
1256             graph->pointed_by[rhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1257           bitmap_set_bit (graph->pointed_by[rhsvar], lhsvar);
1258
1259           /* Implicitly, *x = y */
1260           add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1261
1262           /* All related variables are no longer direct nodes.  */
1263           RESET_BIT (graph->direct_nodes, rhsvar);
1264           v = get_varinfo (rhsvar);
1265           if (!v->is_full_var)
1266             {
1267               v = lookup_vi_for_tree (v->decl);
1268               do
1269                 {
1270                   RESET_BIT (graph->direct_nodes, v->id);
1271                   v = v->next;
1272                 }
1273               while (v != NULL);
1274             }
1275           bitmap_set_bit (graph->address_taken, rhsvar);
1276         }
1277       else if (lhsvar > anything_id
1278                && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1279         {
1280           /* x = y */
1281           add_pred_graph_edge (graph, lhsvar, rhsvar);
1282           /* Implicitly, *x = *y */
1283           add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar,
1284                                    FIRST_REF_NODE + rhsvar);
1285         }
1286       else if (lhs.offset != 0 || rhs.offset != 0)
1287         {
1288           if (rhs.offset != 0)
1289             RESET_BIT (graph->direct_nodes, lhs.var);
1290           else if (lhs.offset != 0)
1291             RESET_BIT (graph->direct_nodes, rhs.var);
1292         }
1293     }
1294 }
1295
1296 /* Build the constraint graph, adding successor edges.  */
1297
1298 static void
1299 build_succ_graph (void)
1300 {
1301   unsigned i, t;
1302   constraint_t c;
1303
1304   FOR_EACH_VEC_ELT (constraint_t, constraints, i, c)
1305     {
1306       struct constraint_expr lhs;
1307       struct constraint_expr rhs;
1308       unsigned int lhsvar;
1309       unsigned int rhsvar;
1310
1311       if (!c)
1312         continue;
1313
1314       lhs = c->lhs;
1315       rhs = c->rhs;
1316       lhsvar = find (lhs.var);
1317       rhsvar = find (rhs.var);
1318
1319       if (lhs.type == DEREF)
1320         {
1321           if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1322             add_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1323         }
1324       else if (rhs.type == DEREF)
1325         {
1326           if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1327             add_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1328         }
1329       else if (rhs.type == ADDRESSOF)
1330         {
1331           /* x = &y */
1332           gcc_assert (find (rhs.var) == rhs.var);
1333           bitmap_set_bit (get_varinfo (lhsvar)->solution, rhsvar);
1334         }
1335       else if (lhsvar > anything_id
1336                && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1337         {
1338           add_graph_edge (graph, lhsvar, rhsvar);
1339         }
1340     }
1341
1342   /* Add edges from STOREDANYTHING to all non-direct nodes that can
1343      receive pointers.  */
1344   t = find (storedanything_id);
1345   for (i = integer_id + 1; i < FIRST_REF_NODE; ++i)
1346     {
1347       if (!TEST_BIT (graph->direct_nodes, i)
1348           && get_varinfo (i)->may_have_pointers)
1349         add_graph_edge (graph, find (i), t);
1350     }
1351
1352   /* Everything stored to ANYTHING also potentially escapes.  */
1353   add_graph_edge (graph, find (escaped_id), t);
1354 }
1355
1356
1357 /* Changed variables on the last iteration.  */
1358 static bitmap changed;
1359
1360 /* Strongly Connected Component visitation info.  */
1361
1362 struct scc_info
1363 {
1364   sbitmap visited;
1365   sbitmap deleted;
1366   unsigned int *dfs;
1367   unsigned int *node_mapping;
1368   int current_index;
1369   VEC(unsigned,heap) *scc_stack;
1370 };
1371
1372
1373 /* Recursive routine to find strongly connected components in GRAPH.
1374    SI is the SCC info to store the information in, and N is the id of current
1375    graph node we are processing.
1376
1377    This is Tarjan's strongly connected component finding algorithm, as
1378    modified by Nuutila to keep only non-root nodes on the stack.
1379    The algorithm can be found in "On finding the strongly connected
1380    connected components in a directed graph" by Esko Nuutila and Eljas
1381    Soisalon-Soininen, in Information Processing Letters volume 49,
1382    number 1, pages 9-14.  */
1383
1384 static void
1385 scc_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1386 {
1387   unsigned int i;
1388   bitmap_iterator bi;
1389   unsigned int my_dfs;
1390
1391   SET_BIT (si->visited, n);
1392   si->dfs[n] = si->current_index ++;
1393   my_dfs = si->dfs[n];
1394
1395   /* Visit all the successors.  */
1396   EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[n], 0, i, bi)
1397     {
1398       unsigned int w;
1399
1400       if (i > LAST_REF_NODE)
1401         break;
1402
1403       w = find (i);
1404       if (TEST_BIT (si->deleted, w))
1405         continue;
1406
1407       if (!TEST_BIT (si->visited, w))
1408         scc_visit (graph, si, w);
1409       {
1410         unsigned int t = find (w);
1411         unsigned int nnode = find (n);
1412         gcc_assert (nnode == n);
1413
1414         if (si->dfs[t] < si->dfs[nnode])
1415           si->dfs[n] = si->dfs[t];
1416       }
1417     }
1418
1419   /* See if any components have been identified.  */
1420   if (si->dfs[n] == my_dfs)
1421     {
1422       if (VEC_length (unsigned, si->scc_stack) > 0
1423           && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
1424         {
1425           bitmap scc = BITMAP_ALLOC (NULL);
1426           unsigned int lowest_node;
1427           bitmap_iterator bi;
1428
1429           bitmap_set_bit (scc, n);
1430
1431           while (VEC_length (unsigned, si->scc_stack) != 0
1432                  && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
1433             {
1434               unsigned int w = VEC_pop (unsigned, si->scc_stack);
1435
1436               bitmap_set_bit (scc, w);
1437             }
1438
1439           lowest_node = bitmap_first_set_bit (scc);
1440           gcc_assert (lowest_node < FIRST_REF_NODE);
1441
1442           /* Collapse the SCC nodes into a single node, and mark the
1443              indirect cycles.  */
1444           EXECUTE_IF_SET_IN_BITMAP (scc, 0, i, bi)
1445             {
1446               if (i < FIRST_REF_NODE)
1447                 {
1448                   if (unite (lowest_node, i))
1449                     unify_nodes (graph, lowest_node, i, false);
1450                 }
1451               else
1452                 {
1453                   unite (lowest_node, i);
1454                   graph->indirect_cycles[i - FIRST_REF_NODE] = lowest_node;
1455                 }
1456             }
1457         }
1458       SET_BIT (si->deleted, n);
1459     }
1460   else
1461     VEC_safe_push (unsigned, heap, si->scc_stack, n);
1462 }
1463
1464 /* Unify node FROM into node TO, updating the changed count if
1465    necessary when UPDATE_CHANGED is true.  */
1466
1467 static void
1468 unify_nodes (constraint_graph_t graph, unsigned int to, unsigned int from,
1469              bool update_changed)
1470 {
1471
1472   gcc_assert (to != from && find (to) == to);
1473   if (dump_file && (dump_flags & TDF_DETAILS))
1474     fprintf (dump_file, "Unifying %s to %s\n",
1475              get_varinfo (from)->name,
1476              get_varinfo (to)->name);
1477
1478   if (update_changed)
1479     stats.unified_vars_dynamic++;
1480   else
1481     stats.unified_vars_static++;
1482
1483   merge_graph_nodes (graph, to, from);
1484   merge_node_constraints (graph, to, from);
1485
1486   /* Mark TO as changed if FROM was changed. If TO was already marked
1487      as changed, decrease the changed count.  */
1488
1489   if (update_changed
1490       && bitmap_bit_p (changed, from))
1491     {
1492       bitmap_clear_bit (changed, from);
1493       bitmap_set_bit (changed, to);
1494     }
1495   if (get_varinfo (from)->solution)
1496     {
1497       /* If the solution changes because of the merging, we need to mark
1498          the variable as changed.  */
1499       if (bitmap_ior_into (get_varinfo (to)->solution,
1500                            get_varinfo (from)->solution))
1501         {
1502           if (update_changed)
1503             bitmap_set_bit (changed, to);
1504         }
1505
1506       BITMAP_FREE (get_varinfo (from)->solution);
1507       BITMAP_FREE (get_varinfo (from)->oldsolution);
1508
1509       if (stats.iterations > 0)
1510         {
1511           BITMAP_FREE (get_varinfo (to)->oldsolution);
1512           get_varinfo (to)->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
1513         }
1514     }
1515   if (valid_graph_edge (graph, to, to))
1516     {
1517       if (graph->succs[to])
1518         bitmap_clear_bit (graph->succs[to], to);
1519     }
1520 }
1521
1522 /* Information needed to compute the topological ordering of a graph.  */
1523
1524 struct topo_info
1525 {
1526   /* sbitmap of visited nodes.  */
1527   sbitmap visited;
1528   /* Array that stores the topological order of the graph, *in
1529      reverse*.  */
1530   VEC(unsigned,heap) *topo_order;
1531 };
1532
1533
1534 /* Initialize and return a topological info structure.  */
1535
1536 static struct topo_info *
1537 init_topo_info (void)
1538 {
1539   size_t size = graph->size;
1540   struct topo_info *ti = XNEW (struct topo_info);
1541   ti->visited = sbitmap_alloc (size);
1542   sbitmap_zero (ti->visited);
1543   ti->topo_order = VEC_alloc (unsigned, heap, 1);
1544   return ti;
1545 }
1546
1547
1548 /* Free the topological sort info pointed to by TI.  */
1549
1550 static void
1551 free_topo_info (struct topo_info *ti)
1552 {
1553   sbitmap_free (ti->visited);
1554   VEC_free (unsigned, heap, ti->topo_order);
1555   free (ti);
1556 }
1557
1558 /* Visit the graph in topological order, and store the order in the
1559    topo_info structure.  */
1560
1561 static void
1562 topo_visit (constraint_graph_t graph, struct topo_info *ti,
1563             unsigned int n)
1564 {
1565   bitmap_iterator bi;
1566   unsigned int j;
1567
1568   SET_BIT (ti->visited, n);
1569
1570   if (graph->succs[n])
1571     EXECUTE_IF_SET_IN_BITMAP (graph->succs[n], 0, j, bi)
1572       {
1573         if (!TEST_BIT (ti->visited, j))
1574           topo_visit (graph, ti, j);
1575       }
1576
1577   VEC_safe_push (unsigned, heap, ti->topo_order, n);
1578 }
1579
1580 /* Process a constraint C that represents x = *(y + off), using DELTA as the
1581    starting solution for y.  */
1582
1583 static void
1584 do_sd_constraint (constraint_graph_t graph, constraint_t c,
1585                   bitmap delta)
1586 {
1587   unsigned int lhs = c->lhs.var;
1588   bool flag = false;
1589   bitmap sol = get_varinfo (lhs)->solution;
1590   unsigned int j;
1591   bitmap_iterator bi;
1592   HOST_WIDE_INT roffset = c->rhs.offset;
1593
1594   /* Our IL does not allow this.  */
1595   gcc_assert (c->lhs.offset == 0);
1596
1597   /* If the solution of Y contains anything it is good enough to transfer
1598      this to the LHS.  */
1599   if (bitmap_bit_p (delta, anything_id))
1600     {
1601       flag |= bitmap_set_bit (sol, anything_id);
1602       goto done;
1603     }
1604
1605   /* If we do not know at with offset the rhs is dereferenced compute
1606      the reachability set of DELTA, conservatively assuming it is
1607      dereferenced at all valid offsets.  */
1608   if (roffset == UNKNOWN_OFFSET)
1609     {
1610       solution_set_expand (delta, delta);
1611       /* No further offset processing is necessary.  */
1612       roffset = 0;
1613     }
1614
1615   /* For each variable j in delta (Sol(y)), add
1616      an edge in the graph from j to x, and union Sol(j) into Sol(x).  */
1617   EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1618     {
1619       varinfo_t v = get_varinfo (j);
1620       HOST_WIDE_INT fieldoffset = v->offset + roffset;
1621       unsigned int t;
1622
1623       if (v->is_full_var)
1624         fieldoffset = v->offset;
1625       else if (roffset != 0)
1626         v = first_vi_for_offset (v, fieldoffset);
1627       /* If the access is outside of the variable we can ignore it.  */
1628       if (!v)
1629         continue;
1630
1631       do
1632         {
1633           t = find (v->id);
1634
1635           /* Adding edges from the special vars is pointless.
1636              They don't have sets that can change.  */
1637           if (get_varinfo (t)->is_special_var)
1638             flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1639           /* Merging the solution from ESCAPED needlessly increases
1640              the set.  Use ESCAPED as representative instead.  */
1641           else if (v->id == escaped_id)
1642             flag |= bitmap_set_bit (sol, escaped_id);
1643           else if (v->may_have_pointers
1644                    && add_graph_edge (graph, lhs, t))
1645             flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1646
1647           /* If the variable is not exactly at the requested offset
1648              we have to include the next one.  */
1649           if (v->offset == (unsigned HOST_WIDE_INT)fieldoffset
1650               || v->next == NULL)
1651             break;
1652
1653           v = v->next;
1654           fieldoffset = v->offset;
1655         }
1656       while (1);
1657     }
1658
1659 done:
1660   /* If the LHS solution changed, mark the var as changed.  */
1661   if (flag)
1662     {
1663       get_varinfo (lhs)->solution = sol;
1664       bitmap_set_bit (changed, lhs);
1665     }
1666 }
1667
1668 /* Process a constraint C that represents *(x + off) = y using DELTA
1669    as the starting solution for x.  */
1670
1671 static void
1672 do_ds_constraint (constraint_t c, bitmap delta)
1673 {
1674   unsigned int rhs = c->rhs.var;
1675   bitmap sol = get_varinfo (rhs)->solution;
1676   unsigned int j;
1677   bitmap_iterator bi;
1678   HOST_WIDE_INT loff = c->lhs.offset;
1679   bool escaped_p = false;
1680
1681   /* Our IL does not allow this.  */
1682   gcc_assert (c->rhs.offset == 0);
1683
1684   /* If the solution of y contains ANYTHING simply use the ANYTHING
1685      solution.  This avoids needlessly increasing the points-to sets.  */
1686   if (bitmap_bit_p (sol, anything_id))
1687     sol = get_varinfo (find (anything_id))->solution;
1688
1689   /* If the solution for x contains ANYTHING we have to merge the
1690      solution of y into all pointer variables which we do via
1691      STOREDANYTHING.  */
1692   if (bitmap_bit_p (delta, anything_id))
1693     {
1694       unsigned t = find (storedanything_id);
1695       if (add_graph_edge (graph, t, rhs))
1696         {
1697           if (bitmap_ior_into (get_varinfo (t)->solution, sol))
1698             bitmap_set_bit (changed, t);
1699         }
1700       return;
1701     }
1702
1703   /* If we do not know at with offset the rhs is dereferenced compute
1704      the reachability set of DELTA, conservatively assuming it is
1705      dereferenced at all valid offsets.  */
1706   if (loff == UNKNOWN_OFFSET)
1707     {
1708       solution_set_expand (delta, delta);
1709       loff = 0;
1710     }
1711
1712   /* For each member j of delta (Sol(x)), add an edge from y to j and
1713      union Sol(y) into Sol(j) */
1714   EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1715     {
1716       varinfo_t v = get_varinfo (j);
1717       unsigned int t;
1718       HOST_WIDE_INT fieldoffset = v->offset + loff;
1719
1720       if (v->is_full_var)
1721         fieldoffset = v->offset;
1722       else if (loff != 0)
1723         v = first_vi_for_offset (v, fieldoffset);
1724       /* If the access is outside of the variable we can ignore it.  */
1725       if (!v)
1726         continue;
1727
1728       do
1729         {
1730           if (v->may_have_pointers)
1731             {
1732               /* If v is a global variable then this is an escape point.  */
1733               if (v->is_global_var
1734                   && !escaped_p)
1735                 {
1736                   t = find (escaped_id);
1737                   if (add_graph_edge (graph, t, rhs)
1738                       && bitmap_ior_into (get_varinfo (t)->solution, sol))
1739                     bitmap_set_bit (changed, t);
1740                   /* Enough to let rhs escape once.  */
1741                   escaped_p = true;
1742                 }
1743
1744               if (v->is_special_var)
1745                 break;
1746
1747               t = find (v->id);
1748               if (add_graph_edge (graph, t, rhs)
1749                   && bitmap_ior_into (get_varinfo (t)->solution, sol))
1750                 bitmap_set_bit (changed, t);
1751             }
1752
1753           /* If the variable is not exactly at the requested offset
1754              we have to include the next one.  */
1755           if (v->offset == (unsigned HOST_WIDE_INT)fieldoffset
1756               || v->next == NULL)
1757             break;
1758
1759           v = v->next;
1760           fieldoffset = v->offset;
1761         }
1762       while (1);
1763     }
1764 }
1765
1766 /* Handle a non-simple (simple meaning requires no iteration),
1767    constraint (IE *x = &y, x = *y, *x = y, and x = y with offsets involved).  */
1768
1769 static void
1770 do_complex_constraint (constraint_graph_t graph, constraint_t c, bitmap delta)
1771 {
1772   if (c->lhs.type == DEREF)
1773     {
1774       if (c->rhs.type == ADDRESSOF)
1775         {
1776           gcc_unreachable();
1777         }
1778       else
1779         {
1780           /* *x = y */
1781           do_ds_constraint (c, delta);
1782         }
1783     }
1784   else if (c->rhs.type == DEREF)
1785     {
1786       /* x = *y */
1787       if (!(get_varinfo (c->lhs.var)->is_special_var))
1788         do_sd_constraint (graph, c, delta);
1789     }
1790   else
1791     {
1792       bitmap tmp;
1793       bitmap solution;
1794       bool flag = false;
1795
1796       gcc_assert (c->rhs.type == SCALAR && c->lhs.type == SCALAR);
1797       solution = get_varinfo (c->rhs.var)->solution;
1798       tmp = get_varinfo (c->lhs.var)->solution;
1799
1800       flag = set_union_with_increment (tmp, solution, c->rhs.offset);
1801
1802       if (flag)
1803         {
1804           get_varinfo (c->lhs.var)->solution = tmp;
1805           bitmap_set_bit (changed, c->lhs.var);
1806         }
1807     }
1808 }
1809
1810 /* Initialize and return a new SCC info structure.  */
1811
1812 static struct scc_info *
1813 init_scc_info (size_t size)
1814 {
1815   struct scc_info *si = XNEW (struct scc_info);
1816   size_t i;
1817
1818   si->current_index = 0;
1819   si->visited = sbitmap_alloc (size);
1820   sbitmap_zero (si->visited);
1821   si->deleted = sbitmap_alloc (size);
1822   sbitmap_zero (si->deleted);
1823   si->node_mapping = XNEWVEC (unsigned int, size);
1824   si->dfs = XCNEWVEC (unsigned int, size);
1825
1826   for (i = 0; i < size; i++)
1827     si->node_mapping[i] = i;
1828
1829   si->scc_stack = VEC_alloc (unsigned, heap, 1);
1830   return si;
1831 }
1832
1833 /* Free an SCC info structure pointed to by SI */
1834
1835 static void
1836 free_scc_info (struct scc_info *si)
1837 {
1838   sbitmap_free (si->visited);
1839   sbitmap_free (si->deleted);
1840   free (si->node_mapping);
1841   free (si->dfs);
1842   VEC_free (unsigned, heap, si->scc_stack);
1843   free (si);
1844 }
1845
1846
1847 /* Find indirect cycles in GRAPH that occur, using strongly connected
1848    components, and note them in the indirect cycles map.
1849
1850    This technique comes from Ben Hardekopf and Calvin Lin,
1851    "It Pays to be Lazy: Fast and Accurate Pointer Analysis for Millions of
1852    Lines of Code", submitted to PLDI 2007.  */
1853
1854 static void
1855 find_indirect_cycles (constraint_graph_t graph)
1856 {
1857   unsigned int i;
1858   unsigned int size = graph->size;
1859   struct scc_info *si = init_scc_info (size);
1860
1861   for (i = 0; i < MIN (LAST_REF_NODE, size); i ++ )
1862     if (!TEST_BIT (si->visited, i) && find (i) == i)
1863       scc_visit (graph, si, i);
1864
1865   free_scc_info (si);
1866 }
1867
1868 /* Compute a topological ordering for GRAPH, and store the result in the
1869    topo_info structure TI.  */
1870
1871 static void
1872 compute_topo_order (constraint_graph_t graph,
1873                     struct topo_info *ti)
1874 {
1875   unsigned int i;
1876   unsigned int size = graph->size;
1877
1878   for (i = 0; i != size; ++i)
1879     if (!TEST_BIT (ti->visited, i) && find (i) == i)
1880       topo_visit (graph, ti, i);
1881 }
1882
1883 /* Structure used to for hash value numbering of pointer equivalence
1884    classes.  */
1885
1886 typedef struct equiv_class_label
1887 {
1888   hashval_t hashcode;
1889   unsigned int equivalence_class;
1890   bitmap labels;
1891 } *equiv_class_label_t;
1892 typedef const struct equiv_class_label *const_equiv_class_label_t;
1893
1894 /* A hashtable for mapping a bitmap of labels->pointer equivalence
1895    classes.  */
1896 static htab_t pointer_equiv_class_table;
1897
1898 /* A hashtable for mapping a bitmap of labels->location equivalence
1899    classes.  */
1900 static htab_t location_equiv_class_table;
1901
1902 /* Hash function for a equiv_class_label_t */
1903
1904 static hashval_t
1905 equiv_class_label_hash (const void *p)
1906 {
1907   const_equiv_class_label_t const ecl = (const_equiv_class_label_t) p;
1908   return ecl->hashcode;
1909 }
1910
1911 /* Equality function for two equiv_class_label_t's.  */
1912
1913 static int
1914 equiv_class_label_eq (const void *p1, const void *p2)
1915 {
1916   const_equiv_class_label_t const eql1 = (const_equiv_class_label_t) p1;
1917   const_equiv_class_label_t const eql2 = (const_equiv_class_label_t) p2;
1918   return (eql1->hashcode == eql2->hashcode
1919           && bitmap_equal_p (eql1->labels, eql2->labels));
1920 }
1921
1922 /* Lookup a equivalence class in TABLE by the bitmap of LABELS it
1923    contains.  */
1924
1925 static unsigned int
1926 equiv_class_lookup (htab_t table, bitmap labels)
1927 {
1928   void **slot;
1929   struct equiv_class_label ecl;
1930
1931   ecl.labels = labels;
1932   ecl.hashcode = bitmap_hash (labels);
1933
1934   slot = htab_find_slot_with_hash (table, &ecl,
1935                                    ecl.hashcode, NO_INSERT);
1936   if (!slot)
1937     return 0;
1938   else
1939     return ((equiv_class_label_t) *slot)->equivalence_class;
1940 }
1941
1942
1943 /* Add an equivalence class named EQUIVALENCE_CLASS with labels LABELS
1944    to TABLE.  */
1945
1946 static void
1947 equiv_class_add (htab_t table, unsigned int equivalence_class,
1948                  bitmap labels)
1949 {
1950   void **slot;
1951   equiv_class_label_t ecl = XNEW (struct equiv_class_label);
1952
1953   ecl->labels = labels;
1954   ecl->equivalence_class = equivalence_class;
1955   ecl->hashcode = bitmap_hash (labels);
1956
1957   slot = htab_find_slot_with_hash (table, ecl,
1958                                    ecl->hashcode, INSERT);
1959   gcc_assert (!*slot);
1960   *slot = (void *) ecl;
1961 }
1962
1963 /* Perform offline variable substitution.
1964
1965    This is a worst case quadratic time way of identifying variables
1966    that must have equivalent points-to sets, including those caused by
1967    static cycles, and single entry subgraphs, in the constraint graph.
1968
1969    The technique is described in "Exploiting Pointer and Location
1970    Equivalence to Optimize Pointer Analysis. In the 14th International
1971    Static Analysis Symposium (SAS), August 2007."  It is known as the
1972    "HU" algorithm, and is equivalent to value numbering the collapsed
1973    constraint graph including evaluating unions.
1974
1975    The general method of finding equivalence classes is as follows:
1976    Add fake nodes (REF nodes) and edges for *a = b and a = *b constraints.
1977    Initialize all non-REF nodes to be direct nodes.
1978    For each constraint a = a U {b}, we set pts(a) = pts(a) u {fresh
1979    variable}
1980    For each constraint containing the dereference, we also do the same
1981    thing.
1982
1983    We then compute SCC's in the graph and unify nodes in the same SCC,
1984    including pts sets.
1985
1986    For each non-collapsed node x:
1987     Visit all unvisited explicit incoming edges.
1988     Ignoring all non-pointers, set pts(x) = Union of pts(a) for y
1989     where y->x.
1990     Lookup the equivalence class for pts(x).
1991      If we found one, equivalence_class(x) = found class.
1992      Otherwise, equivalence_class(x) = new class, and new_class is
1993     added to the lookup table.
1994
1995    All direct nodes with the same equivalence class can be replaced
1996    with a single representative node.
1997    All unlabeled nodes (label == 0) are not pointers and all edges
1998    involving them can be eliminated.
1999    We perform these optimizations during rewrite_constraints
2000
2001    In addition to pointer equivalence class finding, we also perform
2002    location equivalence class finding.  This is the set of variables
2003    that always appear together in points-to sets.  We use this to
2004    compress the size of the points-to sets.  */
2005
2006 /* Current maximum pointer equivalence class id.  */
2007 static int pointer_equiv_class;
2008
2009 /* Current maximum location equivalence class id.  */
2010 static int location_equiv_class;
2011
2012 /* Recursive routine to find strongly connected components in GRAPH,
2013    and label it's nodes with DFS numbers.  */
2014
2015 static void
2016 condense_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
2017 {
2018   unsigned int i;
2019   bitmap_iterator bi;
2020   unsigned int my_dfs;
2021
2022   gcc_assert (si->node_mapping[n] == n);
2023   SET_BIT (si->visited, n);
2024   si->dfs[n] = si->current_index ++;
2025   my_dfs = si->dfs[n];
2026
2027   /* Visit all the successors.  */
2028   EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
2029     {
2030       unsigned int w = si->node_mapping[i];
2031
2032       if (TEST_BIT (si->deleted, w))
2033         continue;
2034
2035       if (!TEST_BIT (si->visited, w))
2036         condense_visit (graph, si, w);
2037       {
2038         unsigned int t = si->node_mapping[w];
2039         unsigned int nnode = si->node_mapping[n];
2040         gcc_assert (nnode == n);
2041
2042         if (si->dfs[t] < si->dfs[nnode])
2043           si->dfs[n] = si->dfs[t];
2044       }
2045     }
2046
2047   /* Visit all the implicit predecessors.  */
2048   EXECUTE_IF_IN_NONNULL_BITMAP (graph->implicit_preds[n], 0, i, bi)
2049     {
2050       unsigned int w = si->node_mapping[i];
2051
2052       if (TEST_BIT (si->deleted, w))
2053         continue;
2054
2055       if (!TEST_BIT (si->visited, w))
2056         condense_visit (graph, si, w);
2057       {
2058         unsigned int t = si->node_mapping[w];
2059         unsigned int nnode = si->node_mapping[n];
2060         gcc_assert (nnode == n);
2061
2062         if (si->dfs[t] < si->dfs[nnode])
2063           si->dfs[n] = si->dfs[t];
2064       }
2065     }
2066
2067   /* See if any components have been identified.  */
2068   if (si->dfs[n] == my_dfs)
2069     {
2070       while (VEC_length (unsigned, si->scc_stack) != 0
2071              && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
2072         {
2073           unsigned int w = VEC_pop (unsigned, si->scc_stack);
2074           si->node_mapping[w] = n;
2075
2076           if (!TEST_BIT (graph->direct_nodes, w))
2077             RESET_BIT (graph->direct_nodes, n);
2078
2079           /* Unify our nodes.  */
2080           if (graph->preds[w])
2081             {
2082               if (!graph->preds[n])
2083                 graph->preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2084               bitmap_ior_into (graph->preds[n], graph->preds[w]);
2085             }
2086           if (graph->implicit_preds[w])
2087             {
2088               if (!graph->implicit_preds[n])
2089                 graph->implicit_preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2090               bitmap_ior_into (graph->implicit_preds[n],
2091                                graph->implicit_preds[w]);
2092             }
2093           if (graph->points_to[w])
2094             {
2095               if (!graph->points_to[n])
2096                 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2097               bitmap_ior_into (graph->points_to[n],
2098                                graph->points_to[w]);
2099             }
2100         }
2101       SET_BIT (si->deleted, n);
2102     }
2103   else
2104     VEC_safe_push (unsigned, heap, si->scc_stack, n);
2105 }
2106
2107 /* Label pointer equivalences.  */
2108
2109 static void
2110 label_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
2111 {
2112   unsigned int i;
2113   bitmap_iterator bi;
2114   SET_BIT (si->visited, n);
2115
2116   if (!graph->points_to[n])
2117     graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2118
2119   /* Label and union our incoming edges's points to sets.  */
2120   EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
2121     {
2122       unsigned int w = si->node_mapping[i];
2123       if (!TEST_BIT (si->visited, w))
2124         label_visit (graph, si, w);
2125
2126       /* Skip unused edges  */
2127       if (w == n || graph->pointer_label[w] == 0)
2128         continue;
2129
2130       if (graph->points_to[w])
2131         bitmap_ior_into(graph->points_to[n], graph->points_to[w]);
2132     }
2133   /* Indirect nodes get fresh variables.  */
2134   if (!TEST_BIT (graph->direct_nodes, n))
2135     bitmap_set_bit (graph->points_to[n], FIRST_REF_NODE + n);
2136
2137   if (!bitmap_empty_p (graph->points_to[n]))
2138     {
2139       unsigned int label = equiv_class_lookup (pointer_equiv_class_table,
2140                                                graph->points_to[n]);
2141       if (!label)
2142         {
2143           label = pointer_equiv_class++;
2144           equiv_class_add (pointer_equiv_class_table,
2145                            label, graph->points_to[n]);
2146         }
2147       graph->pointer_label[n] = label;
2148     }
2149 }
2150
2151 /* Perform offline variable substitution, discovering equivalence
2152    classes, and eliminating non-pointer variables.  */
2153
2154 static struct scc_info *
2155 perform_var_substitution (constraint_graph_t graph)
2156 {
2157   unsigned int i;
2158   unsigned int size = graph->size;
2159   struct scc_info *si = init_scc_info (size);
2160
2161   bitmap_obstack_initialize (&iteration_obstack);
2162   pointer_equiv_class_table = htab_create (511, equiv_class_label_hash,
2163                                            equiv_class_label_eq, free);
2164   location_equiv_class_table = htab_create (511, equiv_class_label_hash,
2165                                             equiv_class_label_eq, free);
2166   pointer_equiv_class = 1;
2167   location_equiv_class = 1;
2168
2169   /* Condense the nodes, which means to find SCC's, count incoming
2170      predecessors, and unite nodes in SCC's.  */
2171   for (i = 0; i < FIRST_REF_NODE; i++)
2172     if (!TEST_BIT (si->visited, si->node_mapping[i]))
2173       condense_visit (graph, si, si->node_mapping[i]);
2174
2175   sbitmap_zero (si->visited);
2176   /* Actually the label the nodes for pointer equivalences  */
2177   for (i = 0; i < FIRST_REF_NODE; i++)
2178     if (!TEST_BIT (si->visited, si->node_mapping[i]))
2179       label_visit (graph, si, si->node_mapping[i]);
2180
2181   /* Calculate location equivalence labels.  */
2182   for (i = 0; i < FIRST_REF_NODE; i++)
2183     {
2184       bitmap pointed_by;
2185       bitmap_iterator bi;
2186       unsigned int j;
2187       unsigned int label;
2188
2189       if (!graph->pointed_by[i])
2190         continue;
2191       pointed_by = BITMAP_ALLOC (&iteration_obstack);
2192
2193       /* Translate the pointed-by mapping for pointer equivalence
2194          labels.  */
2195       EXECUTE_IF_SET_IN_BITMAP (graph->pointed_by[i], 0, j, bi)
2196         {
2197           bitmap_set_bit (pointed_by,
2198                           graph->pointer_label[si->node_mapping[j]]);
2199         }
2200       /* The original pointed_by is now dead.  */
2201       BITMAP_FREE (graph->pointed_by[i]);
2202
2203       /* Look up the location equivalence label if one exists, or make
2204          one otherwise.  */
2205       label = equiv_class_lookup (location_equiv_class_table,
2206                                   pointed_by);
2207       if (label == 0)
2208         {
2209           label = location_equiv_class++;
2210           equiv_class_add (location_equiv_class_table,
2211                            label, pointed_by);
2212         }
2213       else
2214         {
2215           if (dump_file && (dump_flags & TDF_DETAILS))
2216             fprintf (dump_file, "Found location equivalence for node %s\n",
2217                      get_varinfo (i)->name);
2218           BITMAP_FREE (pointed_by);
2219         }
2220       graph->loc_label[i] = label;
2221
2222     }
2223
2224   if (dump_file && (dump_flags & TDF_DETAILS))
2225     for (i = 0; i < FIRST_REF_NODE; i++)
2226       {
2227         bool direct_node = TEST_BIT (graph->direct_nodes, i);
2228         fprintf (dump_file,
2229                  "Equivalence classes for %s node id %d:%s are pointer: %d"
2230                  ", location:%d\n",
2231                  direct_node ? "Direct node" : "Indirect node", i,
2232                  get_varinfo (i)->name,
2233                  graph->pointer_label[si->node_mapping[i]],
2234                  graph->loc_label[si->node_mapping[i]]);
2235       }
2236
2237   /* Quickly eliminate our non-pointer variables.  */
2238
2239   for (i = 0; i < FIRST_REF_NODE; i++)
2240     {
2241       unsigned int node = si->node_mapping[i];
2242
2243       if (graph->pointer_label[node] == 0)
2244         {
2245           if (dump_file && (dump_flags & TDF_DETAILS))
2246             fprintf (dump_file,
2247                      "%s is a non-pointer variable, eliminating edges.\n",
2248                      get_varinfo (node)->name);
2249           stats.nonpointer_vars++;
2250           clear_edges_for_node (graph, node);
2251         }
2252     }
2253
2254   return si;
2255 }
2256
2257 /* Free information that was only necessary for variable
2258    substitution.  */
2259
2260 static void
2261 free_var_substitution_info (struct scc_info *si)
2262 {
2263   free_scc_info (si);
2264   free (graph->pointer_label);
2265   free (graph->loc_label);
2266   free (graph->pointed_by);
2267   free (graph->points_to);
2268   free (graph->eq_rep);
2269   sbitmap_free (graph->direct_nodes);
2270   htab_delete (pointer_equiv_class_table);
2271   htab_delete (location_equiv_class_table);
2272   bitmap_obstack_release (&iteration_obstack);
2273 }
2274
2275 /* Return an existing node that is equivalent to NODE, which has
2276    equivalence class LABEL, if one exists.  Return NODE otherwise.  */
2277
2278 static unsigned int
2279 find_equivalent_node (constraint_graph_t graph,
2280                       unsigned int node, unsigned int label)
2281 {
2282   /* If the address version of this variable is unused, we can
2283      substitute it for anything else with the same label.
2284      Otherwise, we know the pointers are equivalent, but not the
2285      locations, and we can unite them later.  */
2286
2287   if (!bitmap_bit_p (graph->address_taken, node))
2288     {
2289       gcc_assert (label < graph->size);
2290
2291       if (graph->eq_rep[label] != -1)
2292         {
2293           /* Unify the two variables since we know they are equivalent.  */
2294           if (unite (graph->eq_rep[label], node))
2295             unify_nodes (graph, graph->eq_rep[label], node, false);
2296           return graph->eq_rep[label];
2297         }
2298       else
2299         {
2300           graph->eq_rep[label] = node;
2301           graph->pe_rep[label] = node;
2302         }
2303     }
2304   else
2305     {
2306       gcc_assert (label < graph->size);
2307       graph->pe[node] = label;
2308       if (graph->pe_rep[label] == -1)
2309         graph->pe_rep[label] = node;
2310     }
2311
2312   return node;
2313 }
2314
2315 /* Unite pointer equivalent but not location equivalent nodes in
2316    GRAPH.  This may only be performed once variable substitution is
2317    finished.  */
2318
2319 static void
2320 unite_pointer_equivalences (constraint_graph_t graph)
2321 {
2322   unsigned int i;
2323
2324   /* Go through the pointer equivalences and unite them to their
2325      representative, if they aren't already.  */
2326   for (i = 0; i < FIRST_REF_NODE; i++)
2327     {
2328       unsigned int label = graph->pe[i];
2329       if (label)
2330         {
2331           int label_rep = graph->pe_rep[label];
2332
2333           if (label_rep == -1)
2334             continue;
2335
2336           label_rep = find (label_rep);
2337           if (label_rep >= 0 && unite (label_rep, find (i)))
2338             unify_nodes (graph, label_rep, i, false);
2339         }
2340     }
2341 }
2342
2343 /* Move complex constraints to the GRAPH nodes they belong to.  */
2344
2345 static void
2346 move_complex_constraints (constraint_graph_t graph)
2347 {
2348   int i;
2349   constraint_t c;
2350
2351   FOR_EACH_VEC_ELT (constraint_t, constraints, i, c)
2352     {
2353       if (c)
2354         {
2355           struct constraint_expr lhs = c->lhs;
2356           struct constraint_expr rhs = c->rhs;
2357
2358           if (lhs.type == DEREF)
2359             {
2360               insert_into_complex (graph, lhs.var, c);
2361             }
2362           else if (rhs.type == DEREF)
2363             {
2364               if (!(get_varinfo (lhs.var)->is_special_var))
2365                 insert_into_complex (graph, rhs.var, c);
2366             }
2367           else if (rhs.type != ADDRESSOF && lhs.var > anything_id
2368                    && (lhs.offset != 0 || rhs.offset != 0))
2369             {
2370               insert_into_complex (graph, rhs.var, c);
2371             }
2372         }
2373     }
2374 }
2375
2376
2377 /* Optimize and rewrite complex constraints while performing
2378    collapsing of equivalent nodes.  SI is the SCC_INFO that is the
2379    result of perform_variable_substitution.  */
2380
2381 static void
2382 rewrite_constraints (constraint_graph_t graph,
2383                      struct scc_info *si)
2384 {
2385   int i;
2386   unsigned int j;
2387   constraint_t c;
2388
2389   for (j = 0; j < graph->size; j++)
2390     gcc_assert (find (j) == j);
2391
2392   FOR_EACH_VEC_ELT (constraint_t, constraints, i, c)
2393     {
2394       struct constraint_expr lhs = c->lhs;
2395       struct constraint_expr rhs = c->rhs;
2396       unsigned int lhsvar = find (lhs.var);
2397       unsigned int rhsvar = find (rhs.var);
2398       unsigned int lhsnode, rhsnode;
2399       unsigned int lhslabel, rhslabel;
2400
2401       lhsnode = si->node_mapping[lhsvar];
2402       rhsnode = si->node_mapping[rhsvar];
2403       lhslabel = graph->pointer_label[lhsnode];
2404       rhslabel = graph->pointer_label[rhsnode];
2405
2406       /* See if it is really a non-pointer variable, and if so, ignore
2407          the constraint.  */
2408       if (lhslabel == 0)
2409         {
2410           if (dump_file && (dump_flags & TDF_DETAILS))
2411             {
2412
2413               fprintf (dump_file, "%s is a non-pointer variable,"
2414                        "ignoring constraint:",
2415                        get_varinfo (lhs.var)->name);
2416               dump_constraint (dump_file, c);
2417               fprintf (dump_file, "\n");
2418             }
2419           VEC_replace (constraint_t, constraints, i, NULL);
2420           continue;
2421         }
2422
2423       if (rhslabel == 0)
2424         {
2425           if (dump_file && (dump_flags & TDF_DETAILS))
2426             {
2427
2428               fprintf (dump_file, "%s is a non-pointer variable,"
2429                        "ignoring constraint:",
2430                        get_varinfo (rhs.var)->name);
2431               dump_constraint (dump_file, c);
2432               fprintf (dump_file, "\n");
2433             }
2434           VEC_replace (constraint_t, constraints, i, NULL);
2435           continue;
2436         }
2437
2438       lhsvar = find_equivalent_node (graph, lhsvar, lhslabel);
2439       rhsvar = find_equivalent_node (graph, rhsvar, rhslabel);
2440       c->lhs.var = lhsvar;
2441       c->rhs.var = rhsvar;
2442
2443     }
2444 }
2445
2446 /* Eliminate indirect cycles involving NODE.  Return true if NODE was
2447    part of an SCC, false otherwise.  */
2448
2449 static bool
2450 eliminate_indirect_cycles (unsigned int node)
2451 {
2452   if (graph->indirect_cycles[node] != -1
2453       && !bitmap_empty_p (get_varinfo (node)->solution))
2454     {
2455       unsigned int i;
2456       VEC(unsigned,heap) *queue = NULL;
2457       int queuepos;
2458       unsigned int to = find (graph->indirect_cycles[node]);
2459       bitmap_iterator bi;
2460
2461       /* We can't touch the solution set and call unify_nodes
2462          at the same time, because unify_nodes is going to do
2463          bitmap unions into it. */
2464
2465       EXECUTE_IF_SET_IN_BITMAP (get_varinfo (node)->solution, 0, i, bi)
2466         {
2467           if (find (i) == i && i != to)
2468             {
2469               if (unite (to, i))
2470                 VEC_safe_push (unsigned, heap, queue, i);
2471             }
2472         }
2473
2474       for (queuepos = 0;
2475            VEC_iterate (unsigned, queue, queuepos, i);
2476            queuepos++)
2477         {
2478           unify_nodes (graph, to, i, true);
2479         }
2480       VEC_free (unsigned, heap, queue);
2481       return true;
2482     }
2483   return false;
2484 }
2485
2486 /* Solve the constraint graph GRAPH using our worklist solver.
2487    This is based on the PW* family of solvers from the "Efficient Field
2488    Sensitive Pointer Analysis for C" paper.
2489    It works by iterating over all the graph nodes, processing the complex
2490    constraints and propagating the copy constraints, until everything stops
2491    changed.  This corresponds to steps 6-8 in the solving list given above.  */
2492
2493 static void
2494 solve_graph (constraint_graph_t graph)
2495 {
2496   unsigned int size = graph->size;
2497   unsigned int i;
2498   bitmap pts;
2499
2500   changed = BITMAP_ALLOC (NULL);
2501
2502   /* Mark all initial non-collapsed nodes as changed.  */
2503   for (i = 0; i < size; i++)
2504     {
2505       varinfo_t ivi = get_varinfo (i);
2506       if (find (i) == i && !bitmap_empty_p (ivi->solution)
2507           && ((graph->succs[i] && !bitmap_empty_p (graph->succs[i]))
2508               || VEC_length (constraint_t, graph->complex[i]) > 0))
2509         bitmap_set_bit (changed, i);
2510     }
2511
2512   /* Allocate a bitmap to be used to store the changed bits.  */
2513   pts = BITMAP_ALLOC (&pta_obstack);
2514
2515   while (!bitmap_empty_p (changed))
2516     {
2517       unsigned int i;
2518       struct topo_info *ti = init_topo_info ();
2519       stats.iterations++;
2520
2521       bitmap_obstack_initialize (&iteration_obstack);
2522
2523       compute_topo_order (graph, ti);
2524
2525       while (VEC_length (unsigned, ti->topo_order) != 0)
2526         {
2527
2528           i = VEC_pop (unsigned, ti->topo_order);
2529
2530           /* If this variable is not a representative, skip it.  */
2531           if (find (i) != i)
2532             continue;
2533
2534           /* In certain indirect cycle cases, we may merge this
2535              variable to another.  */
2536           if (eliminate_indirect_cycles (i) && find (i) != i)
2537             continue;
2538
2539           /* If the node has changed, we need to process the
2540              complex constraints and outgoing edges again.  */
2541           if (bitmap_clear_bit (changed, i))
2542             {
2543               unsigned int j;
2544               constraint_t c;
2545               bitmap solution;
2546               VEC(constraint_t,heap) *complex = graph->complex[i];
2547               bool solution_empty;
2548
2549               /* Compute the changed set of solution bits.  */
2550               bitmap_and_compl (pts, get_varinfo (i)->solution,
2551                                 get_varinfo (i)->oldsolution);
2552
2553               if (bitmap_empty_p (pts))
2554                 continue;
2555
2556               bitmap_ior_into (get_varinfo (i)->oldsolution, pts);
2557
2558               solution = get_varinfo (i)->solution;
2559               solution_empty = bitmap_empty_p (solution);
2560
2561               /* Process the complex constraints */
2562               FOR_EACH_VEC_ELT (constraint_t, complex, j, c)
2563                 {
2564                   /* XXX: This is going to unsort the constraints in
2565                      some cases, which will occasionally add duplicate
2566                      constraints during unification.  This does not
2567                      affect correctness.  */
2568                   c->lhs.var = find (c->lhs.var);
2569                   c->rhs.var = find (c->rhs.var);
2570
2571                   /* The only complex constraint that can change our
2572                      solution to non-empty, given an empty solution,
2573                      is a constraint where the lhs side is receiving
2574                      some set from elsewhere.  */
2575                   if (!solution_empty || c->lhs.type != DEREF)
2576                     do_complex_constraint (graph, c, pts);
2577                 }
2578
2579               solution_empty = bitmap_empty_p (solution);
2580
2581               if (!solution_empty)
2582                 {
2583                   bitmap_iterator bi;
2584                   unsigned eff_escaped_id = find (escaped_id);
2585
2586                   /* Propagate solution to all successors.  */
2587                   EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i],
2588                                                 0, j, bi)
2589                     {
2590                       bitmap tmp;
2591                       bool flag;
2592
2593                       unsigned int to = find (j);
2594                       tmp = get_varinfo (to)->solution;
2595                       flag = false;
2596
2597                       /* Don't try to propagate to ourselves.  */
2598                       if (to == i)
2599                         continue;
2600
2601                       /* If we propagate from ESCAPED use ESCAPED as
2602                          placeholder.  */
2603                       if (i == eff_escaped_id)
2604                         flag = bitmap_set_bit (tmp, escaped_id);
2605                       else
2606                         flag = set_union_with_increment (tmp, pts, 0);
2607
2608                       if (flag)
2609                         {
2610                           get_varinfo (to)->solution = tmp;
2611                           bitmap_set_bit (changed, to);
2612                         }
2613                     }
2614                 }
2615             }
2616         }
2617       free_topo_info (ti);
2618       bitmap_obstack_release (&iteration_obstack);
2619     }
2620
2621   BITMAP_FREE (pts);
2622   BITMAP_FREE (changed);
2623   bitmap_obstack_release (&oldpta_obstack);
2624 }
2625
2626 /* Map from trees to variable infos.  */
2627 static struct pointer_map_t *vi_for_tree;
2628
2629
2630 /* Insert ID as the variable id for tree T in the vi_for_tree map.  */
2631
2632 static void
2633 insert_vi_for_tree (tree t, varinfo_t vi)
2634 {
2635   void **slot = pointer_map_insert (vi_for_tree, t);
2636   gcc_assert (vi);
2637   gcc_assert (*slot == NULL);
2638   *slot = vi;
2639 }
2640
2641 /* Find the variable info for tree T in VI_FOR_TREE.  If T does not
2642    exist in the map, return NULL, otherwise, return the varinfo we found.  */
2643
2644 static varinfo_t
2645 lookup_vi_for_tree (tree t)
2646 {
2647   void **slot = pointer_map_contains (vi_for_tree, t);
2648   if (slot == NULL)
2649     return NULL;
2650
2651   return (varinfo_t) *slot;
2652 }
2653
2654 /* Return a printable name for DECL  */
2655
2656 static const char *
2657 alias_get_name (tree decl)
2658 {
2659   const char *res;
2660   char *temp;
2661   int num_printed = 0;
2662
2663   if (DECL_ASSEMBLER_NAME_SET_P (decl))
2664     res = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));
2665   else
2666     res= get_name (decl);
2667   if (res != NULL)
2668     return res;
2669
2670   res = "NULL";
2671   if (!dump_file)
2672     return res;
2673
2674   if (TREE_CODE (decl) == SSA_NAME)
2675     {
2676       num_printed = asprintf (&temp, "%s_%u",
2677                               alias_get_name (SSA_NAME_VAR (decl)),
2678                               SSA_NAME_VERSION (decl));
2679     }
2680   else if (DECL_P (decl))
2681     {
2682       num_printed = asprintf (&temp, "D.%u", DECL_UID (decl));
2683     }
2684   if (num_printed > 0)
2685     {
2686       res = ggc_strdup (temp);
2687       free (temp);
2688     }
2689   return res;
2690 }
2691
2692 /* Find the variable id for tree T in the map.
2693    If T doesn't exist in the map, create an entry for it and return it.  */
2694
2695 static varinfo_t
2696 get_vi_for_tree (tree t)
2697 {
2698   void **slot = pointer_map_contains (vi_for_tree, t);
2699   if (slot == NULL)
2700     return get_varinfo (create_variable_info_for (t, alias_get_name (t)));
2701
2702   return (varinfo_t) *slot;
2703 }
2704
2705 /* Get a scalar constraint expression for a new temporary variable.  */
2706
2707 static struct constraint_expr
2708 new_scalar_tmp_constraint_exp (const char *name)
2709 {
2710   struct constraint_expr tmp;
2711   varinfo_t vi;
2712
2713   vi = new_var_info (NULL_TREE, name);
2714   vi->offset = 0;
2715   vi->size = -1;
2716   vi->fullsize = -1;
2717   vi->is_full_var = 1;
2718
2719   tmp.var = vi->id;
2720   tmp.type = SCALAR;
2721   tmp.offset = 0;
2722
2723   return tmp;
2724 }
2725
2726 /* Get a constraint expression vector from an SSA_VAR_P node.
2727    If address_p is true, the result will be taken its address of.  */
2728
2729 static void
2730 get_constraint_for_ssa_var (tree t, VEC(ce_s, heap) **results, bool address_p)
2731 {
2732   struct constraint_expr cexpr;
2733   varinfo_t vi;
2734
2735   /* We allow FUNCTION_DECLs here even though it doesn't make much sense.  */
2736   gcc_assert (SSA_VAR_P (t) || DECL_P (t));
2737
2738   /* For parameters, get at the points-to set for the actual parm
2739      decl.  */
2740   if (TREE_CODE (t) == SSA_NAME
2741       && (TREE_CODE (SSA_NAME_VAR (t)) == PARM_DECL
2742           || TREE_CODE (SSA_NAME_VAR (t)) == RESULT_DECL)
2743       && SSA_NAME_IS_DEFAULT_DEF (t))
2744     {
2745       get_constraint_for_ssa_var (SSA_NAME_VAR (t), results, address_p);
2746       return;
2747     }
2748
2749   /* For global variables resort to the alias target.  */
2750   if (TREE_CODE (t) == VAR_DECL
2751       && (TREE_STATIC (t) || DECL_EXTERNAL (t)))
2752     {
2753       struct varpool_node *node = varpool_get_node (t);
2754       if (node && node->alias)
2755         {
2756           node = varpool_variable_node (node, NULL);
2757           t = node->decl;
2758         }
2759     }
2760
2761   vi = get_vi_for_tree (t);
2762   cexpr.var = vi->id;
2763   cexpr.type = SCALAR;
2764   cexpr.offset = 0;
2765   /* If we determine the result is "anything", and we know this is readonly,
2766      say it points to readonly memory instead.  */
2767   if (cexpr.var == anything_id && TREE_READONLY (t))
2768     {
2769       gcc_unreachable ();
2770       cexpr.type = ADDRESSOF;
2771       cexpr.var = readonly_id;
2772     }
2773
2774   /* If we are not taking the address of the constraint expr, add all
2775      sub-fiels of the variable as well.  */
2776   if (!address_p
2777       && !vi->is_full_var)
2778     {
2779       for (; vi; vi = vi->next)
2780         {
2781           cexpr.var = vi->id;
2782           VEC_safe_push (ce_s, heap, *results, &cexpr);
2783         }
2784       return;
2785     }
2786
2787   VEC_safe_push (ce_s, heap, *results, &cexpr);
2788 }
2789
2790 /* Process constraint T, performing various simplifications and then
2791    adding it to our list of overall constraints.  */
2792
2793 static void
2794 process_constraint (constraint_t t)
2795 {
2796   struct constraint_expr rhs = t->rhs;
2797   struct constraint_expr lhs = t->lhs;
2798
2799   gcc_assert (rhs.var < VEC_length (varinfo_t, varmap));
2800   gcc_assert (lhs.var < VEC_length (varinfo_t, varmap));
2801
2802   /* If we didn't get any useful constraint from the lhs we get
2803      &ANYTHING as fallback from get_constraint_for.  Deal with
2804      it here by turning it into *ANYTHING.  */
2805   if (lhs.type == ADDRESSOF
2806       && lhs.var == anything_id)
2807     lhs.type = DEREF;
2808
2809   /* ADDRESSOF on the lhs is invalid.  */
2810   gcc_assert (lhs.type != ADDRESSOF);
2811
2812   /* We shouldn't add constraints from things that cannot have pointers.
2813      It's not completely trivial to avoid in the callers, so do it here.  */
2814   if (rhs.type != ADDRESSOF
2815       && !get_varinfo (rhs.var)->may_have_pointers)
2816     return;
2817
2818   /* Likewise adding to the solution of a non-pointer var isn't useful.  */
2819   if (!get_varinfo (lhs.var)->may_have_pointers)
2820     return;
2821
2822   /* This can happen in our IR with things like n->a = *p */
2823   if (rhs.type == DEREF && lhs.type == DEREF && rhs.var != anything_id)
2824     {
2825       /* Split into tmp = *rhs, *lhs = tmp */
2826       struct constraint_expr tmplhs;
2827       tmplhs = new_scalar_tmp_constraint_exp ("doubledereftmp");
2828       process_constraint (new_constraint (tmplhs, rhs));
2829       process_constraint (new_constraint (lhs, tmplhs));
2830     }
2831   else if (rhs.type == ADDRESSOF && lhs.type == DEREF)
2832     {
2833       /* Split into tmp = &rhs, *lhs = tmp */
2834       struct constraint_expr tmplhs;
2835       tmplhs = new_scalar_tmp_constraint_exp ("derefaddrtmp");
2836       process_constraint (new_constraint (tmplhs, rhs));
2837       process_constraint (new_constraint (lhs, tmplhs));
2838     }
2839   else
2840     {
2841       gcc_assert (rhs.type != ADDRESSOF || rhs.offset == 0);
2842       VEC_safe_push (constraint_t, heap, constraints, t);
2843     }
2844 }
2845
2846
2847 /* Return the position, in bits, of FIELD_DECL from the beginning of its
2848    structure.  */
2849
2850 static HOST_WIDE_INT
2851 bitpos_of_field (const tree fdecl)
2852 {
2853   if (!host_integerp (DECL_FIELD_OFFSET (fdecl), 0)
2854       || !host_integerp (DECL_FIELD_BIT_OFFSET (fdecl), 0))
2855     return -1;
2856
2857   return (TREE_INT_CST_LOW (DECL_FIELD_OFFSET (fdecl)) * BITS_PER_UNIT
2858           + TREE_INT_CST_LOW (DECL_FIELD_BIT_OFFSET (fdecl)));
2859 }
2860
2861
2862 /* Get constraint expressions for offsetting PTR by OFFSET.  Stores the
2863    resulting constraint expressions in *RESULTS.  */
2864
2865 static void
2866 get_constraint_for_ptr_offset (tree ptr, tree offset,
2867                                VEC (ce_s, heap) **results)
2868 {
2869   struct constraint_expr c;
2870   unsigned int j, n;
2871   HOST_WIDE_INT rhsunitoffset, rhsoffset;
2872
2873   /* If we do not do field-sensitive PTA adding offsets to pointers
2874      does not change the points-to solution.  */
2875   if (!use_field_sensitive)
2876     {
2877       get_constraint_for_rhs (ptr, results);
2878       return;
2879     }
2880
2881   /* If the offset is not a non-negative integer constant that fits
2882      in a HOST_WIDE_INT, we have to fall back to a conservative
2883      solution which includes all sub-fields of all pointed-to
2884      variables of ptr.  */
2885   if (offset == NULL_TREE
2886       || !host_integerp (offset, 0))
2887     rhsoffset = UNKNOWN_OFFSET;
2888   else
2889     {
2890       /* Make sure the bit-offset also fits.  */
2891       rhsunitoffset = TREE_INT_CST_LOW (offset);
2892       rhsoffset = rhsunitoffset * BITS_PER_UNIT;
2893       if (rhsunitoffset != rhsoffset / BITS_PER_UNIT)
2894         rhsoffset = UNKNOWN_OFFSET;
2895     }
2896
2897   get_constraint_for_rhs (ptr, results);
2898   if (rhsoffset == 0)
2899     return;
2900
2901   /* As we are eventually appending to the solution do not use
2902      VEC_iterate here.  */
2903   n = VEC_length (ce_s, *results);
2904   for (j = 0; j < n; j++)
2905     {
2906       varinfo_t curr;
2907       c = *VEC_index (ce_s, *results, j);
2908       curr = get_varinfo (c.var);
2909
2910       if (c.type == ADDRESSOF
2911           /* If this varinfo represents a full variable just use it.  */
2912           && curr->is_full_var)
2913         c.offset = 0;
2914       else if (c.type == ADDRESSOF
2915                /* If we do not know the offset add all subfields.  */
2916                && rhsoffset == UNKNOWN_OFFSET)
2917         {
2918           varinfo_t temp = lookup_vi_for_tree (curr->decl);
2919           do
2920             {
2921               struct constraint_expr c2;
2922               c2.var = temp->id;
2923               c2.type = ADDRESSOF;
2924               c2.offset = 0;
2925               if (c2.var != c.var)
2926                 VEC_safe_push (ce_s, heap, *results, &c2);
2927               temp = temp->next;
2928             }
2929           while (temp);
2930         }
2931       else if (c.type == ADDRESSOF)
2932         {
2933           varinfo_t temp;
2934           unsigned HOST_WIDE_INT offset = curr->offset + rhsoffset;
2935
2936           /* Search the sub-field which overlaps with the
2937              pointed-to offset.  If the result is outside of the variable
2938              we have to provide a conservative result, as the variable is
2939              still reachable from the resulting pointer (even though it
2940              technically cannot point to anything).  The last and first
2941              sub-fields are such conservative results.
2942              ???  If we always had a sub-field for &object + 1 then
2943              we could represent this in a more precise way.  */
2944           if (rhsoffset < 0
2945               && curr->offset < offset)
2946             offset = 0;
2947           temp = first_or_preceding_vi_for_offset (curr, offset);
2948
2949           /* If the found variable is not exactly at the pointed to
2950              result, we have to include the next variable in the
2951              solution as well.  Otherwise two increments by offset / 2
2952              do not result in the same or a conservative superset
2953              solution.  */
2954           if (temp->offset != offset
2955               && temp->next != NULL)
2956             {
2957               struct constraint_expr c2;
2958               c2.var = temp->next->id;
2959               c2.type = ADDRESSOF;
2960               c2.offset = 0;
2961               VEC_safe_push (ce_s, heap, *results, &c2);
2962             }
2963           c.var = temp->id;
2964           c.offset = 0;
2965         }
2966       else
2967         c.offset = rhsoffset;
2968
2969       VEC_replace (ce_s, *results, j, &c);
2970     }
2971 }
2972
2973
2974 /* Given a COMPONENT_REF T, return the constraint_expr vector for it.
2975    If address_p is true the result will be taken its address of.
2976    If lhs_p is true then the constraint expression is assumed to be used
2977    as the lhs.  */
2978
2979 static void
2980 get_constraint_for_component_ref (tree t, VEC(ce_s, heap) **results,
2981                                   bool address_p, bool lhs_p)
2982 {
2983   tree orig_t = t;
2984   HOST_WIDE_INT bitsize = -1;
2985   HOST_WIDE_INT bitmaxsize = -1;
2986   HOST_WIDE_INT bitpos;
2987   tree forzero;
2988   struct constraint_expr *result;
2989
2990   /* Some people like to do cute things like take the address of
2991      &0->a.b */
2992   forzero = t;
2993   while (handled_component_p (forzero)
2994          || INDIRECT_REF_P (forzero)
2995          || TREE_CODE (forzero) == MEM_REF)
2996     forzero = TREE_OPERAND (forzero, 0);
2997
2998   if (CONSTANT_CLASS_P (forzero) && integer_zerop (forzero))
2999     {
3000       struct constraint_expr temp;
3001
3002       temp.offset = 0;
3003       temp.var = integer_id;
3004       temp.type = SCALAR;
3005       VEC_safe_push (ce_s, heap, *results, &temp);
3006       return;
3007     }
3008
3009   /* Handle type-punning through unions.  If we are extracting a pointer
3010      from a union via a possibly type-punning access that pointer
3011      points to anything, similar to a conversion of an integer to
3012      a pointer.  */
3013   if (!lhs_p)
3014     {
3015       tree u;
3016       for (u = t;
3017            TREE_CODE (u) == COMPONENT_REF || TREE_CODE (u) == ARRAY_REF;
3018            u = TREE_OPERAND (u, 0))
3019         if (TREE_CODE (u) == COMPONENT_REF
3020             && TREE_CODE (TREE_TYPE (TREE_OPERAND (u, 0))) == UNION_TYPE)
3021           {
3022             struct constraint_expr temp;
3023
3024             temp.offset = 0;
3025             temp.var = anything_id;
3026             temp.type = ADDRESSOF;
3027             VEC_safe_push (ce_s, heap, *results, &temp);
3028             return;
3029           }
3030     }
3031
3032   t = get_ref_base_and_extent (t, &bitpos, &bitsize, &bitmaxsize);
3033
3034   /* Pretend to take the address of the base, we'll take care of
3035      adding the required subset of sub-fields below.  */
3036   get_constraint_for_1 (t, results, true, lhs_p);
3037   gcc_assert (VEC_length (ce_s, *results) == 1);
3038   result = VEC_last (ce_s, *results);
3039
3040   if (result->type == SCALAR
3041       && get_varinfo (result->var)->is_full_var)
3042     /* For single-field vars do not bother about the offset.  */
3043     result->offset = 0;
3044   else if (result->type == SCALAR)
3045     {
3046       /* In languages like C, you can access one past the end of an
3047          array.  You aren't allowed to dereference it, so we can
3048          ignore this constraint. When we handle pointer subtraction,
3049          we may have to do something cute here.  */
3050
3051       if ((unsigned HOST_WIDE_INT)bitpos < get_varinfo (result->var)->fullsize
3052           && bitmaxsize != 0)
3053         {
3054           /* It's also not true that the constraint will actually start at the
3055              right offset, it may start in some padding.  We only care about
3056              setting the constraint to the first actual field it touches, so
3057              walk to find it.  */
3058           struct constraint_expr cexpr = *result;
3059           varinfo_t curr;
3060           VEC_pop (ce_s, *results);
3061           cexpr.offset = 0;
3062           for (curr = get_varinfo (cexpr.var); curr; curr = curr->next)
3063             {
3064               if (ranges_overlap_p (curr->offset, curr->size,
3065                                     bitpos, bitmaxsize))
3066                 {
3067                   cexpr.var = curr->id;
3068                   VEC_safe_push (ce_s, heap, *results, &cexpr);
3069                   if (address_p)
3070                     break;
3071                 }
3072             }
3073           /* If we are going to take the address of this field then
3074              to be able to compute reachability correctly add at least
3075              the last field of the variable.  */
3076           if (address_p
3077               && VEC_length (ce_s, *results) == 0)
3078             {
3079               curr = get_varinfo (cexpr.var);
3080               while (curr->next != NULL)
3081                 curr = curr->next;
3082               cexpr.var = curr->id;
3083               VEC_safe_push (ce_s, heap, *results, &cexpr);
3084             }
3085           else if (VEC_length (ce_s, *results) == 0)
3086             /* Assert that we found *some* field there. The user couldn't be
3087                accessing *only* padding.  */
3088             /* Still the user could access one past the end of an array
3089                embedded in a struct resulting in accessing *only* padding.  */
3090             /* Or accessing only padding via type-punning to a type
3091                that has a filed just in padding space.  */
3092             {
3093               cexpr.type = SCALAR;
3094               cexpr.var = anything_id;
3095               cexpr.offset = 0;
3096               VEC_safe_push (ce_s, heap, *results, &cexpr);
3097             }
3098         }
3099       else if (bitmaxsize == 0)
3100         {
3101           if (dump_file && (dump_flags & TDF_DETAILS))
3102             fprintf (dump_file, "Access to zero-sized part of variable,"
3103                      "ignoring\n");
3104         }
3105       else
3106         if (dump_file && (dump_flags & TDF_DETAILS))
3107           fprintf (dump_file, "Access to past the end of variable, ignoring\n");
3108     }
3109   else if (result->type == DEREF)
3110     {
3111       /* If we do not know exactly where the access goes say so.  Note
3112          that only for non-structure accesses we know that we access
3113          at most one subfiled of any variable.  */
3114       if (bitpos == -1
3115           || bitsize != bitmaxsize
3116           || AGGREGATE_TYPE_P (TREE_TYPE (orig_t))
3117           || result->offset == UNKNOWN_OFFSET)
3118         result->offset = UNKNOWN_OFFSET;
3119       else
3120         result->offset += bitpos;
3121     }
3122   else if (result->type == ADDRESSOF)
3123     {
3124       /* We can end up here for component references on a
3125          VIEW_CONVERT_EXPR <>(&foobar).  */
3126       result->type = SCALAR;
3127       result->var = anything_id;
3128       result->offset = 0;
3129     }
3130   else
3131     gcc_unreachable ();
3132 }
3133
3134
3135 /* Dereference the constraint expression CONS, and return the result.
3136    DEREF (ADDRESSOF) = SCALAR
3137    DEREF (SCALAR) = DEREF
3138    DEREF (DEREF) = (temp = DEREF1; result = DEREF(temp))
3139    This is needed so that we can handle dereferencing DEREF constraints.  */
3140
3141 static void
3142 do_deref (VEC (ce_s, heap) **constraints)
3143 {
3144   struct constraint_expr *c;
3145   unsigned int i = 0;
3146
3147   FOR_EACH_VEC_ELT (ce_s, *constraints, i, c)
3148     {
3149       if (c->type == SCALAR)
3150         c->type = DEREF;
3151       else if (c->type == ADDRESSOF)
3152         c->type = SCALAR;
3153       else if (c->type == DEREF)
3154         {
3155           struct constraint_expr tmplhs;
3156           tmplhs = new_scalar_tmp_constraint_exp ("dereftmp");
3157           process_constraint (new_constraint (tmplhs, *c));
3158           c->var = tmplhs.var;
3159         }
3160       else
3161         gcc_unreachable ();
3162     }
3163 }
3164
3165 /* Given a tree T, return the constraint expression for taking the
3166    address of it.  */
3167
3168 static void
3169 get_constraint_for_address_of (tree t, VEC (ce_s, heap) **results)
3170 {
3171   struct constraint_expr *c;
3172   unsigned int i;
3173
3174   get_constraint_for_1 (t, results, true, true);
3175
3176   FOR_EACH_VEC_ELT (ce_s, *results, i, c)
3177     {
3178       if (c->type == DEREF)
3179         c->type = SCALAR;
3180       else
3181         c->type = ADDRESSOF;
3182     }
3183 }
3184
3185 /* Given a tree T, return the constraint expression for it.  */
3186
3187 static void
3188 get_constraint_for_1 (tree t, VEC (ce_s, heap) **results, bool address_p,
3189                       bool lhs_p)
3190 {
3191   struct constraint_expr temp;
3192
3193   /* x = integer is all glommed to a single variable, which doesn't
3194      point to anything by itself.  That is, of course, unless it is an
3195      integer constant being treated as a pointer, in which case, we
3196      will return that this is really the addressof anything.  This
3197      happens below, since it will fall into the default case. The only
3198      case we know something about an integer treated like a pointer is
3199      when it is the NULL pointer, and then we just say it points to
3200      NULL.
3201
3202      Do not do that if -fno-delete-null-pointer-checks though, because
3203      in that case *NULL does not fail, so it _should_ alias *anything.
3204      It is not worth adding a new option or renaming the existing one,
3205      since this case is relatively obscure.  */
3206   if ((TREE_CODE (t) == INTEGER_CST
3207        && integer_zerop (t))
3208       /* The only valid CONSTRUCTORs in gimple with pointer typed
3209          elements are zero-initializer.  But in IPA mode we also
3210          process global initializers, so verify at least.  */
3211       || (TREE_CODE (t) == CONSTRUCTOR
3212           && CONSTRUCTOR_NELTS (t) == 0))
3213     {
3214       if (flag_delete_null_pointer_checks)
3215         temp.var = nothing_id;
3216       else
3217         temp.var = nonlocal_id;
3218       temp.type = ADDRESSOF;
3219       temp.offset = 0;
3220       VEC_safe_push (ce_s, heap, *results, &temp);
3221       return;
3222     }
3223
3224   /* String constants are read-only.  */
3225   if (TREE_CODE (t) == STRING_CST)
3226     {
3227       temp.var = readonly_id;
3228       temp.type = SCALAR;
3229       temp.offset = 0;
3230       VEC_safe_push (ce_s, heap, *results, &temp);
3231       return;
3232     }
3233
3234   switch (TREE_CODE_CLASS (TREE_CODE (t)))
3235     {
3236     case tcc_expression:
3237       {
3238         switch (TREE_CODE (t))
3239           {
3240           case ADDR_EXPR:
3241             get_constraint_for_address_of (TREE_OPERAND (t, 0), results);
3242             return;
3243           default:;
3244           }
3245         break;
3246       }
3247     case tcc_reference:
3248       {
3249         switch (TREE_CODE (t))
3250           {
3251           case MEM_REF:
3252             {
3253               struct constraint_expr cs;
3254               varinfo_t vi, curr;
3255               tree off = double_int_to_tree (sizetype, mem_ref_offset (t));
3256               get_constraint_for_ptr_offset (TREE_OPERAND (t, 0), off, results);
3257               do_deref (results);
3258
3259               /* If we are not taking the address then make sure to process
3260                  all subvariables we might access.  */
3261               cs = *VEC_last (ce_s, *results);
3262               if (address_p
3263                   || cs.type != SCALAR)
3264                 return;
3265
3266               vi = get_varinfo (cs.var);
3267               curr = vi->next;
3268               if (!vi->is_full_var
3269                   && curr)
3270                 {
3271                   unsigned HOST_WIDE_INT size;
3272                   if (host_integerp (TYPE_SIZE (TREE_TYPE (t)), 1))
3273                     size = TREE_INT_CST_LOW (TYPE_SIZE (TREE_TYPE (t)));
3274                   else
3275                     size = -1;
3276                   for (; curr; curr = curr->next)
3277                     {
3278                       if (curr->offset - vi->offset < size)
3279                         {
3280                           cs.var = curr->id;
3281                           VEC_safe_push (ce_s, heap, *results, &cs);
3282                         }
3283                       else
3284                         break;
3285                     }
3286                 }
3287               return;
3288             }
3289           case ARRAY_REF:
3290           case ARRAY_RANGE_REF:
3291           case COMPONENT_REF:
3292             get_constraint_for_component_ref (t, results, address_p, lhs_p);
3293             return;
3294           case VIEW_CONVERT_EXPR:
3295             get_constraint_for_1 (TREE_OPERAND (t, 0), results, address_p,
3296                                   lhs_p);
3297             return;
3298           /* We are missing handling for TARGET_MEM_REF here.  */
3299           default:;
3300           }
3301         break;
3302       }
3303     case tcc_exceptional:
3304       {
3305         switch (TREE_CODE (t))
3306           {
3307           case SSA_NAME:
3308             {
3309               get_constraint_for_ssa_var (t, results, address_p);
3310               return;
3311             }
3312           case CONSTRUCTOR:
3313             {
3314               unsigned int i;
3315               tree val;
3316               VEC (ce_s, heap) *tmp = NULL;
3317               FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (t), i, val)
3318                 {
3319                   struct constraint_expr *rhsp;
3320                   unsigned j;
3321                   get_constraint_for_1 (val, &tmp, address_p, lhs_p);
3322                   FOR_EACH_VEC_ELT (ce_s, tmp, j, rhsp)
3323                     VEC_safe_push (ce_s, heap, *results, rhsp);
3324                   VEC_truncate (ce_s, tmp, 0);
3325                 }
3326               VEC_free (ce_s, heap, tmp);
3327               /* We do not know whether the constructor was complete,
3328                  so technically we have to add &NOTHING or &ANYTHING
3329                  like we do for an empty constructor as well.  */
3330               return;
3331             }
3332           default:;
3333           }
3334         break;
3335       }
3336     case tcc_declaration:
3337       {
3338         get_constraint_for_ssa_var (t, results, address_p);
3339         return;
3340       }
3341     case tcc_constant:
3342       {
3343         /* We cannot refer to automatic variables through constants.  */ 
3344         temp.type = ADDRESSOF;
3345         temp.var = nonlocal_id;
3346         temp.offset = 0;
3347         VEC_safe_push (ce_s, heap, *results, &temp);
3348         return;
3349       }
3350     default:;
3351     }
3352
3353   /* The default fallback is a constraint from anything.  */
3354   temp.type = ADDRESSOF;
3355   temp.var = anything_id;
3356   temp.offset = 0;
3357   VEC_safe_push (ce_s, heap, *results, &temp);
3358 }
3359
3360 /* Given a gimple tree T, return the constraint expression vector for it.  */
3361
3362 static void
3363 get_constraint_for (tree t, VEC (ce_s, heap) **results)
3364 {
3365   gcc_assert (VEC_length (ce_s, *results) == 0);
3366
3367   get_constraint_for_1 (t, results, false, true);
3368 }
3369
3370 /* Given a gimple tree T, return the constraint expression vector for it
3371    to be used as the rhs of a constraint.  */
3372
3373 static void
3374 get_constraint_for_rhs (tree t, VEC (ce_s, heap) **results)
3375 {
3376   gcc_assert (VEC_length (ce_s, *results) == 0);
3377
3378   get_constraint_for_1 (t, results, false, false);
3379 }
3380
3381
3382 /* Efficiently generates constraints from all entries in *RHSC to all
3383    entries in *LHSC.  */
3384
3385 static void
3386 process_all_all_constraints (VEC (ce_s, heap) *lhsc, VEC (ce_s, heap) *rhsc)
3387 {
3388   struct constraint_expr *lhsp, *rhsp;
3389   unsigned i, j;
3390
3391   if (VEC_length (ce_s, lhsc) <= 1
3392       || VEC_length (ce_s, rhsc) <= 1)
3393     {
3394       FOR_EACH_VEC_ELT (ce_s, lhsc, i, lhsp)
3395         FOR_EACH_VEC_ELT (ce_s, rhsc, j, rhsp)
3396           process_constraint (new_constraint (*lhsp, *rhsp));
3397     }
3398   else
3399     {
3400       struct constraint_expr tmp;
3401       tmp = new_scalar_tmp_constraint_exp ("allalltmp");
3402       FOR_EACH_VEC_ELT (ce_s, rhsc, i, rhsp)
3403         process_constraint (new_constraint (tmp, *rhsp));
3404       FOR_EACH_VEC_ELT (ce_s, lhsc, i, lhsp)
3405         process_constraint (new_constraint (*lhsp, tmp));
3406     }
3407 }
3408
3409 /* Handle aggregate copies by expanding into copies of the respective
3410    fields of the structures.  */
3411
3412 static void
3413 do_structure_copy (tree lhsop, tree rhsop)
3414 {
3415   struct constraint_expr *lhsp, *rhsp;
3416   VEC (ce_s, heap) *lhsc = NULL, *rhsc = NULL;
3417   unsigned j;
3418
3419   get_constraint_for (lhsop, &lhsc);
3420   get_constraint_for_rhs (rhsop, &rhsc);
3421   lhsp = VEC_index (ce_s, lhsc, 0);
3422   rhsp = VEC_index (ce_s, rhsc, 0);
3423   if (lhsp->type == DEREF
3424       || (lhsp->type == ADDRESSOF && lhsp->var == anything_id)
3425       || rhsp->type == DEREF)
3426     {
3427       if (lhsp->type == DEREF)
3428         {
3429           gcc_assert (VEC_length (ce_s, lhsc) == 1);
3430           lhsp->offset = UNKNOWN_OFFSET;
3431         }
3432       if (rhsp->type == DEREF)
3433         {
3434           gcc_assert (VEC_length (ce_s, rhsc) == 1);
3435           rhsp->offset = UNKNOWN_OFFSET;
3436         }
3437       process_all_all_constraints (lhsc, rhsc);
3438     }
3439   else if (lhsp->type == SCALAR
3440            && (rhsp->type == SCALAR
3441                || rhsp->type == ADDRESSOF))
3442     {
3443       HOST_WIDE_INT lhssize, lhsmaxsize, lhsoffset;
3444       HOST_WIDE_INT rhssize, rhsmaxsize, rhsoffset;
3445       unsigned k = 0;
3446       get_ref_base_and_extent (lhsop, &lhsoffset, &lhssize, &lhsmaxsize);
3447       get_ref_base_and_extent (rhsop, &rhsoffset, &rhssize, &rhsmaxsize);
3448       for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp);)
3449         {
3450           varinfo_t lhsv, rhsv;
3451           rhsp = VEC_index (ce_s, rhsc, k);
3452           lhsv = get_varinfo (lhsp->var);
3453           rhsv = get_varinfo (rhsp->var);
3454           if (lhsv->may_have_pointers
3455               && (lhsv->is_full_var
3456                   || rhsv->is_full_var
3457                   || ranges_overlap_p (lhsv->offset + rhsoffset, lhsv->size,
3458                                        rhsv->offset + lhsoffset, rhsv->size)))
3459             process_constraint (new_constraint (*lhsp, *rhsp));
3460           if (!rhsv->is_full_var
3461               && (lhsv->is_full_var
3462                   || (lhsv->offset + rhsoffset + lhsv->size
3463                       > rhsv->offset + lhsoffset + rhsv->size)))
3464             {
3465               ++k;
3466               if (k >= VEC_length (ce_s, rhsc))
3467                 break;
3468             }
3469           else
3470             ++j;
3471         }
3472     }
3473   else
3474     gcc_unreachable ();
3475
3476   VEC_free (ce_s, heap, lhsc);
3477   VEC_free (ce_s, heap, rhsc);
3478 }
3479
3480 /* Create constraints ID = { rhsc }.  */
3481
3482 static void
3483 make_constraints_to (unsigned id, VEC(ce_s, heap) *rhsc)
3484 {
3485   struct constraint_expr *c;
3486   struct constraint_expr includes;
3487   unsigned int j;
3488
3489   includes.var = id;
3490   includes.offset = 0;
3491   includes.type = SCALAR;
3492
3493   FOR_EACH_VEC_ELT (ce_s, rhsc, j, c)
3494     process_constraint (new_constraint (includes, *c));
3495 }
3496
3497 /* Create a constraint ID = OP.  */
3498
3499 static void
3500 make_constraint_to (unsigned id, tree op)
3501 {
3502   VEC(ce_s, heap) *rhsc = NULL;
3503   get_constraint_for_rhs (op, &rhsc);
3504   make_constraints_to (id, rhsc);
3505   VEC_free (ce_s, heap, rhsc);
3506 }
3507
3508 /* Create a constraint ID = &FROM.  */
3509
3510 static void
3511 make_constraint_from (varinfo_t vi, int from)
3512 {
3513   struct constraint_expr lhs, rhs;
3514
3515   lhs.var = vi->id;
3516   lhs.offset = 0;
3517   lhs.type = SCALAR;
3518
3519   rhs.var = from;
3520   rhs.offset = 0;
3521   rhs.type = ADDRESSOF;
3522   process_constraint (new_constraint (lhs, rhs));
3523 }
3524
3525 /* Create a constraint ID = FROM.  */
3526
3527 static void
3528 make_copy_constraint (varinfo_t vi, int from)
3529 {
3530   struct constraint_expr lhs, rhs;
3531
3532   lhs.var = vi->id;
3533   lhs.offset = 0;
3534   lhs.type = SCALAR;
3535
3536   rhs.var = from;
3537   rhs.offset = 0;
3538   rhs.type = SCALAR;
3539   process_constraint (new_constraint (lhs, rhs));
3540 }
3541
3542 /* Make constraints necessary to make OP escape.  */
3543
3544 static void
3545 make_escape_constraint (tree op)
3546 {
3547   make_constraint_to (escaped_id, op);
3548 }
3549
3550 /* Add constraints to that the solution of VI is transitively closed.  */
3551
3552 static void
3553 make_transitive_closure_constraints (varinfo_t vi)
3554 {
3555   struct constraint_expr lhs, rhs;
3556
3557   /* VAR = *VAR;  */
3558   lhs.type = SCALAR;
3559   lhs.var = vi->id;
3560   lhs.offset = 0;
3561   rhs.type = DEREF;
3562   rhs.var = vi->id;
3563   rhs.offset = 0;
3564   process_constraint (new_constraint (lhs, rhs));
3565
3566   /* VAR = VAR + UNKNOWN;  */
3567   lhs.type = SCALAR;
3568   lhs.var = vi->id;
3569   lhs.offset = 0;
3570   rhs.type = SCALAR;
3571   rhs.var = vi->id;
3572   rhs.offset = UNKNOWN_OFFSET;
3573   process_constraint (new_constraint (lhs, rhs));
3574 }
3575
3576 /* Temporary storage for fake var decls.  */
3577 struct obstack fake_var_decl_obstack;
3578
3579 /* Build a fake VAR_DECL acting as referrer to a DECL_UID.  */
3580
3581 static tree
3582 build_fake_var_decl (tree type)
3583 {
3584   tree decl = (tree) XOBNEW (&fake_var_decl_obstack, struct tree_var_decl);
3585   memset (decl, 0, sizeof (struct tree_var_decl));
3586   TREE_SET_CODE (decl, VAR_DECL);
3587   TREE_TYPE (decl) = type;
3588   DECL_UID (decl) = allocate_decl_uid ();
3589   SET_DECL_PT_UID (decl, -1);
3590   layout_decl (decl, 0);
3591   return decl;
3592 }
3593
3594 /* Create a new artificial heap variable with NAME.
3595    Return the created variable.  */
3596
3597 static varinfo_t
3598 make_heapvar (const char *name)
3599 {
3600   varinfo_t vi;
3601   tree heapvar;
3602   
3603   heapvar = build_fake_var_decl (ptr_type_node);
3604   DECL_EXTERNAL (heapvar) = 1;
3605
3606   vi = new_var_info (heapvar, name);
3607   vi->is_artificial_var = true;
3608   vi->is_heap_var = true;
3609   vi->is_unknown_size_var = true;
3610   vi->offset = 0;
3611   vi->fullsize = ~0;
3612   vi->size = ~0;
3613   vi->is_full_var = true;
3614   insert_vi_for_tree (heapvar, vi);
3615
3616   return vi;
3617 }
3618
3619 /* Create a new artificial heap variable with NAME and make a
3620    constraint from it to LHS.  Return the created variable.  */
3621
3622 static varinfo_t
3623 make_constraint_from_heapvar (varinfo_t lhs, const char *name)
3624 {
3625   varinfo_t vi = make_heapvar (name);
3626   make_constraint_from (lhs, vi->id);
3627
3628   return vi;
3629 }
3630
3631 /* Create a new artificial heap variable with NAME and make a
3632    constraint from it to LHS.  Set flags according to a tag used
3633    for tracking restrict pointers.  */
3634
3635 static void
3636 make_constraint_from_restrict (varinfo_t lhs, const char *name)
3637 {
3638   varinfo_t vi;
3639   vi = make_constraint_from_heapvar (lhs, name);
3640   vi->is_restrict_var = 1;
3641   vi->is_global_var = 0;
3642   vi->is_special_var = 1;
3643   vi->may_have_pointers = 0;
3644 }
3645
3646 /* In IPA mode there are varinfos for different aspects of reach
3647    function designator.  One for the points-to set of the return
3648    value, one for the variables that are clobbered by the function,
3649    one for its uses and one for each parameter (including a single
3650    glob for remaining variadic arguments).  */
3651
3652 enum { fi_clobbers = 1, fi_uses = 2,
3653        fi_static_chain = 3, fi_result = 4, fi_parm_base = 5 };
3654
3655 /* Get a constraint for the requested part of a function designator FI
3656    when operating in IPA mode.  */
3657
3658 static struct constraint_expr
3659 get_function_part_constraint (varinfo_t fi, unsigned part)
3660 {
3661   struct constraint_expr c;
3662
3663   gcc_assert (in_ipa_mode);
3664
3665   if (fi->id == anything_id)
3666     {
3667       /* ???  We probably should have a ANYFN special variable.  */
3668       c.var = anything_id;
3669       c.offset = 0;
3670       c.type = SCALAR;
3671     }
3672   else if (TREE_CODE (fi->decl) == FUNCTION_DECL)
3673     {
3674       varinfo_t ai = first_vi_for_offset (fi, part);
3675       if (ai)
3676         c.var = ai->id;
3677       else
3678         c.var = anything_id;
3679       c.offset = 0;
3680       c.type = SCALAR;
3681     }
3682   else
3683     {
3684       c.var = fi->id;
3685       c.offset = part;
3686       c.type = DEREF;
3687     }
3688
3689   return c;
3690 }
3691
3692 /* For non-IPA mode, generate constraints necessary for a call on the
3693    RHS.  */
3694
3695 static void
3696 handle_rhs_call (gimple stmt, VEC(ce_s, heap) **results)
3697 {
3698   struct constraint_expr rhsc;
3699   unsigned i;
3700   bool returns_uses = false;
3701
3702   for (i = 0; i < gimple_call_num_args (stmt); ++i)
3703     {
3704       tree arg = gimple_call_arg (stmt, i);
3705       int flags = gimple_call_arg_flags (stmt, i);
3706
3707       /* If the argument is not used we can ignore it.  */
3708       if (flags & EAF_UNUSED)
3709         continue;
3710
3711       /* As we compute ESCAPED context-insensitive we do not gain
3712          any precision with just EAF_NOCLOBBER but not EAF_NOESCAPE
3713          set.  The argument would still get clobbered through the
3714          escape solution.
3715          ???  We might get away with less (and more precise) constraints
3716          if using a temporary for transitively closing things.  */
3717       if ((flags & EAF_NOCLOBBER)
3718            && (flags & EAF_NOESCAPE))
3719         {
3720           varinfo_t uses = get_call_use_vi (stmt);
3721           if (!(flags & EAF_DIRECT))
3722             make_transitive_closure_constraints (uses);
3723           make_constraint_to (uses->id, arg);
3724           returns_uses = true;
3725         }
3726       else if (flags & EAF_NOESCAPE)
3727         {
3728           varinfo_t uses = get_call_use_vi (stmt);
3729           varinfo_t clobbers = get_call_clobber_vi (stmt);
3730           if (!(flags & EAF_DIRECT))
3731             {
3732               make_transitive_closure_constraints (uses);
3733               make_transitive_closure_constraints (clobbers);
3734             }
3735           make_constraint_to (uses->id, arg);
3736           make_constraint_to (clobbers->id, arg);
3737           returns_uses = true;
3738         }
3739       else
3740         make_escape_constraint (arg);
3741     }
3742
3743   /* If we added to the calls uses solution make sure we account for
3744      pointers to it to be returned.  */
3745   if (returns_uses)
3746     {
3747       rhsc.var = get_call_use_vi (stmt)->id;
3748       rhsc.offset = 0;
3749       rhsc.type = SCALAR;
3750       VEC_safe_push (ce_s, heap, *results, &rhsc);
3751     }
3752
3753   /* The static chain escapes as well.  */
3754   if (gimple_call_chain (stmt))
3755     make_escape_constraint (gimple_call_chain (stmt));
3756
3757   /* And if we applied NRV the address of the return slot escapes as well.  */
3758   if (gimple_call_return_slot_opt_p (stmt)
3759       && gimple_call_lhs (stmt) != NULL_TREE
3760       && TREE_ADDRESSABLE (TREE_TYPE (gimple_call_lhs (stmt))))
3761     {
3762       VEC(ce_s, heap) *tmpc = NULL;
3763       struct constraint_expr lhsc, *c;
3764       get_constraint_for_address_of (gimple_call_lhs (stmt), &tmpc);
3765       lhsc.var = escaped_id;
3766       lhsc.offset = 0;
3767       lhsc.type = SCALAR;
3768       FOR_EACH_VEC_ELT (ce_s, tmpc, i, c)
3769         process_constraint (new_constraint (lhsc, *c));
3770       VEC_free(ce_s, heap, tmpc);
3771     }
3772
3773   /* Regular functions return nonlocal memory.  */
3774   rhsc.var = nonlocal_id;
3775   rhsc.offset = 0;
3776   rhsc.type = SCALAR;
3777   VEC_safe_push (ce_s, heap, *results, &rhsc);
3778 }
3779
3780 /* For non-IPA mode, generate constraints necessary for a call
3781    that returns a pointer and assigns it to LHS.  This simply makes
3782    the LHS point to global and escaped variables.  */
3783
3784 static void
3785 handle_lhs_call (gimple stmt, tree lhs, int flags, VEC(ce_s, heap) *rhsc,
3786                  tree fndecl)
3787 {
3788   VEC(ce_s, heap) *lhsc = NULL;
3789
3790   get_constraint_for (lhs, &lhsc);
3791   /* If the store is to a global decl make sure to
3792      add proper escape constraints.  */
3793   lhs = get_base_address (lhs);
3794   if (lhs
3795       && DECL_P (lhs)
3796       && is_global_var (lhs))
3797     {
3798       struct constraint_expr tmpc;
3799       tmpc.var = escaped_id;
3800       tmpc.offset = 0;
3801       tmpc.type = SCALAR;
3802       VEC_safe_push (ce_s, heap, lhsc, &tmpc);
3803     }
3804
3805   /* If the call returns an argument unmodified override the rhs
3806      constraints.  */
3807   flags = gimple_call_return_flags (stmt);
3808   if (flags & ERF_RETURNS_ARG
3809       && (flags & ERF_RETURN_ARG_MASK) < gimple_call_num_args (stmt))
3810     {
3811       tree arg;
3812       rhsc = NULL;
3813       arg = gimple_call_arg (stmt, flags & ERF_RETURN_ARG_MASK);
3814       get_constraint_for (arg, &rhsc);
3815       process_all_all_constraints (lhsc, rhsc);
3816       VEC_free (ce_s, heap, rhsc);
3817     }
3818   else if (flags & ERF_NOALIAS)
3819     {
3820       varinfo_t vi;
3821       struct constraint_expr tmpc;
3822       rhsc = NULL;
3823       vi = make_heapvar ("HEAP");
3824       /* We delay marking allocated storage global until we know if
3825          it escapes.  */
3826       DECL_EXTERNAL (vi->decl) = 0;
3827       vi->is_global_var = 0;
3828       /* If this is not a real malloc call assume the memory was
3829          initialized and thus may point to global memory.  All
3830          builtin functions with the malloc attribute behave in a sane way.  */
3831       if (!fndecl
3832           || DECL_BUILT_IN_CLASS (fndecl) != BUILT_IN_NORMAL)
3833         make_constraint_from (vi, nonlocal_id);
3834       tmpc.var = vi->id;
3835       tmpc.offset = 0;
3836       tmpc.type = ADDRESSOF;
3837       VEC_safe_push (ce_s, heap, rhsc, &tmpc);
3838     }
3839
3840   process_all_all_constraints (lhsc, rhsc);
3841
3842   VEC_free (ce_s, heap, lhsc);
3843 }
3844
3845 /* For non-IPA mode, generate constraints necessary for a call of a
3846    const function that returns a pointer in the statement STMT.  */
3847
3848 static void
3849 handle_const_call (gimple stmt, VEC(ce_s, heap) **results)
3850 {
3851   struct constraint_expr rhsc;
3852   unsigned int k;
3853
3854   /* Treat nested const functions the same as pure functions as far
3855      as the static chain is concerned.  */
3856   if (gimple_call_chain (stmt))
3857     {
3858       varinfo_t uses = get_call_use_vi (stmt);
3859       make_transitive_closure_constraints (uses);
3860       make_constraint_to (uses->id, gimple_call_chain (stmt));
3861       rhsc.var = uses->id;
3862       rhsc.offset = 0;
3863       rhsc.type = SCALAR;
3864       VEC_safe_push (ce_s, heap, *results, &rhsc);
3865     }
3866
3867   /* May return arguments.  */
3868   for (k = 0; k < gimple_call_num_args (stmt); ++k)
3869     {
3870       tree arg = gimple_call_arg (stmt, k);
3871       VEC(ce_s, heap) *argc = NULL;
3872       unsigned i;
3873       struct constraint_expr *argp;
3874       get_constraint_for_rhs (arg, &argc);
3875       FOR_EACH_VEC_ELT (ce_s, argc, i, argp)
3876         VEC_safe_push (ce_s, heap, *results, argp);
3877       VEC_free(ce_s, heap, argc);
3878     }
3879
3880   /* May return addresses of globals.  */
3881   rhsc.var = nonlocal_id;
3882   rhsc.offset = 0;
3883   rhsc.type = ADDRESSOF;
3884   VEC_safe_push (ce_s, heap, *results, &rhsc);
3885 }
3886
3887 /* For non-IPA mode, generate constraints necessary for a call to a
3888    pure function in statement STMT.  */
3889
3890 static void
3891 handle_pure_call (gimple stmt, VEC(ce_s, heap) **results)
3892 {
3893   struct constraint_expr rhsc;
3894   unsigned i;
3895   varinfo_t uses = NULL;
3896
3897   /* Memory reached from pointer arguments is call-used.  */
3898   for (i = 0; i < gimple_call_num_args (stmt); ++i)
3899     {
3900       tree arg = gimple_call_arg (stmt, i);
3901       if (!uses)
3902         {
3903           uses = get_call_use_vi (stmt);
3904           make_transitive_closure_constraints (uses);
3905         }
3906       make_constraint_to (uses->id, arg);
3907     }
3908
3909   /* The static chain is used as well.  */
3910   if (gimple_call_chain (stmt))
3911     {
3912       if (!uses)
3913         {
3914           uses = get_call_use_vi (stmt);
3915           make_transitive_closure_constraints (uses);
3916         }
3917       make_constraint_to (uses->id, gimple_call_chain (stmt));
3918     }
3919
3920   /* Pure functions may return call-used and nonlocal memory.  */
3921   if (uses)
3922     {
3923       rhsc.var = uses->id;
3924       rhsc.offset = 0;
3925       rhsc.type = SCALAR;
3926       VEC_safe_push (ce_s, heap, *results, &rhsc);
3927     }
3928   rhsc.var = nonlocal_id;
3929   rhsc.offset = 0;
3930   rhsc.type = SCALAR;
3931   VEC_safe_push (ce_s, heap, *results, &rhsc);
3932 }
3933
3934
3935 /* Return the varinfo for the callee of CALL.  */
3936
3937 static varinfo_t
3938 get_fi_for_callee (gimple call)
3939 {
3940   tree decl, fn = gimple_call_fn (call);
3941
3942   if (fn && TREE_CODE (fn) == OBJ_TYPE_REF)
3943     fn = OBJ_TYPE_REF_EXPR (fn);
3944
3945   /* If we can directly resolve the function being called, do so.
3946      Otherwise, it must be some sort of indirect expression that
3947      we should still be able to handle.  */
3948   decl = gimple_call_addr_fndecl (fn);
3949   if (decl)
3950     return get_vi_for_tree (decl);
3951
3952   /* If the function is anything other than a SSA name pointer we have no
3953      clue and should be getting ANYFN (well, ANYTHING for now).  */
3954   if (!fn || TREE_CODE (fn) != SSA_NAME)
3955     return get_varinfo (anything_id);
3956
3957   if ((TREE_CODE (SSA_NAME_VAR (fn)) == PARM_DECL
3958        || TREE_CODE (SSA_NAME_VAR (fn)) == RESULT_DECL)
3959       && SSA_NAME_IS_DEFAULT_DEF (fn))
3960     fn = SSA_NAME_VAR (fn);
3961
3962   return get_vi_for_tree (fn);
3963 }
3964
3965 /* Create constraints for the builtin call T.  Return true if the call
3966    was handled, otherwise false.  */
3967
3968 static bool
3969 find_func_aliases_for_builtin_call (gimple t)
3970 {
3971   tree fndecl = gimple_call_fndecl (t);
3972   VEC(ce_s, heap) *lhsc = NULL;
3973   VEC(ce_s, heap) *rhsc = NULL;
3974   varinfo_t fi;
3975
3976   if (fndecl != NULL_TREE
3977       && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
3978     /* ???  All builtins that are handled here need to be handled
3979        in the alias-oracle query functions explicitly!  */
3980     switch (DECL_FUNCTION_CODE (fndecl))
3981       {
3982       /* All the following functions return a pointer to the same object
3983          as their first argument points to.  The functions do not add
3984          to the ESCAPED solution.  The functions make the first argument
3985          pointed to memory point to what the second argument pointed to
3986          memory points to.  */
3987       case BUILT_IN_STRCPY:
3988       case BUILT_IN_STRNCPY:
3989       case BUILT_IN_BCOPY:
3990       case BUILT_IN_MEMCPY:
3991       case BUILT_IN_MEMMOVE:
3992       case BUILT_IN_MEMPCPY:
3993       case BUILT_IN_STPCPY:
3994       case BUILT_IN_STPNCPY:
3995       case BUILT_IN_STRCAT:
3996       case BUILT_IN_STRNCAT:
3997       case BUILT_IN_STRCPY_CHK:
3998       case BUILT_IN_STRNCPY_CHK:
3999       case BUILT_IN_MEMCPY_CHK:
4000       case BUILT_IN_MEMMOVE_CHK:
4001       case BUILT_IN_MEMPCPY_CHK:
4002       case BUILT_IN_STPCPY_CHK:
4003       case BUILT_IN_STRCAT_CHK:
4004       case BUILT_IN_STRNCAT_CHK:
4005         {
4006           tree res = gimple_call_lhs (t);
4007           tree dest = gimple_call_arg (t, (DECL_FUNCTION_CODE (fndecl)
4008                                            == BUILT_IN_BCOPY ? 1 : 0));
4009           tree src = gimple_call_arg (t, (DECL_FUNCTION_CODE (fndecl)
4010                                           == BUILT_IN_BCOPY ? 0 : 1));
4011           if (res != NULL_TREE)
4012             {
4013               get_constraint_for (res, &lhsc);
4014               if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_MEMPCPY
4015                   || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPCPY
4016                   || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPNCPY
4017                   || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_MEMPCPY_CHK
4018                   || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPCPY_CHK)
4019                 get_constraint_for_ptr_offset (dest, NULL_TREE, &rhsc);
4020               else
4021                 get_constraint_for (dest, &rhsc);
4022               process_all_all_constraints (lhsc, rhsc);
4023               VEC_free (ce_s, heap, lhsc);
4024               VEC_free (ce_s, heap, rhsc);
4025             }
4026           get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4027           get_constraint_for_ptr_offset (src, NULL_TREE, &rhsc);
4028           do_deref (&lhsc);
4029           do_deref (&rhsc);
4030           process_all_all_constraints (lhsc, rhsc);
4031           VEC_free (ce_s, heap, lhsc);
4032           VEC_free (ce_s, heap, rhsc);
4033           return true;
4034         }
4035       case BUILT_IN_MEMSET:
4036       case BUILT_IN_MEMSET_CHK:
4037         {
4038           tree res = gimple_call_lhs (t);
4039           tree dest = gimple_call_arg (t, 0);
4040           unsigned i;
4041           ce_s *lhsp;
4042           struct constraint_expr ac;
4043           if (res != NULL_TREE)
4044             {
4045               get_constraint_for (res, &lhsc);
4046               get_constraint_for (dest, &rhsc);
4047               process_all_all_constraints (lhsc, rhsc);
4048               VEC_free (ce_s, heap, lhsc);
4049               VEC_free (ce_s, heap, rhsc);
4050             }
4051           get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4052           do_deref (&lhsc);
4053           if (flag_delete_null_pointer_checks
4054               && integer_zerop (gimple_call_arg (t, 1)))
4055             {
4056               ac.type = ADDRESSOF;
4057               ac.var = nothing_id;
4058             }
4059           else
4060             {
4061               ac.type = SCALAR;
4062               ac.var = integer_id;
4063             }
4064           ac.offset = 0;
4065           FOR_EACH_VEC_ELT (ce_s, lhsc, i, lhsp)
4066               process_constraint (new_constraint (*lhsp, ac));
4067           VEC_free (ce_s, heap, lhsc);
4068           return true;
4069         }
4070       case BUILT_IN_ASSUME_ALIGNED:
4071         {
4072           tree res = gimple_call_lhs (t);
4073           tree dest = gimple_call_arg (t, 0);
4074           if (res != NULL_TREE)
4075             {
4076               get_constraint_for (res, &lhsc);
4077               get_constraint_for (dest, &rhsc);
4078               process_all_all_constraints (lhsc, rhsc);
4079               VEC_free (ce_s, heap, lhsc);
4080               VEC_free (ce_s, heap, rhsc);
4081             }
4082           return true;
4083         }
4084       /* All the following functions do not return pointers, do not
4085          modify the points-to sets of memory reachable from their
4086          arguments and do not add to the ESCAPED solution.  */
4087       case BUILT_IN_SINCOS:
4088       case BUILT_IN_SINCOSF:
4089       case BUILT_IN_SINCOSL:
4090       case BUILT_IN_FREXP:
4091       case BUILT_IN_FREXPF:
4092       case BUILT_IN_FREXPL:
4093       case BUILT_IN_GAMMA_R:
4094       case BUILT_IN_GAMMAF_R:
4095       case BUILT_IN_GAMMAL_R:
4096       case BUILT_IN_LGAMMA_R:
4097       case BUILT_IN_LGAMMAF_R:
4098       case BUILT_IN_LGAMMAL_R:
4099       case BUILT_IN_MODF:
4100       case BUILT_IN_MODFF:
4101       case BUILT_IN_MODFL:
4102       case BUILT_IN_REMQUO:
4103       case BUILT_IN_REMQUOF:
4104       case BUILT_IN_REMQUOL:
4105       case BUILT_IN_FREE:
4106         return true;
4107       /* Trampolines are special - they set up passing the static
4108          frame.  */
4109       case BUILT_IN_INIT_TRAMPOLINE:
4110         {
4111           tree tramp = gimple_call_arg (t, 0);
4112           tree nfunc = gimple_call_arg (t, 1);
4113           tree frame = gimple_call_arg (t, 2);
4114           unsigned i;
4115           struct constraint_expr lhs, *rhsp;
4116           if (in_ipa_mode)
4117             {
4118               varinfo_t nfi = NULL;
4119               gcc_assert (TREE_CODE (nfunc) == ADDR_EXPR);
4120               nfi = lookup_vi_for_tree (TREE_OPERAND (nfunc, 0));
4121               if (nfi)
4122                 {
4123                   lhs = get_function_part_constraint (nfi, fi_static_chain);
4124                   get_constraint_for (frame, &rhsc);
4125                   FOR_EACH_VEC_ELT (ce_s, rhsc, i, rhsp)
4126                       process_constraint (new_constraint (lhs, *rhsp));
4127                   VEC_free (ce_s, heap, rhsc);
4128
4129                   /* Make the frame point to the function for
4130                      the trampoline adjustment call.  */
4131                   get_constraint_for (tramp, &lhsc);
4132                   do_deref (&lhsc);
4133                   get_constraint_for (nfunc, &rhsc);
4134                   process_all_all_constraints (lhsc, rhsc);
4135                   VEC_free (ce_s, heap, rhsc);
4136                   VEC_free (ce_s, heap, lhsc);
4137
4138                   return true;
4139                 }
4140             }
4141           /* Else fallthru to generic handling which will let
4142              the frame escape.  */
4143           break;
4144         }
4145       case BUILT_IN_ADJUST_TRAMPOLINE:
4146         {
4147           tree tramp = gimple_call_arg (t, 0);
4148           tree res = gimple_call_lhs (t);
4149           if (in_ipa_mode && res)
4150             {
4151               get_constraint_for (res, &lhsc);
4152               get_constraint_for (tramp, &rhsc);
4153               do_deref (&rhsc);
4154               process_all_all_constraints (lhsc, rhsc);
4155               VEC_free (ce_s, heap, rhsc);
4156               VEC_free (ce_s, heap, lhsc);
4157             }
4158           return true;
4159         }
4160       /* Variadic argument handling needs to be handled in IPA
4161          mode as well.  */
4162       case BUILT_IN_VA_START:
4163         {
4164           if (in_ipa_mode)
4165             {
4166               tree valist = gimple_call_arg (t, 0);
4167               struct constraint_expr rhs, *lhsp;
4168               unsigned i;
4169               /* The va_list gets access to pointers in variadic
4170                  arguments.  */
4171               fi = lookup_vi_for_tree (cfun->decl);
4172               gcc_assert (fi != NULL);
4173               get_constraint_for (valist, &lhsc);
4174               do_deref (&lhsc);
4175               rhs = get_function_part_constraint (fi, ~0);
4176               rhs.type = ADDRESSOF;
4177               FOR_EACH_VEC_ELT (ce_s, lhsc, i, lhsp)
4178                   process_constraint (new_constraint (*lhsp, rhs));
4179               VEC_free (ce_s, heap, lhsc);
4180               /* va_list is clobbered.  */
4181               make_constraint_to (get_call_clobber_vi (t)->id, valist);
4182               return true;
4183             }
4184           break;
4185         }
4186       /* va_end doesn't have any effect that matters.  */
4187       case BUILT_IN_VA_END:
4188         return true;
4189       /* Alternate return.  Simply give up for now.  */
4190       case BUILT_IN_RETURN:
4191         {
4192           fi = NULL;
4193           if (!in_ipa_mode
4194               || !(fi = get_vi_for_tree (cfun->decl)))
4195             make_constraint_from (get_varinfo (escaped_id), anything_id);
4196           else if (in_ipa_mode
4197                    && fi != NULL)
4198             {
4199               struct constraint_expr lhs, rhs;
4200               lhs = get_function_part_constraint (fi, fi_result);
4201               rhs.var = anything_id;
4202               rhs.offset = 0;
4203               rhs.type = SCALAR;
4204               process_constraint (new_constraint (lhs, rhs));
4205             }
4206           return true;
4207         }
4208       /* printf-style functions may have hooks to set pointers to
4209          point to somewhere into the generated string.  Leave them
4210          for a later excercise...  */
4211       default:
4212         /* Fallthru to general call handling.  */;
4213       }
4214
4215   return false;
4216 }
4217
4218 /* Create constraints for the call T.  */
4219
4220 static void
4221 find_func_aliases_for_call (gimple t)
4222 {
4223   tree fndecl = gimple_call_fndecl (t);
4224   VEC(ce_s, heap) *lhsc = NULL;
4225   VEC(ce_s, heap) *rhsc = NULL;
4226   varinfo_t fi;
4227
4228   if (fndecl != NULL_TREE
4229       && DECL_BUILT_IN (fndecl)
4230       && find_func_aliases_for_builtin_call (t))
4231     return;
4232
4233   fi = get_fi_for_callee (t);
4234   if (!in_ipa_mode
4235       || (fndecl && !fi->is_fn_info))
4236     {
4237       VEC(ce_s, heap) *rhsc = NULL;
4238       int flags = gimple_call_flags (t);
4239
4240       /* Const functions can return their arguments and addresses
4241          of global memory but not of escaped memory.  */
4242       if (flags & (ECF_CONST|ECF_NOVOPS))
4243         {
4244           if (gimple_call_lhs (t))
4245             handle_const_call (t, &rhsc);
4246         }
4247       /* Pure functions can return addresses in and of memory
4248          reachable from their arguments, but they are not an escape
4249          point for reachable memory of their arguments.  */
4250       else if (flags & (ECF_PURE|ECF_LOOPING_CONST_OR_PURE))
4251         handle_pure_call (t, &rhsc);
4252       else
4253         handle_rhs_call (t, &rhsc);
4254       if (gimple_call_lhs (t))
4255         handle_lhs_call (t, gimple_call_lhs (t), flags, rhsc, fndecl);
4256       VEC_free (ce_s, heap, rhsc);
4257     }
4258   else
4259     {
4260       tree lhsop;
4261       unsigned j;
4262
4263       /* Assign all the passed arguments to the appropriate incoming
4264          parameters of the function.  */
4265       for (j = 0; j < gimple_call_num_args (t); j++)
4266         {
4267           struct constraint_expr lhs ;
4268           struct constraint_expr *rhsp;
4269           tree arg = gimple_call_arg (t, j);
4270
4271           get_constraint_for_rhs (arg, &rhsc);
4272           lhs = get_function_part_constraint (fi, fi_parm_base + j);
4273           while (VEC_length (ce_s, rhsc) != 0)
4274             {
4275               rhsp = VEC_last (ce_s, rhsc);
4276               process_constraint (new_constraint (lhs, *rhsp));
4277               VEC_pop (ce_s, rhsc);
4278             }
4279         }
4280
4281       /* If we are returning a value, assign it to the result.  */
4282       lhsop = gimple_call_lhs (t);
4283       if (lhsop)
4284         {
4285           struct constraint_expr rhs;
4286           struct constraint_expr *lhsp;
4287
4288           get_constraint_for (lhsop, &lhsc);
4289           rhs = get_function_part_constraint (fi, fi_result);
4290           if (fndecl
4291               && DECL_RESULT (fndecl)
4292               && DECL_BY_REFERENCE (DECL_RESULT (fndecl)))
4293             {
4294               VEC(ce_s, heap) *tem = NULL;
4295               VEC_safe_push (ce_s, heap, tem, &rhs);
4296               do_deref (&tem);
4297               rhs = *VEC_index (ce_s, tem, 0);
4298               VEC_free(ce_s, heap, tem);
4299             }
4300           FOR_EACH_VEC_ELT (ce_s, lhsc, j, lhsp)
4301             process_constraint (new_constraint (*lhsp, rhs));
4302         }
4303
4304       /* If we pass the result decl by reference, honor that.  */
4305       if (lhsop
4306           && fndecl
4307           && DECL_RESULT (fndecl)
4308           && DECL_BY_REFERENCE (DECL_RESULT (fndecl)))
4309         {
4310           struct constraint_expr lhs;
4311           struct constraint_expr *rhsp;
4312
4313           get_constraint_for_address_of (lhsop, &rhsc);
4314           lhs = get_function_part_constraint (fi, fi_result);
4315           FOR_EACH_VEC_ELT (ce_s, rhsc, j, rhsp)
4316             process_constraint (new_constraint (lhs, *rhsp));
4317           VEC_free (ce_s, heap, rhsc);
4318         }
4319
4320       /* If we use a static chain, pass it along.  */
4321       if (gimple_call_chain (t))
4322         {
4323           struct constraint_expr lhs;
4324           struct constraint_expr *rhsp;
4325
4326           get_constraint_for (gimple_call_chain (t), &rhsc);
4327           lhs = get_function_part_constraint (fi, fi_static_chain);
4328           FOR_EACH_VEC_ELT (ce_s, rhsc, j, rhsp)
4329             process_constraint (new_constraint (lhs, *rhsp));
4330         }
4331     }
4332 }
4333
4334 /* Walk statement T setting up aliasing constraints according to the
4335    references found in T.  This function is the main part of the
4336    constraint builder.  AI points to auxiliary alias information used
4337    when building alias sets and computing alias grouping heuristics.  */
4338
4339 static void
4340 find_func_aliases (gimple origt)
4341 {
4342   gimple t = origt;
4343   VEC(ce_s, heap) *lhsc = NULL;
4344   VEC(ce_s, heap) *rhsc = NULL;
4345   struct constraint_expr *c;
4346   varinfo_t fi;
4347
4348   /* Now build constraints expressions.  */
4349   if (gimple_code (t) == GIMPLE_PHI)
4350     {
4351       size_t i;
4352       unsigned int j;
4353
4354       /* For a phi node, assign all the arguments to
4355          the result.  */
4356       get_constraint_for (gimple_phi_result (t), &lhsc);
4357       for (i = 0; i < gimple_phi_num_args (t); i++)
4358         {
4359           tree strippedrhs = PHI_ARG_DEF (t, i);
4360
4361           STRIP_NOPS (strippedrhs);
4362           get_constraint_for_rhs (gimple_phi_arg_def (t, i), &rhsc);
4363
4364           FOR_EACH_VEC_ELT (ce_s, lhsc, j, c)
4365             {
4366               struct constraint_expr *c2;
4367               while (VEC_length (ce_s, rhsc) > 0)
4368                 {
4369                   c2 = VEC_last (ce_s, rhsc);
4370                   process_constraint (new_constraint (*c, *c2));
4371                   VEC_pop (ce_s, rhsc);
4372                 }
4373             }
4374         }
4375     }
4376   /* In IPA mode, we need to generate constraints to pass call
4377      arguments through their calls.   There are two cases,
4378      either a GIMPLE_CALL returning a value, or just a plain
4379      GIMPLE_CALL when we are not.
4380
4381      In non-ipa mode, we need to generate constraints for each
4382      pointer passed by address.  */
4383   else if (is_gimple_call (t))
4384     find_func_aliases_for_call (t);
4385     
4386   /* Otherwise, just a regular assignment statement.  Only care about
4387      operations with pointer result, others are dealt with as escape
4388      points if they have pointer operands.  */
4389   else if (is_gimple_assign (t))
4390     {
4391       /* Otherwise, just a regular assignment statement.  */
4392       tree lhsop = gimple_assign_lhs (t);
4393       tree rhsop = (gimple_num_ops (t) == 2) ? gimple_assign_rhs1 (t) : NULL;
4394
4395       if (rhsop && AGGREGATE_TYPE_P (TREE_TYPE (lhsop)))
4396         do_structure_copy (lhsop, rhsop);
4397       else
4398         {
4399           enum tree_code code = gimple_assign_rhs_code (t);
4400
4401           get_constraint_for (lhsop, &lhsc);
4402
4403           if (code == POINTER_PLUS_EXPR)
4404             get_constraint_for_ptr_offset (gimple_assign_rhs1 (t),
4405                                            gimple_assign_rhs2 (t), &rhsc);
4406           else if (code == BIT_AND_EXPR
4407                    && TREE_CODE (gimple_assign_rhs2 (t)) == INTEGER_CST)
4408             {
4409               /* Aligning a pointer via a BIT_AND_EXPR is offsetting
4410                  the pointer.  Handle it by offsetting it by UNKNOWN.  */
4411               get_constraint_for_ptr_offset (gimple_assign_rhs1 (t),
4412                                              NULL_TREE, &rhsc);
4413             }
4414           else if ((CONVERT_EXPR_CODE_P (code)
4415                     && !(POINTER_TYPE_P (gimple_expr_type (t))
4416                          && !POINTER_TYPE_P (TREE_TYPE (rhsop))))
4417                    || gimple_assign_single_p (t))
4418             get_constraint_for_rhs (rhsop, &rhsc);
4419           else if (truth_value_p (code))
4420             /* Truth value results are not pointer (parts).  Or at least
4421                very very unreasonable obfuscation of a part.  */
4422             ;
4423           else
4424             {
4425               /* All other operations are merges.  */
4426               VEC (ce_s, heap) *tmp = NULL;
4427               struct constraint_expr *rhsp;
4428               unsigned i, j;
4429               get_constraint_for_rhs (gimple_assign_rhs1 (t), &rhsc);
4430               for (i = 2; i < gimple_num_ops (t); ++i)
4431                 {
4432                   get_constraint_for_rhs (gimple_op (t, i), &tmp);
4433                   FOR_EACH_VEC_ELT (ce_s, tmp, j, rhsp)
4434                     VEC_safe_push (ce_s, heap, rhsc, rhsp);
4435                   VEC_truncate (ce_s, tmp, 0);
4436                 }
4437               VEC_free (ce_s, heap, tmp);
4438             }
4439           process_all_all_constraints (lhsc, rhsc);
4440         }
4441       /* If there is a store to a global variable the rhs escapes.  */
4442       if ((lhsop = get_base_address (lhsop)) != NULL_TREE
4443           && DECL_P (lhsop)
4444           && is_global_var (lhsop)
4445           && (!in_ipa_mode
4446               || DECL_EXTERNAL (lhsop) || TREE_PUBLIC (lhsop)))
4447         make_escape_constraint (rhsop);
4448       /* If this is a conversion of a non-restrict pointer to a
4449          restrict pointer track it with a new heapvar.  */
4450       else if (gimple_assign_cast_p (t)
4451                && POINTER_TYPE_P (TREE_TYPE (rhsop))
4452                && POINTER_TYPE_P (TREE_TYPE (lhsop))
4453                && !TYPE_RESTRICT (TREE_TYPE (rhsop))
4454                && TYPE_RESTRICT (TREE_TYPE (lhsop)))
4455         make_constraint_from_restrict (get_vi_for_tree (lhsop),
4456                                        "CAST_RESTRICT");
4457     }
4458   /* Handle escapes through return.  */
4459   else if (gimple_code (t) == GIMPLE_RETURN
4460            && gimple_return_retval (t) != NULL_TREE)
4461     {
4462       fi = NULL;
4463       if (!in_ipa_mode
4464           || !(fi = get_vi_for_tree (cfun->decl)))
4465         make_escape_constraint (gimple_return_retval (t));
4466       else if (in_ipa_mode
4467                && fi != NULL)
4468         {
4469           struct constraint_expr lhs ;
4470           struct constraint_expr *rhsp;
4471           unsigned i;
4472
4473           lhs = get_function_part_constraint (fi, fi_result);
4474           get_constraint_for_rhs (gimple_return_retval (t), &rhsc);
4475           FOR_EACH_VEC_ELT (ce_s, rhsc, i, rhsp)
4476             process_constraint (new_constraint (lhs, *rhsp));
4477         }
4478     }
4479   /* Handle asms conservatively by adding escape constraints to everything.  */
4480   else if (gimple_code (t) == GIMPLE_ASM)
4481     {
4482       unsigned i, noutputs;
4483       const char **oconstraints;
4484       const char *constraint;
4485       bool allows_mem, allows_reg, is_inout;
4486
4487       noutputs = gimple_asm_noutputs (t);
4488       oconstraints = XALLOCAVEC (const char *, noutputs);
4489
4490       for (i = 0; i < noutputs; ++i)
4491         {
4492           tree link = gimple_asm_output_op (t, i);
4493           tree op = TREE_VALUE (link);
4494
4495           constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
4496           oconstraints[i] = constraint;
4497           parse_output_constraint (&constraint, i, 0, 0, &allows_mem,
4498                                    &allows_reg, &is_inout);
4499
4500           /* A memory constraint makes the address of the operand escape.  */
4501           if (!allows_reg && allows_mem)
4502             make_escape_constraint (build_fold_addr_expr (op));
4503
4504           /* The asm may read global memory, so outputs may point to
4505              any global memory.  */
4506           if (op)
4507             {
4508               VEC(ce_s, heap) *lhsc = NULL;
4509               struct constraint_expr rhsc, *lhsp;
4510               unsigned j;
4511               get_constraint_for (op, &lhsc);
4512               rhsc.var = nonlocal_id;
4513               rhsc.offset = 0;
4514               rhsc.type = SCALAR;
4515               FOR_EACH_VEC_ELT (ce_s, lhsc, j, lhsp)
4516                 process_constraint (new_constraint (*lhsp, rhsc));
4517               VEC_free (ce_s, heap, lhsc);
4518             }
4519         }
4520       for (i = 0; i < gimple_asm_ninputs (t); ++i)
4521         {
4522           tree link = gimple_asm_input_op (t, i);
4523           tree op = TREE_VALUE (link);
4524
4525           constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
4526
4527           parse_input_constraint (&constraint, 0, 0, noutputs, 0, oconstraints,
4528                                   &allows_mem, &allows_reg);
4529
4530           /* A memory constraint makes the address of the operand escape.  */
4531           if (!allows_reg && allows_mem)
4532             make_escape_constraint (build_fold_addr_expr (op));
4533           /* Strictly we'd only need the constraint to ESCAPED if
4534              the asm clobbers memory, otherwise using something
4535              along the lines of per-call clobbers/uses would be enough.  */
4536           else if (op)
4537             make_escape_constraint (op);
4538         }
4539     }
4540
4541   VEC_free (ce_s, heap, rhsc);
4542   VEC_free (ce_s, heap, lhsc);
4543 }
4544
4545
4546 /* Create a constraint adding to the clobber set of FI the memory
4547    pointed to by PTR.  */
4548
4549 static void
4550 process_ipa_clobber (varinfo_t fi, tree ptr)
4551 {
4552   VEC(ce_s, heap) *ptrc = NULL;
4553   struct constraint_expr *c, lhs;
4554   unsigned i;
4555   get_constraint_for_rhs (ptr, &ptrc);
4556   lhs = get_function_part_constraint (fi, fi_clobbers);
4557   FOR_EACH_VEC_ELT (ce_s, ptrc, i, c)
4558     process_constraint (new_constraint (lhs, *c));
4559   VEC_free (ce_s, heap, ptrc);
4560 }
4561
4562 /* Walk statement T setting up clobber and use constraints according to the
4563    references found in T.  This function is a main part of the
4564    IPA constraint builder.  */
4565
4566 static void
4567 find_func_clobbers (gimple origt)
4568 {
4569   gimple t = origt;
4570   VEC(ce_s, heap) *lhsc = NULL;
4571   VEC(ce_s, heap) *rhsc = NULL;
4572   varinfo_t fi;
4573
4574   /* Add constraints for clobbered/used in IPA mode.
4575      We are not interested in what automatic variables are clobbered
4576      or used as we only use the information in the caller to which
4577      they do not escape.  */
4578   gcc_assert (in_ipa_mode);
4579
4580   /* If the stmt refers to memory in any way it better had a VUSE.  */
4581   if (gimple_vuse (t) == NULL_TREE)
4582     return;
4583
4584   /* We'd better have function information for the current function.  */
4585   fi = lookup_vi_for_tree (cfun->decl);
4586   gcc_assert (fi != NULL);
4587
4588   /* Account for stores in assignments and calls.  */
4589   if (gimple_vdef (t) != NULL_TREE
4590       && gimple_has_lhs (t))
4591     {
4592       tree lhs = gimple_get_lhs (t);
4593       tree tem = lhs;
4594       while (handled_component_p (tem))
4595         tem = TREE_OPERAND (tem, 0);
4596       if ((DECL_P (tem)
4597            && !auto_var_in_fn_p (tem, cfun->decl))
4598           || INDIRECT_REF_P (tem)
4599           || (TREE_CODE (tem) == MEM_REF
4600               && !(TREE_CODE (TREE_OPERAND (tem, 0)) == ADDR_EXPR
4601                    && auto_var_in_fn_p
4602                         (TREE_OPERAND (TREE_OPERAND (tem, 0), 0), cfun->decl))))
4603         {
4604           struct constraint_expr lhsc, *rhsp;
4605           unsigned i;
4606           lhsc = get_function_part_constraint (fi, fi_clobbers);
4607           get_constraint_for_address_of (lhs, &rhsc);
4608           FOR_EACH_VEC_ELT (ce_s, rhsc, i, rhsp)
4609             process_constraint (new_constraint (lhsc, *rhsp));
4610           VEC_free (ce_s, heap, rhsc);
4611         }
4612     }
4613
4614   /* Account for uses in assigments and returns.  */
4615   if (gimple_assign_single_p (t)
4616       || (gimple_code (t) == GIMPLE_RETURN
4617           && gimple_return_retval (t) != NULL_TREE))
4618     {
4619       tree rhs = (gimple_assign_single_p (t)
4620                   ? gimple_assign_rhs1 (t) : gimple_return_retval (t));
4621       tree tem = rhs;
4622       while (handled_component_p (tem))
4623         tem = TREE_OPERAND (tem, 0);
4624       if ((DECL_P (tem)
4625            && !auto_var_in_fn_p (tem, cfun->decl))
4626           || INDIRECT_REF_P (tem)
4627           || (TREE_CODE (tem) == MEM_REF
4628               && !(TREE_CODE (TREE_OPERAND (tem, 0)) == ADDR_EXPR
4629                    && auto_var_in_fn_p
4630                         (TREE_OPERAND (TREE_OPERAND (tem, 0), 0), cfun->decl))))
4631         {
4632           struct constraint_expr lhs, *rhsp;
4633           unsigned i;
4634           lhs = get_function_part_constraint (fi, fi_uses);
4635           get_constraint_for_address_of (rhs, &rhsc);
4636           FOR_EACH_VEC_ELT (ce_s, rhsc, i, rhsp)
4637             process_constraint (new_constraint (lhs, *rhsp));
4638           VEC_free (ce_s, heap, rhsc);
4639         }
4640     }
4641
4642   if (is_gimple_call (t))
4643     {
4644       varinfo_t cfi = NULL;
4645       tree decl = gimple_call_fndecl (t);
4646       struct constraint_expr lhs, rhs;
4647       unsigned i, j;
4648
4649       /* For builtins we do not have separate function info.  For those
4650          we do not generate escapes for we have to generate clobbers/uses.  */
4651       if (decl
4652           && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
4653         switch (DECL_FUNCTION_CODE (decl))
4654           {
4655           /* The following functions use and clobber memory pointed to
4656              by their arguments.  */
4657           case BUILT_IN_STRCPY:
4658           case BUILT_IN_STRNCPY:
4659           case BUILT_IN_BCOPY:
4660           case BUILT_IN_MEMCPY:
4661           case BUILT_IN_MEMMOVE:
4662           case BUILT_IN_MEMPCPY:
4663           case BUILT_IN_STPCPY:
4664           case BUILT_IN_STPNCPY:
4665           case BUILT_IN_STRCAT:
4666           case BUILT_IN_STRNCAT:
4667           case BUILT_IN_STRCPY_CHK:
4668           case BUILT_IN_STRNCPY_CHK:
4669           case BUILT_IN_MEMCPY_CHK:
4670           case BUILT_IN_MEMMOVE_CHK:
4671           case BUILT_IN_MEMPCPY_CHK:
4672           case BUILT_IN_STPCPY_CHK:
4673           case BUILT_IN_STRCAT_CHK:
4674           case BUILT_IN_STRNCAT_CHK:
4675             {
4676               tree dest = gimple_call_arg (t, (DECL_FUNCTION_CODE (decl)
4677                                                == BUILT_IN_BCOPY ? 1 : 0));
4678               tree src = gimple_call_arg (t, (DECL_FUNCTION_CODE (decl)
4679                                               == BUILT_IN_BCOPY ? 0 : 1));
4680               unsigned i;
4681               struct constraint_expr *rhsp, *lhsp;
4682               get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4683               lhs = get_function_part_constraint (fi, fi_clobbers);
4684               FOR_EACH_VEC_ELT (ce_s, lhsc, i, lhsp)
4685                 process_constraint (new_constraint (lhs, *lhsp));
4686               VEC_free (ce_s, heap, lhsc);
4687               get_constraint_for_ptr_offset (src, NULL_TREE, &rhsc);
4688               lhs = get_function_part_constraint (fi, fi_uses);
4689               FOR_EACH_VEC_ELT (ce_s, rhsc, i, rhsp)
4690                 process_constraint (new_constraint (lhs, *rhsp));
4691               VEC_free (ce_s, heap, rhsc);
4692               return;
4693             }
4694           /* The following function clobbers memory pointed to by
4695              its argument.  */
4696           case BUILT_IN_MEMSET:
4697           case BUILT_IN_MEMSET_CHK:
4698             {
4699               tree dest = gimple_call_arg (t, 0);
4700               unsigned i;
4701               ce_s *lhsp;
4702               get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4703               lhs = get_function_part_constraint (fi, fi_clobbers);
4704               FOR_EACH_VEC_ELT (ce_s, lhsc, i, lhsp)
4705                 process_constraint (new_constraint (lhs, *lhsp));
4706               VEC_free (ce_s, heap, lhsc);
4707               return;
4708             }
4709           /* The following functions clobber their second and third
4710              arguments.  */
4711           case BUILT_IN_SINCOS:
4712           case BUILT_IN_SINCOSF:
4713           case BUILT_IN_SINCOSL:
4714             {
4715               process_ipa_clobber (fi, gimple_call_arg (t, 1));
4716               process_ipa_clobber (fi, gimple_call_arg (t, 2));
4717               return;
4718             }
4719           /* The following functions clobber their second argument.  */
4720           case BUILT_IN_FREXP:
4721           case BUILT_IN_FREXPF:
4722           case BUILT_IN_FREXPL:
4723           case BUILT_IN_LGAMMA_R:
4724           case BUILT_IN_LGAMMAF_R:
4725           case BUILT_IN_LGAMMAL_R:
4726           case BUILT_IN_GAMMA_R:
4727           case BUILT_IN_GAMMAF_R:
4728           case BUILT_IN_GAMMAL_R:
4729           case BUILT_IN_MODF:
4730           case BUILT_IN_MODFF:
4731           case BUILT_IN_MODFL:
4732             {
4733               process_ipa_clobber (fi, gimple_call_arg (t, 1));
4734               return;
4735             }
4736           /* The following functions clobber their third argument.  */
4737           case BUILT_IN_REMQUO:
4738           case BUILT_IN_REMQUOF:
4739           case BUILT_IN_REMQUOL:
4740             {
4741               process_ipa_clobber (fi, gimple_call_arg (t, 2));
4742               return;
4743             }
4744           /* The following functions neither read nor clobber memory.  */
4745           case BUILT_IN_ASSUME_ALIGNED:
4746           case BUILT_IN_FREE:
4747             return;
4748           /* Trampolines are of no interest to us.  */
4749           case BUILT_IN_INIT_TRAMPOLINE:
4750           case BUILT_IN_ADJUST_TRAMPOLINE:
4751             return;
4752           case BUILT_IN_VA_START:
4753           case BUILT_IN_VA_END:
4754             return;
4755           /* printf-style functions may have hooks to set pointers to
4756              point to somewhere into the generated string.  Leave them
4757              for a later excercise...  */
4758           default:
4759             /* Fallthru to general call handling.  */;
4760           }
4761
4762       /* Parameters passed by value are used.  */
4763       lhs = get_function_part_constraint (fi, fi_uses);
4764       for (i = 0; i < gimple_call_num_args (t); i++)
4765         {
4766           struct constraint_expr *rhsp;
4767           tree arg = gimple_call_arg (t, i);
4768
4769           if (TREE_CODE (arg) == SSA_NAME
4770               || is_gimple_min_invariant (arg))
4771             continue;
4772
4773           get_constraint_for_address_of (arg, &rhsc);
4774           FOR_EACH_VEC_ELT (ce_s, rhsc, j, rhsp)
4775             process_constraint (new_constraint (lhs, *rhsp));
4776           VEC_free (ce_s, heap, rhsc);
4777         }
4778
4779       /* Build constraints for propagating clobbers/uses along the
4780          callgraph edges.  */
4781       cfi = get_fi_for_callee (t);
4782       if (cfi->id == anything_id)
4783         {
4784           if (gimple_vdef (t))
4785             make_constraint_from (first_vi_for_offset (fi, fi_clobbers),
4786                                   anything_id);
4787           make_constraint_from (first_vi_for_offset (fi, fi_uses),
4788                                 anything_id);
4789           return;
4790         }
4791
4792       /* For callees without function info (that's external functions),
4793          ESCAPED is clobbered and used.  */
4794       if (gimple_call_fndecl (t)
4795           && !cfi->is_fn_info)
4796         {
4797           varinfo_t vi;
4798
4799           if (gimple_vdef (t))
4800             make_copy_constraint (first_vi_for_offset (fi, fi_clobbers),
4801                                   escaped_id);
4802           make_copy_constraint (first_vi_for_offset (fi, fi_uses), escaped_id);
4803
4804           /* Also honor the call statement use/clobber info.  */
4805           if ((vi = lookup_call_clobber_vi (t)) != NULL)
4806             make_copy_constraint (first_vi_for_offset (fi, fi_clobbers),
4807                                   vi->id);
4808           if ((vi = lookup_call_use_vi (t)) != NULL)
4809             make_copy_constraint (first_vi_for_offset (fi, fi_uses),
4810                                   vi->id);
4811           return;
4812         }
4813
4814       /* Otherwise the caller clobbers and uses what the callee does.
4815          ???  This should use a new complex constraint that filters
4816          local variables of the callee.  */
4817       if (gimple_vdef (t))
4818         {
4819           lhs = get_function_part_constraint (fi, fi_clobbers);
4820           rhs = get_function_part_constraint (cfi, fi_clobbers);
4821           process_constraint (new_constraint (lhs, rhs));
4822         }
4823       lhs = get_function_part_constraint (fi, fi_uses);
4824       rhs = get_function_part_constraint (cfi, fi_uses);
4825       process_constraint (new_constraint (lhs, rhs));
4826     }
4827   else if (gimple_code (t) == GIMPLE_ASM)
4828     {
4829       /* ???  Ick.  We can do better.  */
4830       if (gimple_vdef (t))
4831         make_constraint_from (first_vi_for_offset (fi, fi_clobbers),
4832                               anything_id);
4833       make_constraint_from (first_vi_for_offset (fi, fi_uses),
4834                             anything_id);
4835     }
4836
4837   VEC_free (ce_s, heap, rhsc);
4838 }
4839
4840
4841 /* Find the first varinfo in the same variable as START that overlaps with
4842    OFFSET.  Return NULL if we can't find one.  */
4843
4844 static varinfo_t
4845 first_vi_for_offset (varinfo_t start, unsigned HOST_WIDE_INT offset)
4846 {
4847   /* If the offset is outside of the variable, bail out.  */
4848   if (offset >= start->fullsize)
4849     return NULL;
4850
4851   /* If we cannot reach offset from start, lookup the first field
4852      and start from there.  */
4853   if (start->offset > offset)
4854     start = lookup_vi_for_tree (start->decl);
4855
4856   while (start)
4857     {
4858       /* We may not find a variable in the field list with the actual
4859          offset when when we have glommed a structure to a variable.
4860          In that case, however, offset should still be within the size
4861          of the variable. */
4862       if (offset >= start->offset
4863           && (offset - start->offset) < start->size)
4864         return start;
4865
4866       start= start->next;
4867     }
4868
4869   return NULL;
4870 }
4871
4872 /* Find the first varinfo in the same variable as START that overlaps with
4873    OFFSET.  If there is no such varinfo the varinfo directly preceding
4874    OFFSET is returned.  */
4875
4876 static varinfo_t
4877 first_or_preceding_vi_for_offset (varinfo_t start,
4878                                   unsigned HOST_WIDE_INT offset)
4879 {
4880   /* If we cannot reach offset from start, lookup the first field
4881      and start from there.  */
4882   if (start->offset > offset)
4883     start = lookup_vi_for_tree (start->decl);
4884
4885   /* We may not find a variable in the field list with the actual
4886      offset when when we have glommed a structure to a variable.
4887      In that case, however, offset should still be within the size
4888      of the variable.
4889      If we got beyond the offset we look for return the field
4890      directly preceding offset which may be the last field.  */
4891   while (start->next
4892          && offset >= start->offset
4893          && !((offset - start->offset) < start->size))
4894     start = start->next;
4895
4896   return start;
4897 }
4898
4899
4900 /* This structure is used during pushing fields onto the fieldstack
4901    to track the offset of the field, since bitpos_of_field gives it
4902    relative to its immediate containing type, and we want it relative
4903    to the ultimate containing object.  */
4904
4905 struct fieldoff
4906 {
4907   /* Offset from the base of the base containing object to this field.  */
4908   HOST_WIDE_INT offset;
4909
4910   /* Size, in bits, of the field.  */
4911   unsigned HOST_WIDE_INT size;
4912
4913   unsigned has_unknown_size : 1;
4914
4915   unsigned must_have_pointers : 1;
4916
4917   unsigned may_have_pointers : 1;
4918
4919   unsigned only_restrict_pointers : 1;
4920 };
4921 typedef struct fieldoff fieldoff_s;
4922
4923 DEF_VEC_O(fieldoff_s);
4924 DEF_VEC_ALLOC_O(fieldoff_s,heap);
4925
4926 /* qsort comparison function for two fieldoff's PA and PB */
4927
4928 static int
4929 fieldoff_compare (const void *pa, const void *pb)
4930 {
4931   const fieldoff_s *foa = (const fieldoff_s *)pa;
4932   const fieldoff_s *fob = (const fieldoff_s *)pb;
4933   unsigned HOST_WIDE_INT foasize, fobsize;
4934
4935   if (foa->offset < fob->offset)
4936     return -1;
4937   else if (foa->offset > fob->offset)
4938     return 1;
4939
4940   foasize = foa->size;
4941   fobsize = fob->size;
4942   if (foasize < fobsize)
4943     return -1;
4944   else if (foasize > fobsize)
4945     return 1;
4946   return 0;
4947 }
4948
4949 /* Sort a fieldstack according to the field offset and sizes.  */
4950 static void
4951 sort_fieldstack (VEC(fieldoff_s,heap) *fieldstack)
4952 {
4953   VEC_qsort (fieldoff_s, fieldstack, fieldoff_compare);
4954 }
4955
4956 /* Return true if V is a tree that we can have subvars for.
4957    Normally, this is any aggregate type.  Also complex
4958    types which are not gimple registers can have subvars.  */
4959
4960 static inline bool
4961 var_can_have_subvars (const_tree v)
4962 {
4963   /* Volatile variables should never have subvars.  */
4964   if (TREE_THIS_VOLATILE (v))
4965     return false;
4966
4967   /* Non decls or memory tags can never have subvars.  */
4968   if (!DECL_P (v))
4969     return false;
4970
4971   /* Aggregates without overlapping fields can have subvars.  */
4972   if (TREE_CODE (TREE_TYPE (v)) == RECORD_TYPE)
4973     return true;
4974
4975   return false;
4976 }
4977
4978 /* Return true if T is a type that does contain pointers.  */
4979
4980 static bool
4981 type_must_have_pointers (tree type)
4982 {
4983   if (POINTER_TYPE_P (type))
4984     return true;
4985
4986   if (TREE_CODE (type) == ARRAY_TYPE)
4987     return type_must_have_pointers (TREE_TYPE (type));
4988
4989   /* A function or method can have pointers as arguments, so track
4990      those separately.  */
4991   if (TREE_CODE (type) == FUNCTION_TYPE
4992       || TREE_CODE (type) == METHOD_TYPE)
4993     return true;
4994
4995   return false;
4996 }
4997
4998 static bool
4999 field_must_have_pointers (tree t)
5000 {
5001   return type_must_have_pointers (TREE_TYPE (t));
5002 }
5003
5004 /* Given a TYPE, and a vector of field offsets FIELDSTACK, push all
5005    the fields of TYPE onto fieldstack, recording their offsets along
5006    the way.
5007
5008    OFFSET is used to keep track of the offset in this entire
5009    structure, rather than just the immediately containing structure.
5010    Returns false if the caller is supposed to handle the field we
5011    recursed for.  */
5012
5013 static bool
5014 push_fields_onto_fieldstack (tree type, VEC(fieldoff_s,heap) **fieldstack,
5015                              HOST_WIDE_INT offset)
5016 {
5017   tree field;
5018   bool empty_p = true;
5019
5020   if (TREE_CODE (type) != RECORD_TYPE)
5021     return false;
5022
5023   /* If the vector of fields is growing too big, bail out early.
5024      Callers check for VEC_length <= MAX_FIELDS_FOR_FIELD_SENSITIVE, make
5025      sure this fails.  */
5026   if (VEC_length (fieldoff_s, *fieldstack) > MAX_FIELDS_FOR_FIELD_SENSITIVE)
5027     return false;
5028
5029   for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
5030     if (TREE_CODE (field) == FIELD_DECL)
5031       {
5032         bool push = false;
5033         HOST_WIDE_INT foff = bitpos_of_field (field);
5034
5035         if (!var_can_have_subvars (field)
5036             || TREE_CODE (TREE_TYPE (field)) == QUAL_UNION_TYPE
5037             || TREE_CODE (TREE_TYPE (field)) == UNION_TYPE)
5038           push = true;
5039         else if (!push_fields_onto_fieldstack
5040                     (TREE_TYPE (field), fieldstack, offset + foff)
5041                  && (DECL_SIZE (field)
5042                      && !integer_zerop (DECL_SIZE (field))))
5043           /* Empty structures may have actual size, like in C++.  So
5044              see if we didn't push any subfields and the size is
5045              nonzero, push the field onto the stack.  */
5046           push = true;
5047
5048         if (push)
5049           {
5050             fieldoff_s *pair = NULL;
5051             bool has_unknown_size = false;
5052             bool must_have_pointers_p;
5053
5054             if (!VEC_empty (fieldoff_s, *fieldstack))
5055               pair = VEC_last (fieldoff_s, *fieldstack);
5056
5057             /* If there isn't anything at offset zero, create sth.  */
5058             if (!pair
5059                 && offset + foff != 0)
5060               {
5061                 pair = VEC_safe_push (fieldoff_s, heap, *fieldstack, NULL);
5062                 pair->offset = 0;
5063                 pair->size = offset + foff;
5064                 pair->has_unknown_size = false;
5065                 pair->must_have_pointers = false;
5066                 pair->may_have_pointers = false;
5067                 pair->only_restrict_pointers = false;
5068               }
5069
5070             if (!DECL_SIZE (field)
5071                 || !host_integerp (DECL_SIZE (field), 1))
5072               has_unknown_size = true;
5073
5074             /* If adjacent fields do not contain pointers merge them.  */
5075             must_have_pointers_p = field_must_have_pointers (field);
5076             if (pair
5077                 && !has_unknown_size
5078                 && !must_have_pointers_p
5079                 && !pair->must_have_pointers
5080                 && !pair->has_unknown_size
5081                 && pair->offset + (HOST_WIDE_INT)pair->size == offset + foff)
5082               {
5083                 pair->size += TREE_INT_CST_LOW (DECL_SIZE (field));
5084               }
5085             else
5086               {
5087                 pair = VEC_safe_push (fieldoff_s, heap, *fieldstack, NULL);
5088                 pair->offset = offset + foff;
5089                 pair->has_unknown_size = has_unknown_size;
5090                 if (!has_unknown_size)
5091                   pair->size = TREE_INT_CST_LOW (DECL_SIZE (field));
5092                 else
5093                   pair->size = -1;
5094                 pair->must_have_pointers = must_have_pointers_p;
5095                 pair->may_have_pointers = true;
5096                 pair->only_restrict_pointers
5097                   = (!has_unknown_size
5098                      && POINTER_TYPE_P (TREE_TYPE (field))
5099                      && TYPE_RESTRICT (TREE_TYPE (field)));
5100               }
5101           }
5102
5103         empty_p = false;
5104       }
5105
5106   return !empty_p;
5107 }
5108
5109 /* Count the number of arguments DECL has, and set IS_VARARGS to true
5110    if it is a varargs function.  */
5111
5112 static unsigned int
5113 count_num_arguments (tree decl, bool *is_varargs)
5114 {
5115   unsigned int num = 0;
5116   tree t;
5117
5118   /* Capture named arguments for K&R functions.  They do not
5119      have a prototype and thus no TYPE_ARG_TYPES.  */
5120   for (t = DECL_ARGUMENTS (decl); t; t = DECL_CHAIN (t))
5121     ++num;
5122
5123   /* Check if the function has variadic arguments.  */
5124   for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
5125     if (TREE_VALUE (t) == void_type_node)
5126       break;
5127   if (!t)
5128     *is_varargs = true;
5129
5130   return num;
5131 }
5132
5133 /* Creation function node for DECL, using NAME, and return the index
5134    of the variable we've created for the function.  */
5135
5136 static varinfo_t
5137 create_function_info_for (tree decl, const char *name)
5138 {
5139   struct function *fn = DECL_STRUCT_FUNCTION (decl);
5140   varinfo_t vi, prev_vi;
5141   tree arg;
5142   unsigned int i;
5143   bool is_varargs = false;
5144   unsigned int num_args = count_num_arguments (decl, &is_varargs);
5145
5146   /* Create the variable info.  */
5147
5148   vi = new_var_info (decl, name);
5149   vi->offset = 0;
5150   vi->size = 1;
5151   vi->fullsize = fi_parm_base + num_args;
5152   vi->is_fn_info = 1;
5153   vi->may_have_pointers = false;
5154   if (is_varargs)
5155     vi->fullsize = ~0;
5156   insert_vi_for_tree (vi->decl, vi);
5157
5158   prev_vi = vi;
5159
5160   /* Create a variable for things the function clobbers and one for
5161      things the function uses.  */
5162     {
5163       varinfo_t clobbervi, usevi;
5164       const char *newname;
5165       char *tempname;
5166
5167       asprintf (&tempname, "%s.clobber", name);
5168       newname = ggc_strdup (tempname);
5169       free (tempname);
5170
5171       clobbervi = new_var_info (NULL, newname);
5172       clobbervi->offset = fi_clobbers;
5173       clobbervi->size = 1;
5174       clobbervi->fullsize = vi->fullsize;
5175       clobbervi->is_full_var = true;
5176       clobbervi->is_global_var = false;
5177       gcc_assert (prev_vi->offset < clobbervi->offset);
5178       prev_vi->next = clobbervi;
5179       prev_vi = clobbervi;
5180
5181       asprintf (&tempname, "%s.use", name);
5182       newname = ggc_strdup (tempname);
5183       free (tempname);
5184
5185       usevi = new_var_info (NULL, newname);
5186       usevi->offset = fi_uses;
5187       usevi->size = 1;
5188       usevi->fullsize = vi->fullsize;
5189       usevi->is_full_var = true;
5190       usevi->is_global_var = false;
5191       gcc_assert (prev_vi->offset < usevi->offset);
5192       prev_vi->next = usevi;
5193       prev_vi = usevi;
5194     }
5195
5196   /* And one for the static chain.  */
5197   if (fn->static_chain_decl != NULL_TREE)
5198     {
5199       varinfo_t chainvi;
5200       const char *newname;
5201       char *tempname;
5202
5203       asprintf (&tempname, "%s.chain", name);
5204       newname = ggc_strdup (tempname);
5205       free (tempname);
5206
5207       chainvi = new_var_info (fn->static_chain_decl, newname);
5208       chainvi->offset = fi_static_chain;
5209       chainvi->size = 1;
5210       chainvi->fullsize = vi->fullsize;
5211       chainvi->is_full_var = true;
5212       chainvi->is_global_var = false;
5213       gcc_assert (prev_vi->offset < chainvi->offset);
5214       prev_vi->next = chainvi;
5215       prev_vi = chainvi;
5216       insert_vi_for_tree (fn->static_chain_decl, chainvi);
5217     }
5218
5219   /* Create a variable for the return var.  */
5220   if (DECL_RESULT (decl) != NULL
5221       || !VOID_TYPE_P (TREE_TYPE (TREE_TYPE (decl))))
5222     {
5223       varinfo_t resultvi;
5224       const char *newname;
5225       char *tempname;
5226       tree resultdecl = decl;
5227
5228       if (DECL_RESULT (decl))
5229         resultdecl = DECL_RESULT (decl);
5230
5231       asprintf (&tempname, "%s.result", name);
5232       newname = ggc_strdup (tempname);
5233       free (tempname);
5234
5235       resultvi = new_var_info (resultdecl, newname);
5236       resultvi->offset = fi_result;
5237       resultvi->size = 1;
5238       resultvi->fullsize = vi->fullsize;
5239       resultvi->is_full_var = true;
5240       if (DECL_RESULT (decl))
5241         resultvi->may_have_pointers = true;
5242       gcc_assert (prev_vi->offset < resultvi->offset);
5243       prev_vi->next = resultvi;
5244       prev_vi = resultvi;
5245       if (DECL_RESULT (decl))
5246         insert_vi_for_tree (DECL_RESULT (decl), resultvi);
5247     }
5248
5249   /* Set up variables for each argument.  */
5250   arg = DECL_ARGUMENTS (decl);
5251   for (i = 0; i < num_args; i++)
5252     {
5253       varinfo_t argvi;
5254       const char *newname;
5255       char *tempname;
5256       tree argdecl = decl;
5257
5258       if (arg)
5259         argdecl = arg;
5260
5261       asprintf (&tempname, "%s.arg%d", name, i);
5262       newname = ggc_strdup (tempname);
5263       free (tempname);
5264
5265       argvi = new_var_info (argdecl, newname);
5266       argvi->offset = fi_parm_base + i;
5267       argvi->size = 1;
5268       argvi->is_full_var = true;
5269       argvi->fullsize = vi->fullsize;
5270       if (arg)
5271         argvi->may_have_pointers = true;
5272       gcc_assert (prev_vi->offset < argvi->offset);
5273       prev_vi->next = argvi;
5274       prev_vi = argvi;
5275       if (arg)
5276         {
5277           insert_vi_for_tree (arg, argvi);
5278           arg = DECL_CHAIN (arg);
5279         }
5280     }
5281
5282   /* Add one representative for all further args.  */
5283   if (is_varargs)
5284     {
5285       varinfo_t argvi;
5286       const char *newname;
5287       char *tempname;
5288       tree decl;
5289
5290       asprintf (&tempname, "%s.varargs", name);
5291       newname = ggc_strdup (tempname);
5292       free (tempname);
5293
5294       /* We need sth that can be pointed to for va_start.  */
5295       decl = build_fake_var_decl (ptr_type_node);
5296
5297       argvi = new_var_info (decl, newname);
5298       argvi->offset = fi_parm_base + num_args;
5299       argvi->size = ~0;
5300       argvi->is_full_var = true;
5301       argvi->is_heap_var = true;
5302       argvi->fullsize = vi->fullsize;
5303       gcc_assert (prev_vi->offset < argvi->offset);
5304       prev_vi->next = argvi;
5305       prev_vi = argvi;
5306     }
5307
5308   return vi;
5309 }
5310
5311
5312 /* Return true if FIELDSTACK contains fields that overlap.
5313    FIELDSTACK is assumed to be sorted by offset.  */
5314
5315 static bool
5316 check_for_overlaps (VEC (fieldoff_s,heap) *fieldstack)
5317 {
5318   fieldoff_s *fo = NULL;
5319   unsigned int i;
5320   HOST_WIDE_INT lastoffset = -1;
5321
5322   FOR_EACH_VEC_ELT (fieldoff_s, fieldstack, i, fo)
5323     {
5324       if (fo->offset == lastoffset)
5325         return true;
5326       lastoffset = fo->offset;
5327     }
5328   return false;
5329 }
5330
5331 /* Create a varinfo structure for NAME and DECL, and add it to VARMAP.
5332    This will also create any varinfo structures necessary for fields
5333    of DECL.  */
5334
5335 static varinfo_t
5336 create_variable_info_for_1 (tree decl, const char *name)
5337 {
5338   varinfo_t vi, newvi;
5339   tree decl_type = TREE_TYPE (decl);
5340   tree declsize = DECL_P (decl) ? DECL_SIZE (decl) : TYPE_SIZE (decl_type);
5341   VEC (fieldoff_s,heap) *fieldstack = NULL;
5342   fieldoff_s *fo;
5343   unsigned int i;
5344
5345   if (!declsize
5346       || !host_integerp (declsize, 1))
5347     {
5348       vi = new_var_info (decl, name);
5349       vi->offset = 0;
5350       vi->size = ~0;
5351       vi->fullsize = ~0;
5352       vi->is_unknown_size_var = true;
5353       vi->is_full_var = true;
5354       vi->may_have_pointers = true;
5355       return vi;
5356     }
5357
5358   /* Collect field information.  */
5359   if (use_field_sensitive
5360       && var_can_have_subvars (decl)
5361       /* ???  Force us to not use subfields for global initializers
5362          in IPA mode.  Else we'd have to parse arbitrary initializers.  */
5363       && !(in_ipa_mode
5364            && is_global_var (decl)
5365            && DECL_INITIAL (decl)))
5366     {
5367       fieldoff_s *fo = NULL;
5368       bool notokay = false;
5369       unsigned int i;
5370
5371       push_fields_onto_fieldstack (decl_type, &fieldstack, 0);
5372
5373       for (i = 0; !notokay && VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
5374         if (fo->has_unknown_size
5375             || fo->offset < 0)
5376           {
5377             notokay = true;
5378             break;
5379           }
5380
5381       /* We can't sort them if we have a field with a variable sized type,
5382          which will make notokay = true.  In that case, we are going to return
5383          without creating varinfos for the fields anyway, so sorting them is a
5384          waste to boot.  */
5385       if (!notokay)
5386         {
5387           sort_fieldstack (fieldstack);
5388           /* Due to some C++ FE issues, like PR 22488, we might end up
5389              what appear to be overlapping fields even though they,
5390              in reality, do not overlap.  Until the C++ FE is fixed,
5391              we will simply disable field-sensitivity for these cases.  */
5392           notokay = check_for_overlaps (fieldstack);
5393         }
5394
5395       if (notokay)
5396         VEC_free (fieldoff_s, heap, fieldstack);
5397     }
5398
5399   /* If we didn't end up collecting sub-variables create a full
5400      variable for the decl.  */
5401   if (VEC_length (fieldoff_s, fieldstack) <= 1
5402       || VEC_length (fieldoff_s, fieldstack) > MAX_FIELDS_FOR_FIELD_SENSITIVE)
5403     {
5404       vi = new_var_info (decl, name);
5405       vi->offset = 0;
5406       vi->may_have_pointers = true;
5407       vi->fullsize = TREE_INT_CST_LOW (declsize);
5408       vi->size = vi->fullsize;
5409       vi->is_full_var = true;
5410       VEC_free (fieldoff_s, heap, fieldstack);
5411       return vi;
5412     }
5413
5414   vi = new_var_info (decl, name);
5415   vi->fullsize = TREE_INT_CST_LOW (declsize);
5416   for (i = 0, newvi = vi;
5417        VEC_iterate (fieldoff_s, fieldstack, i, fo);
5418        ++i, newvi = newvi->next)
5419     {
5420       const char *newname = "NULL";
5421       char *tempname;
5422
5423       if (dump_file)
5424         {
5425           asprintf (&tempname, "%s." HOST_WIDE_INT_PRINT_DEC
5426                     "+" HOST_WIDE_INT_PRINT_DEC, name, fo->offset, fo->size);
5427           newname = ggc_strdup (tempname);
5428           free (tempname);
5429         }
5430       newvi->name = newname;
5431       newvi->offset = fo->offset;
5432       newvi->size = fo->size;
5433       newvi->fullsize = vi->fullsize;
5434       newvi->may_have_pointers = fo->may_have_pointers;
5435       newvi->only_restrict_pointers = fo->only_restrict_pointers;
5436       if (i + 1 < VEC_length (fieldoff_s, fieldstack))
5437         newvi->next = new_var_info (decl, name);
5438     }
5439
5440   VEC_free (fieldoff_s, heap, fieldstack);
5441
5442   return vi;
5443 }
5444
5445 static unsigned int
5446 create_variable_info_for (tree decl, const char *name)
5447 {
5448   varinfo_t vi = create_variable_info_for_1 (decl, name);
5449   unsigned int id = vi->id;
5450
5451   insert_vi_for_tree (decl, vi);
5452
5453   if (TREE_CODE (decl) != VAR_DECL)
5454     return id;
5455
5456   /* Create initial constraints for globals.  */
5457   for (; vi; vi = vi->next)
5458     {
5459       if (!vi->may_have_pointers
5460           || !vi->is_global_var)
5461         continue;
5462
5463       /* Mark global restrict qualified pointers.  */
5464       if ((POINTER_TYPE_P (TREE_TYPE (decl))
5465            && TYPE_RESTRICT (TREE_TYPE (decl)))
5466           || vi->only_restrict_pointers)
5467         make_constraint_from_restrict (vi, "GLOBAL_RESTRICT");
5468
5469       /* In non-IPA mode the initializer from nonlocal is all we need.  */
5470       if (!in_ipa_mode
5471           || DECL_HARD_REGISTER (decl))
5472         make_copy_constraint (vi, nonlocal_id);
5473
5474       else
5475         {
5476           struct varpool_node *vnode = varpool_get_node (decl);
5477
5478           /* For escaped variables initialize them from nonlocal.  */
5479           if (!varpool_all_refs_explicit_p (vnode))
5480             make_copy_constraint (vi, nonlocal_id);
5481
5482           /* If this is a global variable with an initializer and we are in
5483              IPA mode generate constraints for it.  */
5484           if (DECL_INITIAL (decl))
5485             {
5486               VEC (ce_s, heap) *rhsc = NULL;
5487               struct constraint_expr lhs, *rhsp;
5488               unsigned i;
5489               get_constraint_for_rhs (DECL_INITIAL (decl), &rhsc);
5490               lhs.var = vi->id;
5491               lhs.offset = 0;
5492               lhs.type = SCALAR;
5493               FOR_EACH_VEC_ELT (ce_s, rhsc, i, rhsp)
5494                 process_constraint (new_constraint (lhs, *rhsp));
5495               /* If this is a variable that escapes from the unit
5496                  the initializer escapes as well.  */
5497               if (!varpool_all_refs_explicit_p (vnode))
5498                 {
5499                   lhs.var = escaped_id;
5500                   lhs.offset = 0;
5501                   lhs.type = SCALAR;
5502                   FOR_EACH_VEC_ELT (ce_s, rhsc, i, rhsp)
5503                     process_constraint (new_constraint (lhs, *rhsp));
5504                 }
5505               VEC_free (ce_s, heap, rhsc);
5506             }
5507         }
5508     }
5509
5510   return id;
5511 }
5512
5513 /* Print out the points-to solution for VAR to FILE.  */
5514
5515 static void
5516 dump_solution_for_var (FILE *file, unsigned int var)
5517 {
5518   varinfo_t vi = get_varinfo (var);
5519   unsigned int i;
5520   bitmap_iterator bi;
5521
5522   /* Dump the solution for unified vars anyway, this avoids difficulties
5523      in scanning dumps in the testsuite.  */
5524   fprintf (file, "%s = { ", vi->name);
5525   vi = get_varinfo (find (var));
5526   EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
5527     fprintf (file, "%s ", get_varinfo (i)->name);
5528   fprintf (file, "}");
5529
5530   /* But note when the variable was unified.  */
5531   if (vi->id != var)
5532     fprintf (file, " same as %s", vi->name);
5533
5534   fprintf (file, "\n");
5535 }
5536
5537 /* Print the points-to solution for VAR to stdout.  */
5538
5539 DEBUG_FUNCTION void
5540 debug_solution_for_var (unsigned int var)
5541 {
5542   dump_solution_for_var (stdout, var);
5543 }
5544
5545 /* Create varinfo structures for all of the variables in the
5546    function for intraprocedural mode.  */
5547
5548 static void
5549 intra_create_variable_infos (void)
5550 {
5551   tree t;
5552
5553   /* For each incoming pointer argument arg, create the constraint ARG
5554      = NONLOCAL or a dummy variable if it is a restrict qualified
5555      passed-by-reference argument.  */
5556   for (t = DECL_ARGUMENTS (current_function_decl); t; t = DECL_CHAIN (t))
5557     {
5558       varinfo_t p;
5559
5560       /* For restrict qualified pointers to objects passed by
5561          reference build a real representative for the pointed-to object.  */
5562       if (DECL_BY_REFERENCE (t)
5563           && POINTER_TYPE_P (TREE_TYPE (t))
5564           && TYPE_RESTRICT (TREE_TYPE (t)))
5565         {
5566           struct constraint_expr lhsc, rhsc;
5567           varinfo_t vi;
5568           tree heapvar = build_fake_var_decl (TREE_TYPE (TREE_TYPE (t)));
5569           DECL_EXTERNAL (heapvar) = 1;
5570           vi = create_variable_info_for_1 (heapvar, "PARM_NOALIAS");
5571           insert_vi_for_tree (heapvar, vi);
5572           lhsc.var = get_vi_for_tree (t)->id;
5573           lhsc.type = SCALAR;
5574           lhsc.offset = 0;
5575           rhsc.var = vi->id;
5576           rhsc.type = ADDRESSOF;
5577           rhsc.offset = 0;
5578           process_constraint (new_constraint (lhsc, rhsc));
5579           vi->is_restrict_var = 1;
5580           for (; vi; vi = vi->next)
5581             if (vi->may_have_pointers)
5582               {
5583                 if (vi->only_restrict_pointers)
5584                   make_constraint_from_restrict (vi, "GLOBAL_RESTRICT");
5585                 make_copy_constraint (vi, nonlocal_id);
5586               }
5587           continue;
5588         }
5589
5590       for (p = get_vi_for_tree (t); p; p = p->next)
5591         {
5592           if (p->may_have_pointers)
5593             make_constraint_from (p, nonlocal_id);
5594           if (p->only_restrict_pointers)
5595             make_constraint_from_restrict (p, "PARM_RESTRICT");
5596         }
5597       if (POINTER_TYPE_P (TREE_TYPE (t))
5598           && TYPE_RESTRICT (TREE_TYPE (t)))
5599         make_constraint_from_restrict (get_vi_for_tree (t), "PARM_RESTRICT");
5600     }
5601
5602   /* Add a constraint for a result decl that is passed by reference.  */
5603   if (DECL_RESULT (cfun->decl)
5604       && DECL_BY_REFERENCE (DECL_RESULT (cfun->decl)))
5605     {
5606       varinfo_t p, result_vi = get_vi_for_tree (DECL_RESULT (cfun->decl));
5607
5608       for (p = result_vi; p; p = p->next)
5609         make_constraint_from (p, nonlocal_id);
5610     }
5611
5612   /* Add a constraint for the incoming static chain parameter.  */
5613   if (cfun->static_chain_decl != NULL_TREE)
5614     {
5615       varinfo_t p, chain_vi = get_vi_for_tree (cfun->static_chain_decl);
5616
5617       for (p = chain_vi; p; p = p->next)
5618         make_constraint_from (p, nonlocal_id);
5619     }
5620 }
5621
5622 /* Structure used to put solution bitmaps in a hashtable so they can
5623    be shared among variables with the same points-to set.  */
5624
5625 typedef struct shared_bitmap_info
5626 {
5627   bitmap pt_vars;
5628   hashval_t hashcode;
5629 } *shared_bitmap_info_t;
5630 typedef const struct shared_bitmap_info *const_shared_bitmap_info_t;
5631
5632 static htab_t shared_bitmap_table;
5633
5634 /* Hash function for a shared_bitmap_info_t */
5635
5636 static hashval_t
5637 shared_bitmap_hash (const void *p)
5638 {
5639   const_shared_bitmap_info_t const bi = (const_shared_bitmap_info_t) p;
5640   return bi->hashcode;
5641 }
5642
5643 /* Equality function for two shared_bitmap_info_t's. */
5644
5645 static int
5646 shared_bitmap_eq (const void *p1, const void *p2)
5647 {
5648   const_shared_bitmap_info_t const sbi1 = (const_shared_bitmap_info_t) p1;
5649   const_shared_bitmap_info_t const sbi2 = (const_shared_bitmap_info_t) p2;
5650   return bitmap_equal_p (sbi1->pt_vars, sbi2->pt_vars);
5651 }
5652
5653 /* Lookup a bitmap in the shared bitmap hashtable, and return an already
5654    existing instance if there is one, NULL otherwise.  */
5655
5656 static bitmap
5657 shared_bitmap_lookup (bitmap pt_vars)
5658 {
5659   void **slot;
5660   struct shared_bitmap_info sbi;
5661
5662   sbi.pt_vars = pt_vars;
5663   sbi.hashcode = bitmap_hash (pt_vars);
5664
5665   slot = htab_find_slot_with_hash (shared_bitmap_table, &sbi,
5666                                    sbi.hashcode, NO_INSERT);
5667   if (!slot)
5668     return NULL;
5669   else
5670     return ((shared_bitmap_info_t) *slot)->pt_vars;
5671 }
5672
5673
5674 /* Add a bitmap to the shared bitmap hashtable.  */
5675
5676 static void
5677 shared_bitmap_add (bitmap pt_vars)
5678 {
5679   void **slot;
5680   shared_bitmap_info_t sbi = XNEW (struct shared_bitmap_info);
5681
5682   sbi->pt_vars = pt_vars;
5683   sbi->hashcode = bitmap_hash (pt_vars);
5684
5685   slot = htab_find_slot_with_hash (shared_bitmap_table, sbi,
5686                                    sbi->hashcode, INSERT);
5687   gcc_assert (!*slot);
5688   *slot = (void *) sbi;
5689 }
5690
5691
5692 /* Set bits in INTO corresponding to the variable uids in solution set FROM.  */
5693
5694 static void
5695 set_uids_in_ptset (bitmap into, bitmap from, struct pt_solution *pt)
5696 {
5697   unsigned int i;
5698   bitmap_iterator bi;
5699
5700   EXECUTE_IF_SET_IN_BITMAP (from, 0, i, bi)
5701     {
5702       varinfo_t vi = get_varinfo (i);
5703
5704       /* The only artificial variables that are allowed in a may-alias
5705          set are heap variables.  */
5706       if (vi->is_artificial_var && !vi->is_heap_var)
5707         continue;
5708
5709       if (TREE_CODE (vi->decl) == VAR_DECL
5710           || TREE_CODE (vi->decl) == PARM_DECL
5711           || TREE_CODE (vi->decl) == RESULT_DECL)
5712         {
5713           /* If we are in IPA mode we will not recompute points-to
5714              sets after inlining so make sure they stay valid.  */
5715           if (in_ipa_mode
5716               && !DECL_PT_UID_SET_P (vi->decl))
5717             SET_DECL_PT_UID (vi->decl, DECL_UID (vi->decl));
5718
5719           /* Add the decl to the points-to set.  Note that the points-to
5720              set contains global variables.  */
5721           bitmap_set_bit (into, DECL_PT_UID (vi->decl));
5722           if (vi->is_global_var)
5723             pt->vars_contains_global = true;
5724         }
5725     }
5726 }
5727
5728
5729 /* Compute the points-to solution *PT for the variable VI.  */
5730
5731 static void
5732 find_what_var_points_to (varinfo_t orig_vi, struct pt_solution *pt)
5733 {
5734   unsigned int i;
5735   bitmap_iterator bi;
5736   bitmap finished_solution;
5737   bitmap result;
5738   varinfo_t vi;
5739
5740   memset (pt, 0, sizeof (struct pt_solution));
5741
5742   /* This variable may have been collapsed, let's get the real
5743      variable.  */
5744   vi = get_varinfo (find (orig_vi->id));
5745
5746   /* Translate artificial variables into SSA_NAME_PTR_INFO
5747      attributes.  */
5748   EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
5749     {
5750       varinfo_t vi = get_varinfo (i);
5751
5752       if (vi->is_artificial_var)
5753         {
5754           if (vi->id == nothing_id)
5755             pt->null = 1;
5756           else if (vi->id == escaped_id)
5757             {
5758               if (in_ipa_mode)
5759                 pt->ipa_escaped = 1;
5760               else
5761                 pt->escaped = 1;
5762             }
5763           else if (vi->id == nonlocal_id)
5764             pt->nonlocal = 1;
5765           else if (vi->is_heap_var)
5766             /* We represent heapvars in the points-to set properly.  */
5767             ;
5768           else if (vi->id == readonly_id)
5769             /* Nobody cares.  */
5770             ;
5771           else if (vi->id == anything_id
5772                    || vi->id == integer_id)
5773             pt->anything = 1;
5774         }
5775       if (vi->is_restrict_var)
5776         pt->vars_contains_restrict = true;
5777     }
5778
5779   /* Instead of doing extra work, simply do not create
5780      elaborate points-to information for pt_anything pointers.  */
5781   if (pt->anything
5782       && (orig_vi->is_artificial_var
5783           || !pt->vars_contains_restrict))
5784     return;
5785
5786   /* Share the final set of variables when possible.  */
5787   finished_solution = BITMAP_GGC_ALLOC ();
5788   stats.points_to_sets_created++;
5789
5790   set_uids_in_ptset (finished_solution, vi->solution, pt);
5791   result = shared_bitmap_lookup (finished_solution);
5792   if (!result)
5793     {
5794       shared_bitmap_add (finished_solution);
5795       pt->vars = finished_solution;
5796     }
5797   else
5798     {
5799       pt->vars = result;
5800       bitmap_clear (finished_solution);
5801     }
5802 }
5803
5804 /* Given a pointer variable P, fill in its points-to set.  */
5805
5806 static void
5807 find_what_p_points_to (tree p)
5808 {
5809   struct ptr_info_def *pi;
5810   tree lookup_p = p;
5811   varinfo_t vi;
5812
5813   /* For parameters, get at the points-to set for the actual parm
5814      decl.  */
5815   if (TREE_CODE (p) == SSA_NAME
5816       && (TREE_CODE (SSA_NAME_VAR (p)) == PARM_DECL
5817           || TREE_CODE (SSA_NAME_VAR (p)) == RESULT_DECL)
5818       && SSA_NAME_IS_DEFAULT_DEF (p))
5819     lookup_p = SSA_NAME_VAR (p);
5820
5821   vi = lookup_vi_for_tree (lookup_p);
5822   if (!vi)
5823     return;
5824
5825   pi = get_ptr_info (p);
5826   find_what_var_points_to (vi, &pi->pt);
5827 }
5828
5829
5830 /* Query statistics for points-to solutions.  */
5831
5832 static struct {
5833   unsigned HOST_WIDE_INT pt_solution_includes_may_alias;
5834   unsigned HOST_WIDE_INT pt_solution_includes_no_alias;
5835   unsigned HOST_WIDE_INT pt_solutions_intersect_may_alias;
5836   unsigned HOST_WIDE_INT pt_solutions_intersect_no_alias;
5837 } pta_stats;
5838
5839 void
5840 dump_pta_stats (FILE *s)
5841 {
5842   fprintf (s, "\nPTA query stats:\n");
5843   fprintf (s, "  pt_solution_includes: "
5844            HOST_WIDE_INT_PRINT_DEC" disambiguations, "
5845            HOST_WIDE_INT_PRINT_DEC" queries\n",
5846            pta_stats.pt_solution_includes_no_alias,
5847            pta_stats.pt_solution_includes_no_alias
5848            + pta_stats.pt_solution_includes_may_alias);
5849   fprintf (s, "  pt_solutions_intersect: "
5850            HOST_WIDE_INT_PRINT_DEC" disambiguations, "
5851            HOST_WIDE_INT_PRINT_DEC" queries\n",
5852            pta_stats.pt_solutions_intersect_no_alias,
5853            pta_stats.pt_solutions_intersect_no_alias
5854            + pta_stats.pt_solutions_intersect_may_alias);
5855 }
5856
5857
5858 /* Reset the points-to solution *PT to a conservative default
5859    (point to anything).  */
5860
5861 void
5862 pt_solution_reset (struct pt_solution *pt)
5863 {
5864   memset (pt, 0, sizeof (struct pt_solution));
5865   pt->anything = true;
5866 }
5867
5868 /* Set the points-to solution *PT to point only to the variables
5869    in VARS.  VARS_CONTAINS_GLOBAL specifies whether that contains
5870    global variables and VARS_CONTAINS_RESTRICT specifies whether
5871    it contains restrict tag variables.  */
5872
5873 void
5874 pt_solution_set (struct pt_solution *pt, bitmap vars,
5875                  bool vars_contains_global, bool vars_contains_restrict)
5876 {
5877   memset (pt, 0, sizeof (struct pt_solution));
5878   pt->vars = vars;
5879   pt->vars_contains_global = vars_contains_global;
5880   pt->vars_contains_restrict = vars_contains_restrict;
5881 }
5882
5883 /* Set the points-to solution *PT to point only to the variable VAR.  */
5884
5885 void
5886 pt_solution_set_var (struct pt_solution *pt, tree var)
5887 {
5888   memset (pt, 0, sizeof (struct pt_solution));
5889   pt->vars = BITMAP_GGC_ALLOC ();
5890   bitmap_set_bit (pt->vars, DECL_PT_UID (var));
5891   pt->vars_contains_global = is_global_var (var);
5892 }
5893
5894 /* Computes the union of the points-to solutions *DEST and *SRC and
5895    stores the result in *DEST.  This changes the points-to bitmap
5896    of *DEST and thus may not be used if that might be shared.
5897    The points-to bitmap of *SRC and *DEST will not be shared after
5898    this function if they were not before.  */
5899
5900 static void
5901 pt_solution_ior_into (struct pt_solution *dest, struct pt_solution *src)
5902 {
5903   dest->anything |= src->anything;
5904   if (dest->anything)
5905     {
5906       pt_solution_reset (dest);
5907       return;
5908     }
5909
5910   dest->nonlocal |= src->nonlocal;
5911   dest->escaped |= src->escaped;
5912   dest->ipa_escaped |= src->ipa_escaped;
5913   dest->null |= src->null;
5914   dest->vars_contains_global |= src->vars_contains_global;
5915   dest->vars_contains_restrict |= src->vars_contains_restrict;
5916   if (!src->vars)
5917     return;
5918
5919   if (!dest->vars)
5920     dest->vars = BITMAP_GGC_ALLOC ();
5921   bitmap_ior_into (dest->vars, src->vars);
5922 }
5923
5924 /* Return true if the points-to solution *PT is empty.  */
5925
5926 bool
5927 pt_solution_empty_p (struct pt_solution *pt)
5928 {
5929   if (pt->anything
5930       || pt->nonlocal)
5931     return false;
5932
5933   if (pt->vars
5934       && !bitmap_empty_p (pt->vars))
5935     return false;
5936
5937   /* If the solution includes ESCAPED, check if that is empty.  */
5938   if (pt->escaped
5939       && !pt_solution_empty_p (&cfun->gimple_df->escaped))
5940     return false;
5941
5942   /* If the solution includes ESCAPED, check if that is empty.  */
5943   if (pt->ipa_escaped
5944       && !pt_solution_empty_p (&ipa_escaped_pt))
5945     return false;
5946
5947   return true;
5948 }
5949
5950 /* Return true if the points-to solution *PT includes global memory.  */
5951
5952 bool
5953 pt_solution_includes_global (struct pt_solution *pt)
5954 {
5955   if (pt->anything
5956       || pt->nonlocal
5957       || pt->vars_contains_global)
5958     return true;
5959
5960   if (pt->escaped)
5961     return pt_solution_includes_global (&cfun->gimple_df->escaped);
5962
5963   if (pt->ipa_escaped)
5964     return pt_solution_includes_global (&ipa_escaped_pt);
5965
5966   /* ???  This predicate is not correct for the IPA-PTA solution
5967      as we do not properly distinguish between unit escape points
5968      and global variables.  */
5969   if (cfun->gimple_df->ipa_pta)
5970     return true;
5971
5972   return false;
5973 }
5974
5975 /* Return true if the points-to solution *PT includes the variable
5976    declaration DECL.  */
5977
5978 static bool
5979 pt_solution_includes_1 (struct pt_solution *pt, const_tree decl)
5980 {
5981   if (pt->anything)
5982     return true;
5983
5984   if (pt->nonlocal
5985       && is_global_var (decl))
5986     return true;
5987
5988   if (pt->vars
5989       && bitmap_bit_p (pt->vars, DECL_PT_UID (decl)))
5990     return true;
5991
5992   /* If the solution includes ESCAPED, check it.  */
5993   if (pt->escaped
5994       && pt_solution_includes_1 (&cfun->gimple_df->escaped, decl))
5995     return true;
5996
5997   /* If the solution includes ESCAPED, check it.  */
5998   if (pt->ipa_escaped
5999       && pt_solution_includes_1 (&ipa_escaped_pt, decl))
6000     return true;
6001
6002   return false;
6003 }
6004
6005 bool
6006 pt_solution_includes (struct pt_solution *pt, const_tree decl)
6007 {
6008   bool res = pt_solution_includes_1 (pt, decl);
6009   if (res)
6010     ++pta_stats.pt_solution_includes_may_alias;
6011   else
6012     ++pta_stats.pt_solution_includes_no_alias;
6013   return res;
6014 }
6015
6016 /* Return true if both points-to solutions PT1 and PT2 have a non-empty
6017    intersection.  */
6018
6019 static bool
6020 pt_solutions_intersect_1 (struct pt_solution *pt1, struct pt_solution *pt2)
6021 {
6022   if (pt1->anything || pt2->anything)
6023     return true;
6024
6025   /* If either points to unknown global memory and the other points to
6026      any global memory they alias.  */
6027   if ((pt1->nonlocal
6028        && (pt2->nonlocal
6029            || pt2->vars_contains_global))
6030       || (pt2->nonlocal
6031           && pt1->vars_contains_global))
6032     return true;
6033
6034   /* Check the escaped solution if required.  */
6035   if ((pt1->escaped || pt2->escaped)
6036       && !pt_solution_empty_p (&cfun->gimple_df->escaped))
6037     {
6038       /* If both point to escaped memory and that solution
6039          is not empty they alias.  */
6040       if (pt1->escaped && pt2->escaped)
6041         return true;
6042
6043       /* If either points to escaped memory see if the escaped solution
6044          intersects with the other.  */
6045       if ((pt1->escaped
6046            && pt_solutions_intersect_1 (&cfun->gimple_df->escaped, pt2))
6047           || (pt2->escaped
6048               && pt_solutions_intersect_1 (&cfun->gimple_df->escaped, pt1)))
6049         return true;
6050     }
6051
6052   /* Check the escaped solution if required.
6053      ???  Do we need to check the local against the IPA escaped sets?  */
6054   if ((pt1->ipa_escaped || pt2->ipa_escaped)
6055       && !pt_solution_empty_p (&ipa_escaped_pt))
6056     {
6057       /* If both point to escaped memory and that solution
6058          is not empty they alias.  */
6059       if (pt1->ipa_escaped && pt2->ipa_escaped)
6060         return true;
6061
6062       /* If either points to escaped memory see if the escaped solution
6063          intersects with the other.  */
6064       if ((pt1->ipa_escaped
6065            && pt_solutions_intersect_1 (&ipa_escaped_pt, pt2))
6066           || (pt2->ipa_escaped
6067               && pt_solutions_intersect_1 (&ipa_escaped_pt, pt1)))
6068         return true;
6069     }
6070
6071   /* Now both pointers alias if their points-to solution intersects.  */
6072   return (pt1->vars
6073           && pt2->vars
6074           && bitmap_intersect_p (pt1->vars, pt2->vars));
6075 }
6076
6077 bool
6078 pt_solutions_intersect (struct pt_solution *pt1, struct pt_solution *pt2)
6079 {
6080   bool res = pt_solutions_intersect_1 (pt1, pt2);
6081   if (res)
6082     ++pta_stats.pt_solutions_intersect_may_alias;
6083   else
6084     ++pta_stats.pt_solutions_intersect_no_alias;
6085   return res;
6086 }
6087
6088 /* Return true if both points-to solutions PT1 and PT2 for two restrict
6089    qualified pointers are possibly based on the same pointer.  */
6090
6091 bool
6092 pt_solutions_same_restrict_base (struct pt_solution *pt1,
6093                                  struct pt_solution *pt2)
6094 {
6095   /* If we deal with points-to solutions of two restrict qualified
6096      pointers solely rely on the pointed-to variable bitmap intersection.
6097      For two pointers that are based on each other the bitmaps will
6098      intersect.  */
6099   if (pt1->vars_contains_restrict
6100       && pt2->vars_contains_restrict)
6101     {
6102       gcc_assert (pt1->vars && pt2->vars);
6103       return bitmap_intersect_p (pt1->vars, pt2->vars);
6104     }
6105
6106   return true;
6107 }
6108
6109
6110 /* Dump points-to information to OUTFILE.  */
6111
6112 static void
6113 dump_sa_points_to_info (FILE *outfile)
6114 {
6115   unsigned int i;
6116
6117   fprintf (outfile, "\nPoints-to sets\n\n");
6118
6119   if (dump_flags & TDF_STATS)
6120     {
6121       fprintf (outfile, "Stats:\n");
6122       fprintf (outfile, "Total vars:               %d\n", stats.total_vars);
6123       fprintf (outfile, "Non-pointer vars:          %d\n",
6124                stats.nonpointer_vars);
6125       fprintf (outfile, "Statically unified vars:  %d\n",
6126                stats.unified_vars_static);
6127       fprintf (outfile, "Dynamically unified vars: %d\n",
6128                stats.unified_vars_dynamic);
6129       fprintf (outfile, "Iterations:               %d\n", stats.iterations);
6130       fprintf (outfile, "Number of edges:          %d\n", stats.num_edges);
6131       fprintf (outfile, "Number of implicit edges: %d\n",
6132                stats.num_implicit_edges);
6133     }
6134
6135   for (i = 0; i < VEC_length (varinfo_t, varmap); i++)
6136     {
6137       varinfo_t vi = get_varinfo (i);
6138       if (!vi->may_have_pointers)
6139         continue;
6140       dump_solution_for_var (outfile, i);
6141     }
6142 }
6143
6144
6145 /* Debug points-to information to stderr.  */
6146
6147 DEBUG_FUNCTION void
6148 debug_sa_points_to_info (void)
6149 {
6150   dump_sa_points_to_info (stderr);
6151 }
6152
6153
6154 /* Initialize the always-existing constraint variables for NULL
6155    ANYTHING, READONLY, and INTEGER */
6156
6157 static void
6158 init_base_vars (void)
6159 {
6160   struct constraint_expr lhs, rhs;
6161   varinfo_t var_anything;
6162   varinfo_t var_nothing;
6163   varinfo_t var_readonly;
6164   varinfo_t var_escaped;
6165   varinfo_t var_nonlocal;
6166   varinfo_t var_storedanything;
6167   varinfo_t var_integer;
6168
6169   /* Create the NULL variable, used to represent that a variable points
6170      to NULL.  */
6171   var_nothing = new_var_info (NULL_TREE, "NULL");
6172   gcc_assert (var_nothing->id == nothing_id);
6173   var_nothing->is_artificial_var = 1;
6174   var_nothing->offset = 0;
6175   var_nothing->size = ~0;
6176   var_nothing->fullsize = ~0;
6177   var_nothing->is_special_var = 1;
6178   var_nothing->may_have_pointers = 0;
6179   var_nothing->is_global_var = 0;
6180
6181   /* Create the ANYTHING variable, used to represent that a variable
6182      points to some unknown piece of memory.  */
6183   var_anything = new_var_info (NULL_TREE, "ANYTHING");
6184   gcc_assert (var_anything->id == anything_id);
6185   var_anything->is_artificial_var = 1;
6186   var_anything->size = ~0;
6187   var_anything->offset = 0;
6188   var_anything->next = NULL;
6189   var_anything->fullsize = ~0;
6190   var_anything->is_special_var = 1;
6191
6192   /* Anything points to anything.  This makes deref constraints just
6193      work in the presence of linked list and other p = *p type loops,
6194      by saying that *ANYTHING = ANYTHING. */
6195   lhs.type = SCALAR;
6196   lhs.var = anything_id;
6197   lhs.offset = 0;
6198   rhs.type = ADDRESSOF;
6199   rhs.var = anything_id;
6200   rhs.offset = 0;
6201
6202   /* This specifically does not use process_constraint because
6203      process_constraint ignores all anything = anything constraints, since all
6204      but this one are redundant.  */
6205   VEC_safe_push (constraint_t, heap, constraints, new_constraint (lhs, rhs));
6206
6207   /* Create the READONLY variable, used to represent that a variable
6208      points to readonly memory.  */
6209   var_readonly = new_var_info (NULL_TREE, "READONLY");
6210   gcc_assert (var_readonly->id == readonly_id);
6211   var_readonly->is_artificial_var = 1;
6212   var_readonly->offset = 0;
6213   var_readonly->size = ~0;
6214   var_readonly->fullsize = ~0;
6215   var_readonly->next = NULL;
6216   var_readonly->is_special_var = 1;
6217
6218   /* readonly memory points to anything, in order to make deref
6219      easier.  In reality, it points to anything the particular
6220      readonly variable can point to, but we don't track this
6221      separately. */
6222   lhs.type = SCALAR;
6223   lhs.var = readonly_id;
6224   lhs.offset = 0;
6225   rhs.type = ADDRESSOF;
6226   rhs.var = readonly_id;  /* FIXME */
6227   rhs.offset = 0;
6228   process_constraint (new_constraint (lhs, rhs));
6229
6230   /* Create the ESCAPED variable, used to represent the set of escaped
6231      memory.  */
6232   var_escaped = new_var_info (NULL_TREE, "ESCAPED");
6233   gcc_assert (var_escaped->id == escaped_id);
6234   var_escaped->is_artificial_var = 1;
6235   var_escaped->offset = 0;
6236   var_escaped->size = ~0;
6237   var_escaped->fullsize = ~0;
6238   var_escaped->is_special_var = 0;
6239
6240   /* Create the NONLOCAL variable, used to represent the set of nonlocal
6241      memory.  */
6242   var_nonlocal = new_var_info (NULL_TREE, "NONLOCAL");
6243   gcc_assert (var_nonlocal->id == nonlocal_id);
6244   var_nonlocal->is_artificial_var = 1;
6245   var_nonlocal->offset = 0;
6246   var_nonlocal->size = ~0;
6247   var_nonlocal->fullsize = ~0;
6248   var_nonlocal->is_special_var = 1;
6249
6250   /* ESCAPED = *ESCAPED, because escaped is may-deref'd at calls, etc.  */
6251   lhs.type = SCALAR;
6252   lhs.var = escaped_id;
6253   lhs.offset = 0;
6254   rhs.type = DEREF;
6255   rhs.var = escaped_id;
6256   rhs.offset = 0;
6257   process_constraint (new_constraint (lhs, rhs));
6258
6259   /* ESCAPED = ESCAPED + UNKNOWN_OFFSET, because if a sub-field escapes the
6260      whole variable escapes.  */
6261   lhs.type = SCALAR;
6262   lhs.var = escaped_id;
6263   lhs.offset = 0;
6264   rhs.type = SCALAR;
6265   rhs.var = escaped_id;
6266   rhs.offset = UNKNOWN_OFFSET;
6267   process_constraint (new_constraint (lhs, rhs));
6268
6269   /* *ESCAPED = NONLOCAL.  This is true because we have to assume
6270      everything pointed to by escaped points to what global memory can
6271      point to.  */
6272   lhs.type = DEREF;
6273   lhs.var = escaped_id;
6274   lhs.offset = 0;
6275   rhs.type = SCALAR;
6276   rhs.var = nonlocal_id;
6277   rhs.offset = 0;
6278   process_constraint (new_constraint (lhs, rhs));
6279
6280   /* NONLOCAL = &NONLOCAL, NONLOCAL = &ESCAPED.  This is true because
6281      global memory may point to global memory and escaped memory.  */
6282   lhs.type = SCALAR;
6283   lhs.var = nonlocal_id;
6284   lhs.offset = 0;
6285   rhs.type = ADDRESSOF;
6286   rhs.var = nonlocal_id;
6287   rhs.offset = 0;
6288   process_constraint (new_constraint (lhs, rhs));
6289   rhs.type = ADDRESSOF;
6290   rhs.var = escaped_id;
6291   rhs.offset = 0;
6292   process_constraint (new_constraint (lhs, rhs));
6293
6294   /* Create the STOREDANYTHING variable, used to represent the set of
6295      variables stored to *ANYTHING.  */
6296   var_storedanything = new_var_info (NULL_TREE, "STOREDANYTHING");
6297   gcc_assert (var_storedanything->id == storedanything_id);
6298   var_storedanything->is_artificial_var = 1;
6299   var_storedanything->offset = 0;
6300   var_storedanything->size = ~0;
6301   var_storedanything->fullsize = ~0;
6302   var_storedanything->is_special_var = 0;
6303
6304   /* Create the INTEGER variable, used to represent that a variable points
6305      to what an INTEGER "points to".  */
6306   var_integer = new_var_info (NULL_TREE, "INTEGER");
6307   gcc_assert (var_integer->id == integer_id);
6308   var_integer->is_artificial_var = 1;
6309   var_integer->size = ~0;
6310   var_integer->fullsize = ~0;
6311   var_integer->offset = 0;
6312   var_integer->next = NULL;
6313   var_integer->is_special_var = 1;
6314
6315   /* INTEGER = ANYTHING, because we don't know where a dereference of
6316      a random integer will point to.  */
6317   lhs.type = SCALAR;
6318   lhs.var = integer_id;
6319   lhs.offset = 0;
6320   rhs.type = ADDRESSOF;
6321   rhs.var = anything_id;
6322   rhs.offset = 0;
6323   process_constraint (new_constraint (lhs, rhs));
6324 }
6325
6326 /* Initialize things necessary to perform PTA */
6327
6328 static void
6329 init_alias_vars (void)
6330 {
6331   use_field_sensitive = (MAX_FIELDS_FOR_FIELD_SENSITIVE > 1);
6332
6333   bitmap_obstack_initialize (&pta_obstack);
6334   bitmap_obstack_initialize (&oldpta_obstack);
6335   bitmap_obstack_initialize (&predbitmap_obstack);
6336
6337   constraint_pool = create_alloc_pool ("Constraint pool",
6338                                        sizeof (struct constraint), 30);
6339   variable_info_pool = create_alloc_pool ("Variable info pool",
6340                                           sizeof (struct variable_info), 30);
6341   constraints = VEC_alloc (constraint_t, heap, 8);
6342   varmap = VEC_alloc (varinfo_t, heap, 8);
6343   vi_for_tree = pointer_map_create ();
6344   call_stmt_vars = pointer_map_create ();
6345
6346   memset (&stats, 0, sizeof (stats));
6347   shared_bitmap_table = htab_create (511, shared_bitmap_hash,
6348                                      shared_bitmap_eq, free);
6349   init_base_vars ();
6350
6351   gcc_obstack_init (&fake_var_decl_obstack);
6352 }
6353
6354 /* Remove the REF and ADDRESS edges from GRAPH, as well as all the
6355    predecessor edges.  */
6356
6357 static void
6358 remove_preds_and_fake_succs (constraint_graph_t graph)
6359 {
6360   unsigned int i;
6361
6362   /* Clear the implicit ref and address nodes from the successor
6363      lists.  */
6364   for (i = 0; i < FIRST_REF_NODE; i++)
6365     {
6366       if (graph->succs[i])
6367         bitmap_clear_range (graph->succs[i], FIRST_REF_NODE,
6368                             FIRST_REF_NODE * 2);
6369     }
6370
6371   /* Free the successor list for the non-ref nodes.  */
6372   for (i = FIRST_REF_NODE; i < graph->size; i++)
6373     {
6374       if (graph->succs[i])
6375         BITMAP_FREE (graph->succs[i]);
6376     }
6377
6378   /* Now reallocate the size of the successor list as, and blow away
6379      the predecessor bitmaps.  */
6380   graph->size = VEC_length (varinfo_t, varmap);
6381   graph->succs = XRESIZEVEC (bitmap, graph->succs, graph->size);
6382
6383   free (graph->implicit_preds);
6384   graph->implicit_preds = NULL;
6385   free (graph->preds);
6386   graph->preds = NULL;
6387   bitmap_obstack_release (&predbitmap_obstack);
6388 }
6389
6390 /* Solve the constraint set.  */
6391
6392 static void
6393 solve_constraints (void)
6394 {
6395   struct scc_info *si;
6396
6397   if (dump_file)
6398     fprintf (dump_file,
6399              "\nCollapsing static cycles and doing variable "
6400              "substitution\n");
6401
6402   init_graph (VEC_length (varinfo_t, varmap) * 2);
6403
6404   if (dump_file)
6405     fprintf (dump_file, "Building predecessor graph\n");
6406   build_pred_graph ();
6407
6408   if (dump_file)
6409     fprintf (dump_file, "Detecting pointer and location "
6410              "equivalences\n");
6411   si = perform_var_substitution (graph);
6412
6413   if (dump_file)
6414     fprintf (dump_file, "Rewriting constraints and unifying "
6415              "variables\n");
6416   rewrite_constraints (graph, si);
6417
6418   build_succ_graph ();
6419
6420   free_var_substitution_info (si);
6421
6422   /* Attach complex constraints to graph nodes.  */
6423   move_complex_constraints (graph);
6424
6425   if (dump_file)
6426     fprintf (dump_file, "Uniting pointer but not location equivalent "
6427              "variables\n");
6428   unite_pointer_equivalences (graph);
6429
6430   if (dump_file)
6431     fprintf (dump_file, "Finding indirect cycles\n");
6432   find_indirect_cycles (graph);
6433
6434   /* Implicit nodes and predecessors are no longer necessary at this
6435      point. */
6436   remove_preds_and_fake_succs (graph);
6437
6438   if (dump_file && (dump_flags & TDF_GRAPH))
6439     {
6440       fprintf (dump_file, "\n\n// The constraint graph before solve-graph "
6441                "in dot format:\n");
6442       dump_constraint_graph (dump_file);
6443       fprintf (dump_file, "\n\n");
6444     }
6445
6446   if (dump_file)
6447     fprintf (dump_file, "Solving graph\n");
6448
6449   solve_graph (graph);
6450
6451   if (dump_file && (dump_flags & TDF_GRAPH))
6452     {
6453       fprintf (dump_file, "\n\n// The constraint graph after solve-graph "
6454                "in dot format:\n");
6455       dump_constraint_graph (dump_file);
6456       fprintf (dump_file, "\n\n");
6457     }
6458
6459   if (dump_file)
6460     dump_sa_points_to_info (dump_file);
6461 }
6462
6463 /* Create points-to sets for the current function.  See the comments
6464    at the start of the file for an algorithmic overview.  */
6465
6466 static void
6467 compute_points_to_sets (void)
6468 {
6469   basic_block bb;
6470   unsigned i;
6471   varinfo_t vi;
6472
6473   timevar_push (TV_TREE_PTA);
6474
6475   init_alias_vars ();
6476
6477   intra_create_variable_infos ();
6478
6479   /* Now walk all statements and build the constraint set.  */
6480   FOR_EACH_BB (bb)
6481     {
6482       gimple_stmt_iterator gsi;
6483
6484       for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6485         {
6486           gimple phi = gsi_stmt (gsi);
6487
6488           if (is_gimple_reg (gimple_phi_result (phi)))
6489             find_func_aliases (phi);
6490         }
6491
6492       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6493         {
6494           gimple stmt = gsi_stmt (gsi);
6495
6496           find_func_aliases (stmt);
6497         }
6498     }
6499
6500   if (dump_file)
6501     {
6502       fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
6503       dump_constraints (dump_file, 0);
6504     }
6505
6506   /* From the constraints compute the points-to sets.  */
6507   solve_constraints ();
6508
6509   /* Compute the points-to set for ESCAPED used for call-clobber analysis.  */
6510   find_what_var_points_to (get_varinfo (escaped_id),
6511                            &cfun->gimple_df->escaped);
6512
6513   /* Make sure the ESCAPED solution (which is used as placeholder in
6514      other solutions) does not reference itself.  This simplifies
6515      points-to solution queries.  */
6516   cfun->gimple_df->escaped.escaped = 0;
6517
6518   /* Mark escaped HEAP variables as global.  */
6519   FOR_EACH_VEC_ELT (varinfo_t, varmap, i, vi)
6520     if (vi->is_heap_var
6521         && !vi->is_restrict_var
6522         && !vi->is_global_var)
6523       DECL_EXTERNAL (vi->decl) = vi->is_global_var
6524         = pt_solution_includes (&cfun->gimple_df->escaped, vi->decl);
6525
6526   /* Compute the points-to sets for pointer SSA_NAMEs.  */
6527   for (i = 0; i < num_ssa_names; ++i)
6528     {
6529       tree ptr = ssa_name (i);
6530       if (ptr
6531           && POINTER_TYPE_P (TREE_TYPE (ptr)))
6532         find_what_p_points_to (ptr);
6533     }
6534
6535   /* Compute the call-used/clobbered sets.  */
6536   FOR_EACH_BB (bb)
6537     {
6538       gimple_stmt_iterator gsi;
6539
6540       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6541         {
6542           gimple stmt = gsi_stmt (gsi);
6543           struct pt_solution *pt;
6544           if (!is_gimple_call (stmt))
6545             continue;
6546
6547           pt = gimple_call_use_set (stmt);
6548           if (gimple_call_flags (stmt) & ECF_CONST)
6549             memset (pt, 0, sizeof (struct pt_solution));
6550           else if ((vi = lookup_call_use_vi (stmt)) != NULL)
6551             {
6552               find_what_var_points_to (vi, pt);
6553               /* Escaped (and thus nonlocal) variables are always
6554                  implicitly used by calls.  */
6555               /* ???  ESCAPED can be empty even though NONLOCAL
6556                  always escaped.  */
6557               pt->nonlocal = 1;
6558               pt->escaped = 1;
6559             }
6560           else
6561             {
6562               /* If there is nothing special about this call then
6563                  we have made everything that is used also escape.  */
6564               *pt = cfun->gimple_df->escaped;
6565               pt->nonlocal = 1;
6566             }
6567
6568           pt = gimple_call_clobber_set (stmt);
6569           if (gimple_call_flags (stmt) & (ECF_CONST|ECF_PURE|ECF_NOVOPS))
6570             memset (pt, 0, sizeof (struct pt_solution));
6571           else if ((vi = lookup_call_clobber_vi (stmt)) != NULL)
6572             {
6573               find_what_var_points_to (vi, pt);
6574               /* Escaped (and thus nonlocal) variables are always
6575                  implicitly clobbered by calls.  */
6576               /* ???  ESCAPED can be empty even though NONLOCAL
6577                  always escaped.  */
6578               pt->nonlocal = 1;
6579               pt->escaped = 1;
6580             }
6581           else
6582             {
6583               /* If there is nothing special about this call then
6584                  we have made everything that is used also escape.  */
6585               *pt = cfun->gimple_df->escaped;
6586               pt->nonlocal = 1;
6587             }
6588         }
6589     }
6590
6591   timevar_pop (TV_TREE_PTA);
6592 }
6593
6594
6595 /* Delete created points-to sets.  */
6596
6597 static void
6598 delete_points_to_sets (void)
6599 {
6600   unsigned int i;
6601
6602   htab_delete (shared_bitmap_table);
6603   if (dump_file && (dump_flags & TDF_STATS))
6604     fprintf (dump_file, "Points to sets created:%d\n",
6605              stats.points_to_sets_created);
6606
6607   pointer_map_destroy (vi_for_tree);
6608   pointer_map_destroy (call_stmt_vars);
6609   bitmap_obstack_release (&pta_obstack);
6610   VEC_free (constraint_t, heap, constraints);
6611
6612   for (i = 0; i < graph->size; i++)
6613     VEC_free (constraint_t, heap, graph->complex[i]);
6614   free (graph->complex);
6615
6616   free (graph->rep);
6617   free (graph->succs);
6618   free (graph->pe);
6619   free (graph->pe_rep);
6620   free (graph->indirect_cycles);
6621   free (graph);
6622
6623   VEC_free (varinfo_t, heap, varmap);
6624   free_alloc_pool (variable_info_pool);
6625   free_alloc_pool (constraint_pool);
6626
6627   obstack_free (&fake_var_decl_obstack, NULL);
6628 }
6629
6630
6631 /* Compute points-to information for every SSA_NAME pointer in the
6632    current function and compute the transitive closure of escaped
6633    variables to re-initialize the call-clobber states of local variables.  */
6634
6635 unsigned int
6636 compute_may_aliases (void)
6637 {
6638   if (cfun->gimple_df->ipa_pta)
6639     {
6640       if (dump_file)
6641         {
6642           fprintf (dump_file, "\nNot re-computing points-to information "
6643                    "because IPA points-to information is available.\n\n");
6644
6645           /* But still dump what we have remaining it.  */
6646           dump_alias_info (dump_file);
6647
6648           if (dump_flags & TDF_DETAILS)
6649             dump_referenced_vars (dump_file);
6650         }
6651
6652       return 0;
6653     }
6654
6655   /* For each pointer P_i, determine the sets of variables that P_i may
6656      point-to.  Compute the reachability set of escaped and call-used
6657      variables.  */
6658   compute_points_to_sets ();
6659
6660   /* Debugging dumps.  */
6661   if (dump_file)
6662     {
6663       dump_alias_info (dump_file);
6664
6665       if (dump_flags & TDF_DETAILS)
6666         dump_referenced_vars (dump_file);
6667     }
6668
6669   /* Deallocate memory used by aliasing data structures and the internal
6670      points-to solution.  */
6671   delete_points_to_sets ();
6672
6673   gcc_assert (!need_ssa_update_p (cfun));
6674
6675   return 0;
6676 }
6677
6678 static bool
6679 gate_tree_pta (void)
6680 {
6681   return flag_tree_pta;
6682 }
6683
6684 /* A dummy pass to cause points-to information to be computed via
6685    TODO_rebuild_alias.  */
6686
6687 struct gimple_opt_pass pass_build_alias =
6688 {
6689  {
6690   GIMPLE_PASS,
6691   "alias",                  /* name */
6692   gate_tree_pta,            /* gate */
6693   NULL,                     /* execute */
6694   NULL,                     /* sub */
6695   NULL,                     /* next */
6696   0,                        /* static_pass_number */
6697   TV_NONE,                  /* tv_id */
6698   PROP_cfg | PROP_ssa,      /* properties_required */
6699   0,                        /* properties_provided */
6700   0,                        /* properties_destroyed */
6701   0,                        /* todo_flags_start */
6702   TODO_rebuild_alias        /* todo_flags_finish */
6703  }
6704 };
6705
6706 /* A dummy pass to cause points-to information to be computed via
6707    TODO_rebuild_alias.  */
6708
6709 struct gimple_opt_pass pass_build_ealias =
6710 {
6711  {
6712   GIMPLE_PASS,
6713   "ealias",                 /* name */
6714   gate_tree_pta,            /* gate */
6715   NULL,                     /* execute */
6716   NULL,                     /* sub */
6717   NULL,                     /* next */
6718   0,                        /* static_pass_number */
6719   TV_NONE,                  /* tv_id */
6720   PROP_cfg | PROP_ssa,      /* properties_required */
6721   0,                        /* properties_provided */
6722   0,                        /* properties_destroyed */
6723   0,                        /* todo_flags_start */
6724   TODO_rebuild_alias        /* todo_flags_finish */
6725  }
6726 };
6727
6728
6729 /* Return true if we should execute IPA PTA.  */
6730 static bool
6731 gate_ipa_pta (void)
6732 {
6733   return (optimize
6734           && flag_ipa_pta
6735           /* Don't bother doing anything if the program has errors.  */
6736           && !seen_error ());
6737 }
6738
6739 /* IPA PTA solutions for ESCAPED.  */
6740 struct pt_solution ipa_escaped_pt
6741   = { true, false, false, false, false, false, false, NULL };
6742
6743 /* Associate node with varinfo DATA. Worker for
6744    cgraph_for_node_and_aliases.  */
6745 static bool
6746 associate_varinfo_to_alias (struct cgraph_node *node, void *data)
6747 {
6748   if (node->alias || node->thunk.thunk_p)
6749     insert_vi_for_tree (node->decl, (varinfo_t)data);
6750   return false;
6751 }
6752
6753 /* Execute the driver for IPA PTA.  */
6754 static unsigned int
6755 ipa_pta_execute (void)
6756 {
6757   struct cgraph_node *node;
6758   struct varpool_node *var;
6759   int from;
6760
6761   in_ipa_mode = 1;
6762
6763   init_alias_vars ();
6764
6765   if (dump_file && (dump_flags & TDF_DETAILS))
6766     {
6767       dump_cgraph (dump_file);
6768       fprintf (dump_file, "\n");
6769     }
6770
6771   /* Build the constraints.  */
6772   for (node = cgraph_nodes; node; node = node->next)
6773     {
6774       varinfo_t vi;
6775       /* Nodes without a body are not interesting.  Especially do not
6776          visit clones at this point for now - we get duplicate decls
6777          there for inline clones at least.  */
6778       if (!cgraph_function_with_gimple_body_p (node))
6779         continue;
6780
6781       gcc_assert (!node->clone_of);
6782
6783       vi = create_function_info_for (node->decl,
6784                                      alias_get_name (node->decl));
6785       cgraph_for_node_and_aliases (node, associate_varinfo_to_alias, vi, true);
6786     }
6787
6788   /* Create constraints for global variables and their initializers.  */
6789   for (var = varpool_nodes; var; var = var->next)
6790     {
6791       if (var->alias)
6792         continue;
6793
6794       get_vi_for_tree (var->decl);
6795     }
6796
6797   if (dump_file)
6798     {
6799       fprintf (dump_file,
6800                "Generating constraints for global initializers\n\n");
6801       dump_constraints (dump_file, 0);
6802       fprintf (dump_file, "\n");
6803     }
6804   from = VEC_length (constraint_t, constraints);
6805
6806   for (node = cgraph_nodes; node; node = node->next)
6807     {
6808       struct function *func;
6809       basic_block bb;
6810       tree old_func_decl;
6811
6812       /* Nodes without a body are not interesting.  */
6813       if (!cgraph_function_with_gimple_body_p (node))
6814         continue;
6815
6816       if (dump_file)
6817         {
6818           fprintf (dump_file,
6819                    "Generating constraints for %s", cgraph_node_name (node));
6820           if (DECL_ASSEMBLER_NAME_SET_P (node->decl))
6821             fprintf (dump_file, " (%s)",
6822                      IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (node->decl)));
6823           fprintf (dump_file, "\n");
6824         }
6825
6826       func = DECL_STRUCT_FUNCTION (node->decl);
6827       old_func_decl = current_function_decl;
6828       push_cfun (func);
6829       current_function_decl = node->decl;
6830
6831       /* For externally visible or attribute used annotated functions use
6832          local constraints for their arguments.
6833          For local functions we see all callers and thus do not need initial
6834          constraints for parameters.  */
6835       if (node->reachable_from_other_partition
6836           || node->local.externally_visible
6837           || node->needed)
6838         {
6839           intra_create_variable_infos ();
6840
6841           /* We also need to make function return values escape.  Nothing
6842              escapes by returning from main though.  */
6843           if (!MAIN_NAME_P (DECL_NAME (node->decl)))
6844             {
6845               varinfo_t fi, rvi;
6846               fi = lookup_vi_for_tree (node->decl);
6847               rvi = first_vi_for_offset (fi, fi_result);
6848               if (rvi && rvi->offset == fi_result)
6849                 {
6850                   struct constraint_expr includes;
6851                   struct constraint_expr var;
6852                   includes.var = escaped_id;
6853                   includes.offset = 0;
6854                   includes.type = SCALAR;
6855                   var.var = rvi->id;
6856                   var.offset = 0;
6857                   var.type = SCALAR;
6858                   process_constraint (new_constraint (includes, var));
6859                 }
6860             }
6861         }
6862
6863       /* Build constriants for the function body.  */
6864       FOR_EACH_BB_FN (bb, func)
6865         {
6866           gimple_stmt_iterator gsi;
6867
6868           for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
6869                gsi_next (&gsi))
6870             {
6871               gimple phi = gsi_stmt (gsi);
6872
6873               if (is_gimple_reg (gimple_phi_result (phi)))
6874                 find_func_aliases (phi);
6875             }
6876
6877           for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6878             {
6879               gimple stmt = gsi_stmt (gsi);
6880
6881               find_func_aliases (stmt);
6882               find_func_clobbers (stmt);
6883             }
6884         }
6885
6886       current_function_decl = old_func_decl;
6887       pop_cfun ();
6888
6889       if (dump_file)
6890         {
6891           fprintf (dump_file, "\n");
6892           dump_constraints (dump_file, from);
6893           fprintf (dump_file, "\n");
6894         }
6895       from = VEC_length (constraint_t, constraints);
6896     }
6897
6898   /* From the constraints compute the points-to sets.  */
6899   solve_constraints ();
6900
6901   /* Compute the global points-to sets for ESCAPED.
6902      ???  Note that the computed escape set is not correct
6903      for the whole unit as we fail to consider graph edges to
6904      externally visible functions.  */
6905   find_what_var_points_to (get_varinfo (escaped_id), &ipa_escaped_pt);
6906
6907   /* Make sure the ESCAPED solution (which is used as placeholder in
6908      other solutions) does not reference itself.  This simplifies
6909      points-to solution queries.  */
6910   ipa_escaped_pt.ipa_escaped = 0;
6911
6912   /* Assign the points-to sets to the SSA names in the unit.  */
6913   for (node = cgraph_nodes; node; node = node->next)
6914     {
6915       tree ptr;
6916       struct function *fn;
6917       unsigned i;
6918       varinfo_t fi;
6919       basic_block bb;
6920       struct pt_solution uses, clobbers;
6921       struct cgraph_edge *e;
6922
6923       /* Nodes without a body are not interesting.  */
6924       if (!cgraph_function_with_gimple_body_p (node))
6925         continue;
6926
6927       fn = DECL_STRUCT_FUNCTION (node->decl);
6928
6929       /* Compute the points-to sets for pointer SSA_NAMEs.  */
6930       FOR_EACH_VEC_ELT (tree, fn->gimple_df->ssa_names, i, ptr)
6931         {
6932           if (ptr
6933               && POINTER_TYPE_P (TREE_TYPE (ptr)))
6934             find_what_p_points_to (ptr);
6935         }
6936
6937       /* Compute the call-use and call-clobber sets for all direct calls.  */
6938       fi = lookup_vi_for_tree (node->decl);
6939       gcc_assert (fi->is_fn_info);
6940       find_what_var_points_to (first_vi_for_offset (fi, fi_clobbers),
6941                                &clobbers);
6942       find_what_var_points_to (first_vi_for_offset (fi, fi_uses), &uses);
6943       for (e = node->callers; e; e = e->next_caller)
6944         {
6945           if (!e->call_stmt)
6946             continue;
6947
6948           *gimple_call_clobber_set (e->call_stmt) = clobbers;
6949           *gimple_call_use_set (e->call_stmt) = uses;
6950         }
6951
6952       /* Compute the call-use and call-clobber sets for indirect calls
6953          and calls to external functions.  */
6954       FOR_EACH_BB_FN (bb, fn)
6955         {
6956           gimple_stmt_iterator gsi;
6957
6958           for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6959             {
6960               gimple stmt = gsi_stmt (gsi);
6961               struct pt_solution *pt;
6962               varinfo_t vi;
6963               tree decl;
6964
6965               if (!is_gimple_call (stmt))
6966                 continue;
6967
6968               /* Handle direct calls to external functions.  */
6969               decl = gimple_call_fndecl (stmt);
6970               if (decl
6971                   && (!(fi = lookup_vi_for_tree (decl))
6972                       || !fi->is_fn_info))
6973                 {
6974                   pt = gimple_call_use_set (stmt);
6975                   if (gimple_call_flags (stmt) & ECF_CONST)
6976                     memset (pt, 0, sizeof (struct pt_solution));
6977                   else if ((vi = lookup_call_use_vi (stmt)) != NULL)
6978                     {
6979                       find_what_var_points_to (vi, pt);
6980                       /* Escaped (and thus nonlocal) variables are always
6981                          implicitly used by calls.  */
6982                       /* ???  ESCAPED can be empty even though NONLOCAL
6983                          always escaped.  */
6984                       pt->nonlocal = 1;
6985                       pt->ipa_escaped = 1;
6986                     }
6987                   else
6988                     {
6989                       /* If there is nothing special about this call then
6990                          we have made everything that is used also escape.  */
6991                       *pt = ipa_escaped_pt;
6992                       pt->nonlocal = 1;
6993                     }
6994
6995                   pt = gimple_call_clobber_set (stmt);
6996                   if (gimple_call_flags (stmt) & (ECF_CONST|ECF_PURE|ECF_NOVOPS))
6997                     memset (pt, 0, sizeof (struct pt_solution));
6998                   else if ((vi = lookup_call_clobber_vi (stmt)) != NULL)
6999                     {
7000                       find_what_var_points_to (vi, pt);
7001                       /* Escaped (and thus nonlocal) variables are always
7002                          implicitly clobbered by calls.  */
7003                       /* ???  ESCAPED can be empty even though NONLOCAL
7004                          always escaped.  */
7005                       pt->nonlocal = 1;
7006                       pt->ipa_escaped = 1;
7007                     }
7008                   else
7009                     {
7010                       /* If there is nothing special about this call then
7011                          we have made everything that is used also escape.  */
7012                       *pt = ipa_escaped_pt;
7013                       pt->nonlocal = 1;
7014                     }
7015                 }
7016
7017               /* Handle indirect calls.  */
7018               if (!decl
7019                   && (fi = get_fi_for_callee (stmt)))
7020                 {
7021                   /* We need to accumulate all clobbers/uses of all possible
7022                      callees.  */
7023                   fi = get_varinfo (find (fi->id));
7024                   /* If we cannot constrain the set of functions we'll end up
7025                      calling we end up using/clobbering everything.  */
7026                   if (bitmap_bit_p (fi->solution, anything_id)
7027                       || bitmap_bit_p (fi->solution, nonlocal_id)
7028                       || bitmap_bit_p (fi->solution, escaped_id))
7029                     {
7030                       pt_solution_reset (gimple_call_clobber_set (stmt));
7031                       pt_solution_reset (gimple_call_use_set (stmt));
7032                     }
7033                   else
7034                     {
7035                       bitmap_iterator bi;
7036                       unsigned i;
7037                       struct pt_solution *uses, *clobbers;
7038
7039                       uses = gimple_call_use_set (stmt);
7040                       clobbers = gimple_call_clobber_set (stmt);
7041                       memset (uses, 0, sizeof (struct pt_solution));
7042                       memset (clobbers, 0, sizeof (struct pt_solution));
7043                       EXECUTE_IF_SET_IN_BITMAP (fi->solution, 0, i, bi)
7044                         {
7045                           struct pt_solution sol;
7046
7047                           vi = get_varinfo (i);
7048                           if (!vi->is_fn_info)
7049                             {
7050                               /* ???  We could be more precise here?  */
7051                               uses->nonlocal = 1;
7052                               uses->ipa_escaped = 1;
7053                               clobbers->nonlocal = 1;
7054                               clobbers->ipa_escaped = 1;
7055                               continue;
7056                             }
7057
7058                           if (!uses->anything)
7059                             {
7060                               find_what_var_points_to
7061                                   (first_vi_for_offset (vi, fi_uses), &sol);
7062                               pt_solution_ior_into (uses, &sol);
7063                             }
7064                           if (!clobbers->anything)
7065                             {
7066                               find_what_var_points_to
7067                                   (first_vi_for_offset (vi, fi_clobbers), &sol);
7068                               pt_solution_ior_into (clobbers, &sol);
7069                             }
7070                         }
7071                     }
7072                 }
7073             }
7074         }
7075
7076       fn->gimple_df->ipa_pta = true;
7077     }
7078
7079   delete_points_to_sets ();
7080
7081   in_ipa_mode = 0;
7082
7083   return 0;
7084 }
7085
7086 struct simple_ipa_opt_pass pass_ipa_pta =
7087 {
7088  {
7089   SIMPLE_IPA_PASS,
7090   "pta",                                /* name */
7091   gate_ipa_pta,                 /* gate */
7092   ipa_pta_execute,                      /* execute */
7093   NULL,                                 /* sub */
7094   NULL,                                 /* next */
7095   0,                                    /* static_pass_number */
7096   TV_IPA_PTA,                   /* tv_id */
7097   0,                                    /* properties_required */
7098   0,                                    /* properties_provided */
7099   0,                                    /* properties_destroyed */
7100   0,                                    /* todo_flags_start */
7101   TODO_update_ssa                       /* todo_flags_finish */
7102  }
7103 };