OSDN Git Service

1cb07f5581cee093ec1103ef72a934bf5b05862e
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-structalias.c
1 /* Tree based points-to analysis
2    Copyright (C) 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
3    Contributed by Daniel Berlin <dberlin@dberlin.org>
4
5    This file is part of GCC.
6
7    GCC is free software; you can redistribute it and/or modify
8    under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    GCC is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GCC; see the file COPYING3.  If not see
19    <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "ggc.h"
26 #include "obstack.h"
27 #include "bitmap.h"
28 #include "flags.h"
29 #include "rtl.h"
30 #include "tm_p.h"
31 #include "hard-reg-set.h"
32 #include "basic-block.h"
33 #include "output.h"
34 #include "tree.h"
35 #include "c-common.h"
36 #include "tree-flow.h"
37 #include "tree-inline.h"
38 #include "varray.h"
39 #include "c-tree.h"
40 #include "diagnostic.h"
41 #include "toplev.h"
42 #include "gimple.h"
43 #include "hashtab.h"
44 #include "function.h"
45 #include "cgraph.h"
46 #include "tree-pass.h"
47 #include "timevar.h"
48 #include "alloc-pool.h"
49 #include "splay-tree.h"
50 #include "params.h"
51 #include "tree-ssa-structalias.h"
52 #include "cgraph.h"
53 #include "alias.h"
54 #include "pointer-set.h"
55
56 /* The idea behind this analyzer is to generate set constraints from the
57    program, then solve the resulting constraints in order to generate the
58    points-to sets.
59
60    Set constraints are a way of modeling program analysis problems that
61    involve sets.  They consist of an inclusion constraint language,
62    describing the variables (each variable is a set) and operations that
63    are involved on the variables, and a set of rules that derive facts
64    from these operations.  To solve a system of set constraints, you derive
65    all possible facts under the rules, which gives you the correct sets
66    as a consequence.
67
68    See  "Efficient Field-sensitive pointer analysis for C" by "David
69    J. Pearce and Paul H. J. Kelly and Chris Hankin, at
70    http://citeseer.ist.psu.edu/pearce04efficient.html
71
72    Also see "Ultra-fast Aliasing Analysis using CLA: A Million Lines
73    of C Code in a Second" by ""Nevin Heintze and Olivier Tardieu" at
74    http://citeseer.ist.psu.edu/heintze01ultrafast.html
75
76    There are three types of real constraint expressions, DEREF,
77    ADDRESSOF, and SCALAR.  Each constraint expression consists
78    of a constraint type, a variable, and an offset.
79
80    SCALAR is a constraint expression type used to represent x, whether
81    it appears on the LHS or the RHS of a statement.
82    DEREF is a constraint expression type used to represent *x, whether
83    it appears on the LHS or the RHS of a statement.
84    ADDRESSOF is a constraint expression used to represent &x, whether
85    it appears on the LHS or the RHS of a statement.
86
87    Each pointer variable in the program is assigned an integer id, and
88    each field of a structure variable is assigned an integer id as well.
89
90    Structure variables are linked to their list of fields through a "next
91    field" in each variable that points to the next field in offset
92    order.
93    Each variable for a structure field has
94
95    1. "size", that tells the size in bits of that field.
96    2. "fullsize, that tells the size in bits of the entire structure.
97    3. "offset", that tells the offset in bits from the beginning of the
98    structure to this field.
99
100    Thus,
101    struct f
102    {
103      int a;
104      int b;
105    } foo;
106    int *bar;
107
108    looks like
109
110    foo.a -> id 1, size 32, offset 0, fullsize 64, next foo.b
111    foo.b -> id 2, size 32, offset 32, fullsize 64, next NULL
112    bar -> id 3, size 32, offset 0, fullsize 32, next NULL
113
114
115   In order to solve the system of set constraints, the following is
116   done:
117
118   1. Each constraint variable x has a solution set associated with it,
119   Sol(x).
120
121   2. Constraints are separated into direct, copy, and complex.
122   Direct constraints are ADDRESSOF constraints that require no extra
123   processing, such as P = &Q
124   Copy constraints are those of the form P = Q.
125   Complex constraints are all the constraints involving dereferences
126   and offsets (including offsetted copies).
127
128   3. All direct constraints of the form P = &Q are processed, such
129   that Q is added to Sol(P)
130
131   4. All complex constraints for a given constraint variable are stored in a
132   linked list attached to that variable's node.
133
134   5. A directed graph is built out of the copy constraints. Each
135   constraint variable is a node in the graph, and an edge from
136   Q to P is added for each copy constraint of the form P = Q
137
138   6. The graph is then walked, and solution sets are
139   propagated along the copy edges, such that an edge from Q to P
140   causes Sol(P) <- Sol(P) union Sol(Q).
141
142   7.  As we visit each node, all complex constraints associated with
143   that node are processed by adding appropriate copy edges to the graph, or the
144   appropriate variables to the solution set.
145
146   8. The process of walking the graph is iterated until no solution
147   sets change.
148
149   Prior to walking the graph in steps 6 and 7, We perform static
150   cycle elimination on the constraint graph, as well
151   as off-line variable substitution.
152
153   TODO: Adding offsets to pointer-to-structures can be handled (IE not punted
154   on and turned into anything), but isn't.  You can just see what offset
155   inside the pointed-to struct it's going to access.
156
157   TODO: Constant bounded arrays can be handled as if they were structs of the
158   same number of elements.
159
160   TODO: Modeling heap and incoming pointers becomes much better if we
161   add fields to them as we discover them, which we could do.
162
163   TODO: We could handle unions, but to be honest, it's probably not
164   worth the pain or slowdown.  */
165
166 static GTY ((if_marked ("tree_map_marked_p"), param_is (struct tree_map)))
167 htab_t heapvar_for_stmt;
168
169 static bool use_field_sensitive = true;
170 static int in_ipa_mode = 0;
171
172 /* Used for predecessor bitmaps. */
173 static bitmap_obstack predbitmap_obstack;
174
175 /* Used for points-to sets.  */
176 static bitmap_obstack pta_obstack;
177
178 /* Used for oldsolution members of variables. */
179 static bitmap_obstack oldpta_obstack;
180
181 /* Used for per-solver-iteration bitmaps.  */
182 static bitmap_obstack iteration_obstack;
183
184 static unsigned int create_variable_info_for (tree, const char *);
185 typedef struct constraint_graph *constraint_graph_t;
186 static void unify_nodes (constraint_graph_t, unsigned int, unsigned int, bool);
187
188 DEF_VEC_P(constraint_t);
189 DEF_VEC_ALLOC_P(constraint_t,heap);
190
191 #define EXECUTE_IF_IN_NONNULL_BITMAP(a, b, c, d)        \
192   if (a)                                                \
193     EXECUTE_IF_SET_IN_BITMAP (a, b, c, d)
194
195 static struct constraint_stats
196 {
197   unsigned int total_vars;
198   unsigned int nonpointer_vars;
199   unsigned int unified_vars_static;
200   unsigned int unified_vars_dynamic;
201   unsigned int iterations;
202   unsigned int num_edges;
203   unsigned int num_implicit_edges;
204   unsigned int points_to_sets_created;
205 } stats;
206
207 struct variable_info
208 {
209   /* ID of this variable  */
210   unsigned int id;
211
212   /* True if this is a variable created by the constraint analysis, such as
213      heap variables and constraints we had to break up.  */
214   unsigned int is_artificial_var:1;
215
216   /* True if this is a special variable whose solution set should not be
217      changed.  */
218   unsigned int is_special_var:1;
219
220   /* True for variables whose size is not known or variable.  */
221   unsigned int is_unknown_size_var:1;
222
223   /* True for (sub-)fields that represent a whole variable.  */
224   unsigned int is_full_var : 1;
225
226   /* True if this is a heap variable.  */
227   unsigned int is_heap_var:1;
228
229   /* True if we may not use TBAA to prune references to this
230      variable.  This is used for C++ placement new.  */
231   unsigned int no_tbaa_pruning : 1;
232
233   /* True if this field may contain pointers.  */
234   unsigned int may_have_pointers : 1;
235
236   /* Variable id this was collapsed to due to type unsafety.  Zero if
237      this variable was not collapsed.  This should be unused completely
238      after build_succ_graph, or something is broken.  */
239   unsigned int collapsed_to;
240
241   /* A link to the variable for the next field in this structure.  */
242   struct variable_info *next;
243
244   /* Offset of this variable, in bits, from the base variable  */
245   unsigned HOST_WIDE_INT offset;
246
247   /* Size of the variable, in bits.  */
248   unsigned HOST_WIDE_INT size;
249
250   /* Full size of the base variable, in bits.  */
251   unsigned HOST_WIDE_INT fullsize;
252
253   /* Name of this variable */
254   const char *name;
255
256   /* Tree that this variable is associated with.  */
257   tree decl;
258
259   /* Points-to set for this variable.  */
260   bitmap solution;
261
262   /* Old points-to set for this variable.  */
263   bitmap oldsolution;
264 };
265 typedef struct variable_info *varinfo_t;
266
267 static varinfo_t first_vi_for_offset (varinfo_t, unsigned HOST_WIDE_INT);
268 static varinfo_t lookup_vi_for_tree (tree);
269
270 /* Pool of variable info structures.  */
271 static alloc_pool variable_info_pool;
272
273 DEF_VEC_P(varinfo_t);
274
275 DEF_VEC_ALLOC_P(varinfo_t, heap);
276
277 /* Table of variable info structures for constraint variables.
278    Indexed directly by variable info id.  */
279 static VEC(varinfo_t,heap) *varmap;
280
281 /* Return the varmap element N */
282
283 static inline varinfo_t
284 get_varinfo (unsigned int n)
285 {
286   return VEC_index (varinfo_t, varmap, n);
287 }
288
289 /* Return the varmap element N, following the collapsed_to link.  */
290
291 static inline varinfo_t
292 get_varinfo_fc (unsigned int n)
293 {
294   varinfo_t v = VEC_index (varinfo_t, varmap, n);
295
296   if (v->collapsed_to != 0)
297     return get_varinfo (v->collapsed_to);
298   return v;
299 }
300
301 /* Static IDs for the special variables.  */
302 enum { nothing_id = 0, anything_id = 1, readonly_id = 2,
303        escaped_id = 3, nonlocal_id = 4, callused_id = 5,
304        storedanything_id = 6, integer_id = 7 };
305
306 /* Variable that represents the unknown pointer.  */
307 static varinfo_t var_anything;
308 static tree anything_tree;
309
310 /* Variable that represents the NULL pointer.  */
311 static varinfo_t var_nothing;
312 static tree nothing_tree;
313
314 /* Variable that represents read only memory.  */
315 static varinfo_t var_readonly;
316 static tree readonly_tree;
317
318 /* Variable that represents escaped memory.  */
319 static varinfo_t var_escaped;
320 static tree escaped_tree;
321
322 /* Variable that represents nonlocal memory.  */
323 static varinfo_t var_nonlocal;
324 static tree nonlocal_tree;
325
326 /* Variable that represents call-used memory.  */
327 static varinfo_t var_callused;
328 static tree callused_tree;
329
330 /* Variable that represents variables that are stored to anything.  */
331 static varinfo_t var_storedanything;
332 static tree storedanything_tree;
333
334 /* Variable that represents integers.  This is used for when people do things
335    like &0->a.b.  */
336 static varinfo_t var_integer;
337 static tree integer_tree;
338
339 /* Lookup a heap var for FROM, and return it if we find one.  */
340
341 static tree
342 heapvar_lookup (tree from)
343 {
344   struct tree_map *h, in;
345   in.base.from = from;
346
347   h = (struct tree_map *) htab_find_with_hash (heapvar_for_stmt, &in,
348                                                htab_hash_pointer (from));
349   if (h)
350     return h->to;
351   return NULL_TREE;
352 }
353
354 /* Insert a mapping FROM->TO in the heap var for statement
355    hashtable.  */
356
357 static void
358 heapvar_insert (tree from, tree to)
359 {
360   struct tree_map *h;
361   void **loc;
362
363   h = GGC_NEW (struct tree_map);
364   h->hash = htab_hash_pointer (from);
365   h->base.from = from;
366   h->to = to;
367   loc = htab_find_slot_with_hash (heapvar_for_stmt, h, h->hash, INSERT);
368   *(struct tree_map **) loc = h;
369 }
370
371 /* Return a new variable info structure consisting for a variable
372    named NAME, and using constraint graph node NODE.  */
373
374 static varinfo_t
375 new_var_info (tree t, unsigned int id, const char *name)
376 {
377   varinfo_t ret = (varinfo_t) pool_alloc (variable_info_pool);
378   tree var;
379
380   ret->id = id;
381   ret->name = name;
382   ret->decl = t;
383   ret->is_artificial_var = false;
384   ret->is_heap_var = false;
385   ret->is_special_var = false;
386   ret->is_unknown_size_var = false;
387   ret->is_full_var = false;
388   ret->may_have_pointers = true;
389   var = t;
390   if (TREE_CODE (var) == SSA_NAME)
391     var = SSA_NAME_VAR (var);
392   ret->no_tbaa_pruning = (DECL_P (var)
393                           && POINTER_TYPE_P (TREE_TYPE (var))
394                           && DECL_NO_TBAA_P (var));
395   ret->solution = BITMAP_ALLOC (&pta_obstack);
396   ret->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
397   ret->next = NULL;
398   ret->collapsed_to = 0;
399   return ret;
400 }
401
402 typedef enum {SCALAR, DEREF, ADDRESSOF} constraint_expr_type;
403
404 /* An expression that appears in a constraint.  */
405
406 struct constraint_expr
407 {
408   /* Constraint type.  */
409   constraint_expr_type type;
410
411   /* Variable we are referring to in the constraint.  */
412   unsigned int var;
413
414   /* Offset, in bits, of this constraint from the beginning of
415      variables it ends up referring to.
416
417      IOW, in a deref constraint, we would deref, get the result set,
418      then add OFFSET to each member.   */
419   unsigned HOST_WIDE_INT offset;
420 };
421
422 typedef struct constraint_expr ce_s;
423 DEF_VEC_O(ce_s);
424 DEF_VEC_ALLOC_O(ce_s, heap);
425 static void get_constraint_for_1 (tree, VEC(ce_s, heap) **, bool);
426 static void get_constraint_for (tree, VEC(ce_s, heap) **);
427 static void do_deref (VEC (ce_s, heap) **);
428
429 /* Our set constraints are made up of two constraint expressions, one
430    LHS, and one RHS.
431
432    As described in the introduction, our set constraints each represent an
433    operation between set valued variables.
434 */
435 struct constraint
436 {
437   struct constraint_expr lhs;
438   struct constraint_expr rhs;
439 };
440
441 /* List of constraints that we use to build the constraint graph from.  */
442
443 static VEC(constraint_t,heap) *constraints;
444 static alloc_pool constraint_pool;
445
446
447 DEF_VEC_I(int);
448 DEF_VEC_ALLOC_I(int, heap);
449
450 /* The constraint graph is represented as an array of bitmaps
451    containing successor nodes.  */
452
453 struct constraint_graph
454 {
455   /* Size of this graph, which may be different than the number of
456      nodes in the variable map.  */
457   unsigned int size;
458
459   /* Explicit successors of each node. */
460   bitmap *succs;
461
462   /* Implicit predecessors of each node (Used for variable
463      substitution). */
464   bitmap *implicit_preds;
465
466   /* Explicit predecessors of each node (Used for variable substitution).  */
467   bitmap *preds;
468
469   /* Indirect cycle representatives, or -1 if the node has no indirect
470      cycles.  */
471   int *indirect_cycles;
472
473   /* Representative node for a node.  rep[a] == a unless the node has
474      been unified. */
475   unsigned int *rep;
476
477   /* Equivalence class representative for a label.  This is used for
478      variable substitution.  */
479   int *eq_rep;
480
481   /* Pointer equivalence label for a node.  All nodes with the same
482      pointer equivalence label can be unified together at some point
483      (either during constraint optimization or after the constraint
484      graph is built).  */
485   unsigned int *pe;
486
487   /* Pointer equivalence representative for a label.  This is used to
488      handle nodes that are pointer equivalent but not location
489      equivalent.  We can unite these once the addressof constraints
490      are transformed into initial points-to sets.  */
491   int *pe_rep;
492
493   /* Pointer equivalence label for each node, used during variable
494      substitution.  */
495   unsigned int *pointer_label;
496
497   /* Location equivalence label for each node, used during location
498      equivalence finding.  */
499   unsigned int *loc_label;
500
501   /* Pointed-by set for each node, used during location equivalence
502      finding.  This is pointed-by rather than pointed-to, because it
503      is constructed using the predecessor graph.  */
504   bitmap *pointed_by;
505
506   /* Points to sets for pointer equivalence.  This is *not* the actual
507      points-to sets for nodes.  */
508   bitmap *points_to;
509
510   /* Bitmap of nodes where the bit is set if the node is a direct
511      node.  Used for variable substitution.  */
512   sbitmap direct_nodes;
513
514   /* Bitmap of nodes where the bit is set if the node is address
515      taken.  Used for variable substitution.  */
516   bitmap address_taken;
517
518   /* Vector of complex constraints for each graph node.  Complex
519      constraints are those involving dereferences or offsets that are
520      not 0.  */
521   VEC(constraint_t,heap) **complex;
522 };
523
524 static constraint_graph_t graph;
525
526 /* During variable substitution and the offline version of indirect
527    cycle finding, we create nodes to represent dereferences and
528    address taken constraints.  These represent where these start and
529    end.  */
530 #define FIRST_REF_NODE (VEC_length (varinfo_t, varmap))
531 #define LAST_REF_NODE (FIRST_REF_NODE + (FIRST_REF_NODE - 1))
532
533 /* Return the representative node for NODE, if NODE has been unioned
534    with another NODE.
535    This function performs path compression along the way to finding
536    the representative.  */
537
538 static unsigned int
539 find (unsigned int node)
540 {
541   gcc_assert (node < graph->size);
542   if (graph->rep[node] != node)
543     return graph->rep[node] = find (graph->rep[node]);
544   return node;
545 }
546
547 /* Union the TO and FROM nodes to the TO nodes.
548    Note that at some point in the future, we may want to do
549    union-by-rank, in which case we are going to have to return the
550    node we unified to.  */
551
552 static bool
553 unite (unsigned int to, unsigned int from)
554 {
555   gcc_assert (to < graph->size && from < graph->size);
556   if (to != from && graph->rep[from] != to)
557     {
558       graph->rep[from] = to;
559       return true;
560     }
561   return false;
562 }
563
564 /* Create a new constraint consisting of LHS and RHS expressions.  */
565
566 static constraint_t
567 new_constraint (const struct constraint_expr lhs,
568                 const struct constraint_expr rhs)
569 {
570   constraint_t ret = (constraint_t) pool_alloc (constraint_pool);
571   ret->lhs = lhs;
572   ret->rhs = rhs;
573   return ret;
574 }
575
576 /* Print out constraint C to FILE.  */
577
578 void
579 dump_constraint (FILE *file, constraint_t c)
580 {
581   if (c->lhs.type == ADDRESSOF)
582     fprintf (file, "&");
583   else if (c->lhs.type == DEREF)
584     fprintf (file, "*");
585   fprintf (file, "%s", get_varinfo_fc (c->lhs.var)->name);
586   if (c->lhs.offset != 0)
587     fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->lhs.offset);
588   fprintf (file, " = ");
589   if (c->rhs.type == ADDRESSOF)
590     fprintf (file, "&");
591   else if (c->rhs.type == DEREF)
592     fprintf (file, "*");
593   fprintf (file, "%s", get_varinfo_fc (c->rhs.var)->name);
594   if (c->rhs.offset != 0)
595     fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->rhs.offset);
596   fprintf (file, "\n");
597 }
598
599 /* Print out constraint C to stderr.  */
600
601 void
602 debug_constraint (constraint_t c)
603 {
604   dump_constraint (stderr, c);
605 }
606
607 /* Print out all constraints to FILE */
608
609 void
610 dump_constraints (FILE *file)
611 {
612   int i;
613   constraint_t c;
614   for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
615     dump_constraint (file, c);
616 }
617
618 /* Print out all constraints to stderr.  */
619
620 void
621 debug_constraints (void)
622 {
623   dump_constraints (stderr);
624 }
625
626 /* Print out to FILE the edge in the constraint graph that is created by
627    constraint c. The edge may have a label, depending on the type of
628    constraint that it represents. If complex1, e.g: a = *b, then the label
629    is "=*", if complex2, e.g: *a = b, then the label is "*=", if
630    complex with an offset, e.g: a = b + 8, then the label is "+".
631    Otherwise the edge has no label.  */
632
633 void
634 dump_constraint_edge (FILE *file, constraint_t c)
635 {
636   if (c->rhs.type != ADDRESSOF)
637     {
638       const char *src = get_varinfo_fc (c->rhs.var)->name;
639       const char *dst = get_varinfo_fc (c->lhs.var)->name;
640       fprintf (file, "  \"%s\" -> \"%s\" ", src, dst);
641       /* Due to preprocessing of constraints, instructions like *a = *b are
642          illegal; thus, we do not have to handle such cases.  */
643       if (c->lhs.type == DEREF)
644         fprintf (file, " [ label=\"*=\" ] ;\n");
645       else if (c->rhs.type == DEREF)
646         fprintf (file, " [ label=\"=*\" ] ;\n");
647       else
648         {
649           /* We must check the case where the constraint is an offset.
650              In this case, it is treated as a complex constraint.  */
651           if (c->rhs.offset != c->lhs.offset)
652             fprintf (file, " [ label=\"+\" ] ;\n");
653           else
654             fprintf (file, " ;\n");
655         }
656     }
657 }
658
659 /* Print the constraint graph in dot format.  */
660
661 void
662 dump_constraint_graph (FILE *file)
663 {
664   unsigned int i=0, size;
665   constraint_t c;
666
667   /* Only print the graph if it has already been initialized:  */
668   if (!graph)
669     return;
670
671   /* Print the constraints used to produce the constraint graph. The
672      constraints will be printed as comments in the dot file:  */
673   fprintf (file, "\n\n/* Constraints used in the constraint graph:\n");
674   dump_constraints (file);
675   fprintf (file, "*/\n");
676
677   /* Prints the header of the dot file:  */
678   fprintf (file, "\n\n// The constraint graph in dot format:\n");
679   fprintf (file, "strict digraph {\n");
680   fprintf (file, "  node [\n    shape = box\n  ]\n");
681   fprintf (file, "  edge [\n    fontsize = \"12\"\n  ]\n");
682   fprintf (file, "\n  // List of nodes in the constraint graph:\n");
683
684   /* The next lines print the nodes in the graph. In order to get the
685      number of nodes in the graph, we must choose the minimum between the
686      vector VEC (varinfo_t, varmap) and graph->size. If the graph has not
687      yet been initialized, then graph->size == 0, otherwise we must only
688      read nodes that have an entry in VEC (varinfo_t, varmap).  */
689   size = VEC_length (varinfo_t, varmap);
690   size = size < graph->size ? size : graph->size;
691   for (i = 0; i < size; i++)
692     {
693       const char *name = get_varinfo_fc (graph->rep[i])->name;
694       fprintf (file, "  \"%s\" ;\n", name);
695     }
696
697   /* Go over the list of constraints printing the edges in the constraint
698      graph.  */
699   fprintf (file, "\n  // The constraint edges:\n");
700   for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
701     if (c)
702       dump_constraint_edge (file, c);
703
704   /* Prints the tail of the dot file. By now, only the closing bracket.  */
705   fprintf (file, "}\n\n\n");
706 }
707
708 /* Print out the constraint graph to stderr.  */
709
710 void
711 debug_constraint_graph (void)
712 {
713   dump_constraint_graph (stderr);
714 }
715
716 /* SOLVER FUNCTIONS
717
718    The solver is a simple worklist solver, that works on the following
719    algorithm:
720
721    sbitmap changed_nodes = all zeroes;
722    changed_count = 0;
723    For each node that is not already collapsed:
724        changed_count++;
725        set bit in changed nodes
726
727    while (changed_count > 0)
728    {
729      compute topological ordering for constraint graph
730
731      find and collapse cycles in the constraint graph (updating
732      changed if necessary)
733
734      for each node (n) in the graph in topological order:
735        changed_count--;
736
737        Process each complex constraint associated with the node,
738        updating changed if necessary.
739
740        For each outgoing edge from n, propagate the solution from n to
741        the destination of the edge, updating changed as necessary.
742
743    }  */
744
745 /* Return true if two constraint expressions A and B are equal.  */
746
747 static bool
748 constraint_expr_equal (struct constraint_expr a, struct constraint_expr b)
749 {
750   return a.type == b.type && a.var == b.var && a.offset == b.offset;
751 }
752
753 /* Return true if constraint expression A is less than constraint expression
754    B.  This is just arbitrary, but consistent, in order to give them an
755    ordering.  */
756
757 static bool
758 constraint_expr_less (struct constraint_expr a, struct constraint_expr b)
759 {
760   if (a.type == b.type)
761     {
762       if (a.var == b.var)
763         return a.offset < b.offset;
764       else
765         return a.var < b.var;
766     }
767   else
768     return a.type < b.type;
769 }
770
771 /* Return true if constraint A is less than constraint B.  This is just
772    arbitrary, but consistent, in order to give them an ordering.  */
773
774 static bool
775 constraint_less (const constraint_t a, const constraint_t b)
776 {
777   if (constraint_expr_less (a->lhs, b->lhs))
778     return true;
779   else if (constraint_expr_less (b->lhs, a->lhs))
780     return false;
781   else
782     return constraint_expr_less (a->rhs, b->rhs);
783 }
784
785 /* Return true if two constraints A and B are equal.  */
786
787 static bool
788 constraint_equal (struct constraint a, struct constraint b)
789 {
790   return constraint_expr_equal (a.lhs, b.lhs)
791     && constraint_expr_equal (a.rhs, b.rhs);
792 }
793
794
795 /* Find a constraint LOOKFOR in the sorted constraint vector VEC */
796
797 static constraint_t
798 constraint_vec_find (VEC(constraint_t,heap) *vec,
799                      struct constraint lookfor)
800 {
801   unsigned int place;
802   constraint_t found;
803
804   if (vec == NULL)
805     return NULL;
806
807   place = VEC_lower_bound (constraint_t, vec, &lookfor, constraint_less);
808   if (place >= VEC_length (constraint_t, vec))
809     return NULL;
810   found = VEC_index (constraint_t, vec, place);
811   if (!constraint_equal (*found, lookfor))
812     return NULL;
813   return found;
814 }
815
816 /* Union two constraint vectors, TO and FROM.  Put the result in TO.  */
817
818 static void
819 constraint_set_union (VEC(constraint_t,heap) **to,
820                       VEC(constraint_t,heap) **from)
821 {
822   int i;
823   constraint_t c;
824
825   for (i = 0; VEC_iterate (constraint_t, *from, i, c); i++)
826     {
827       if (constraint_vec_find (*to, *c) == NULL)
828         {
829           unsigned int place = VEC_lower_bound (constraint_t, *to, c,
830                                                 constraint_less);
831           VEC_safe_insert (constraint_t, heap, *to, place, c);
832         }
833     }
834 }
835
836 /* Take a solution set SET, add OFFSET to each member of the set, and
837    overwrite SET with the result when done.  */
838
839 static void
840 solution_set_add (bitmap set, unsigned HOST_WIDE_INT offset)
841 {
842   bitmap result = BITMAP_ALLOC (&iteration_obstack);
843   unsigned int i;
844   bitmap_iterator bi;
845
846   EXECUTE_IF_SET_IN_BITMAP (set, 0, i, bi)
847     {
848       varinfo_t vi = get_varinfo (i);
849
850       /* If this is a variable with just one field just set its bit
851          in the result.  */
852       if (vi->is_artificial_var
853           || vi->is_unknown_size_var
854           || vi->is_full_var)
855         bitmap_set_bit (result, i);
856       else
857         {
858           unsigned HOST_WIDE_INT fieldoffset = vi->offset + offset;
859           varinfo_t v = first_vi_for_offset (vi, fieldoffset);
860           /* If the result is outside of the variable use the last field.  */
861           if (!v)
862             {
863               v = vi;
864               while (v->next != NULL)
865                 v = v->next;
866             }
867           bitmap_set_bit (result, v->id);
868           /* If the result is not exactly at fieldoffset include the next
869              field as well.  See get_constraint_for_ptr_offset for more
870              rationale.  */
871           if (v->offset != fieldoffset
872               && v->next != NULL)
873             bitmap_set_bit (result, v->next->id);
874         }
875     }
876
877   bitmap_copy (set, result);
878   BITMAP_FREE (result);
879 }
880
881 /* Union solution sets TO and FROM, and add INC to each member of FROM in the
882    process.  */
883
884 static bool
885 set_union_with_increment  (bitmap to, bitmap from, unsigned HOST_WIDE_INT inc)
886 {
887   if (inc == 0)
888     return bitmap_ior_into (to, from);
889   else
890     {
891       bitmap tmp;
892       bool res;
893
894       tmp = BITMAP_ALLOC (&iteration_obstack);
895       bitmap_copy (tmp, from);
896       solution_set_add (tmp, inc);
897       res = bitmap_ior_into (to, tmp);
898       BITMAP_FREE (tmp);
899       return res;
900     }
901 }
902
903 /* Insert constraint C into the list of complex constraints for graph
904    node VAR.  */
905
906 static void
907 insert_into_complex (constraint_graph_t graph,
908                      unsigned int var, constraint_t c)
909 {
910   VEC (constraint_t, heap) *complex = graph->complex[var];
911   unsigned int place = VEC_lower_bound (constraint_t, complex, c,
912                                         constraint_less);
913
914   /* Only insert constraints that do not already exist.  */
915   if (place >= VEC_length (constraint_t, complex)
916       || !constraint_equal (*c, *VEC_index (constraint_t, complex, place)))
917     VEC_safe_insert (constraint_t, heap, graph->complex[var], place, c);
918 }
919
920
921 /* Condense two variable nodes into a single variable node, by moving
922    all associated info from SRC to TO.  */
923
924 static void
925 merge_node_constraints (constraint_graph_t graph, unsigned int to,
926                         unsigned int from)
927 {
928   unsigned int i;
929   constraint_t c;
930
931   gcc_assert (find (from) == to);
932
933   /* Move all complex constraints from src node into to node  */
934   for (i = 0; VEC_iterate (constraint_t, graph->complex[from], i, c); i++)
935     {
936       /* In complex constraints for node src, we may have either
937          a = *src, and *src = a, or an offseted constraint which are
938          always added to the rhs node's constraints.  */
939
940       if (c->rhs.type == DEREF)
941         c->rhs.var = to;
942       else if (c->lhs.type == DEREF)
943         c->lhs.var = to;
944       else
945         c->rhs.var = to;
946     }
947   constraint_set_union (&graph->complex[to], &graph->complex[from]);
948   VEC_free (constraint_t, heap, graph->complex[from]);
949   graph->complex[from] = NULL;
950 }
951
952
953 /* Remove edges involving NODE from GRAPH.  */
954
955 static void
956 clear_edges_for_node (constraint_graph_t graph, unsigned int node)
957 {
958   if (graph->succs[node])
959     BITMAP_FREE (graph->succs[node]);
960 }
961
962 /* Merge GRAPH nodes FROM and TO into node TO.  */
963
964 static void
965 merge_graph_nodes (constraint_graph_t graph, unsigned int to,
966                    unsigned int from)
967 {
968   if (graph->indirect_cycles[from] != -1)
969     {
970       /* If we have indirect cycles with the from node, and we have
971          none on the to node, the to node has indirect cycles from the
972          from node now that they are unified.
973          If indirect cycles exist on both, unify the nodes that they
974          are in a cycle with, since we know they are in a cycle with
975          each other.  */
976       if (graph->indirect_cycles[to] == -1)
977         graph->indirect_cycles[to] = graph->indirect_cycles[from];
978     }
979
980   /* Merge all the successor edges.  */
981   if (graph->succs[from])
982     {
983       if (!graph->succs[to])
984         graph->succs[to] = BITMAP_ALLOC (&pta_obstack);
985       bitmap_ior_into (graph->succs[to],
986                        graph->succs[from]);
987     }
988
989   clear_edges_for_node (graph, from);
990 }
991
992
993 /* Add an indirect graph edge to GRAPH, going from TO to FROM if
994    it doesn't exist in the graph already.  */
995
996 static void
997 add_implicit_graph_edge (constraint_graph_t graph, unsigned int to,
998                          unsigned int from)
999 {
1000   if (to == from)
1001     return;
1002
1003   if (!graph->implicit_preds[to])
1004     graph->implicit_preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1005
1006   if (bitmap_set_bit (graph->implicit_preds[to], from))
1007     stats.num_implicit_edges++;
1008 }
1009
1010 /* Add a predecessor graph edge to GRAPH, going from TO to FROM if
1011    it doesn't exist in the graph already.
1012    Return false if the edge already existed, true otherwise.  */
1013
1014 static void
1015 add_pred_graph_edge (constraint_graph_t graph, unsigned int to,
1016                      unsigned int from)
1017 {
1018   if (!graph->preds[to])
1019     graph->preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1020   bitmap_set_bit (graph->preds[to], from);
1021 }
1022
1023 /* Add a graph edge to GRAPH, going from FROM to TO if
1024    it doesn't exist in the graph already.
1025    Return false if the edge already existed, true otherwise.  */
1026
1027 static bool
1028 add_graph_edge (constraint_graph_t graph, unsigned int to,
1029                 unsigned int from)
1030 {
1031   if (to == from)
1032     {
1033       return false;
1034     }
1035   else
1036     {
1037       bool r = false;
1038
1039       if (!graph->succs[from])
1040         graph->succs[from] = BITMAP_ALLOC (&pta_obstack);
1041       if (bitmap_set_bit (graph->succs[from], to))
1042         {
1043           r = true;
1044           if (to < FIRST_REF_NODE && from < FIRST_REF_NODE)
1045             stats.num_edges++;
1046         }
1047       return r;
1048     }
1049 }
1050
1051
1052 /* Return true if {DEST.SRC} is an existing graph edge in GRAPH.  */
1053
1054 static bool
1055 valid_graph_edge (constraint_graph_t graph, unsigned int src,
1056                   unsigned int dest)
1057 {
1058   return (graph->succs[dest]
1059           && bitmap_bit_p (graph->succs[dest], src));
1060 }
1061
1062 /* Initialize the constraint graph structure to contain SIZE nodes.  */
1063
1064 static void
1065 init_graph (unsigned int size)
1066 {
1067   unsigned int j;
1068
1069   graph = XCNEW (struct constraint_graph);
1070   graph->size = size;
1071   graph->succs = XCNEWVEC (bitmap, graph->size);
1072   graph->indirect_cycles = XNEWVEC (int, graph->size);
1073   graph->rep = XNEWVEC (unsigned int, graph->size);
1074   graph->complex = XCNEWVEC (VEC(constraint_t, heap) *, size);
1075   graph->pe = XCNEWVEC (unsigned int, graph->size);
1076   graph->pe_rep = XNEWVEC (int, graph->size);
1077
1078   for (j = 0; j < graph->size; j++)
1079     {
1080       graph->rep[j] = j;
1081       graph->pe_rep[j] = -1;
1082       graph->indirect_cycles[j] = -1;
1083     }
1084 }
1085
1086 /* Build the constraint graph, adding only predecessor edges right now.  */
1087
1088 static void
1089 build_pred_graph (void)
1090 {
1091   int i;
1092   constraint_t c;
1093   unsigned int j;
1094
1095   graph->implicit_preds = XCNEWVEC (bitmap, graph->size);
1096   graph->preds = XCNEWVEC (bitmap, graph->size);
1097   graph->pointer_label = XCNEWVEC (unsigned int, graph->size);
1098   graph->loc_label = XCNEWVEC (unsigned int, graph->size);
1099   graph->pointed_by = XCNEWVEC (bitmap, graph->size);
1100   graph->points_to = XCNEWVEC (bitmap, graph->size);
1101   graph->eq_rep = XNEWVEC (int, graph->size);
1102   graph->direct_nodes = sbitmap_alloc (graph->size);
1103   graph->address_taken = BITMAP_ALLOC (&predbitmap_obstack);
1104   sbitmap_zero (graph->direct_nodes);
1105
1106   for (j = 0; j < FIRST_REF_NODE; j++)
1107     {
1108       if (!get_varinfo (j)->is_special_var)
1109         SET_BIT (graph->direct_nodes, j);
1110     }
1111
1112   for (j = 0; j < graph->size; j++)
1113     graph->eq_rep[j] = -1;
1114
1115   for (j = 0; j < VEC_length (varinfo_t, varmap); j++)
1116     graph->indirect_cycles[j] = -1;
1117
1118   for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
1119     {
1120       struct constraint_expr lhs = c->lhs;
1121       struct constraint_expr rhs = c->rhs;
1122       unsigned int lhsvar = get_varinfo_fc (lhs.var)->id;
1123       unsigned int rhsvar = get_varinfo_fc (rhs.var)->id;
1124
1125       if (lhs.type == DEREF)
1126         {
1127           /* *x = y.  */
1128           if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1129             add_pred_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1130         }
1131       else if (rhs.type == DEREF)
1132         {
1133           /* x = *y */
1134           if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1135             add_pred_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1136           else
1137             RESET_BIT (graph->direct_nodes, lhsvar);
1138         }
1139       else if (rhs.type == ADDRESSOF)
1140         {
1141           varinfo_t v;
1142
1143           /* x = &y */
1144           if (graph->points_to[lhsvar] == NULL)
1145             graph->points_to[lhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1146           bitmap_set_bit (graph->points_to[lhsvar], rhsvar);
1147
1148           if (graph->pointed_by[rhsvar] == NULL)
1149             graph->pointed_by[rhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1150           bitmap_set_bit (graph->pointed_by[rhsvar], lhsvar);
1151
1152           /* Implicitly, *x = y */
1153           add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1154
1155           /* All related variables are no longer direct nodes.  */
1156           RESET_BIT (graph->direct_nodes, rhsvar);
1157           v = get_varinfo (rhsvar);
1158           if (!v->is_full_var)
1159             {
1160               v = lookup_vi_for_tree (v->decl);
1161               do
1162                 {
1163                   RESET_BIT (graph->direct_nodes, v->id);
1164                   v = v->next;
1165                 }
1166               while (v != NULL);
1167             }
1168           bitmap_set_bit (graph->address_taken, rhsvar);
1169         }
1170       else if (lhsvar > anything_id
1171                && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1172         {
1173           /* x = y */
1174           add_pred_graph_edge (graph, lhsvar, rhsvar);
1175           /* Implicitly, *x = *y */
1176           add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar,
1177                                    FIRST_REF_NODE + rhsvar);
1178         }
1179       else if (lhs.offset != 0 || rhs.offset != 0)
1180         {
1181           if (rhs.offset != 0)
1182             RESET_BIT (graph->direct_nodes, lhs.var);
1183           else if (lhs.offset != 0)
1184             RESET_BIT (graph->direct_nodes, rhs.var);
1185         }
1186     }
1187 }
1188
1189 /* Build the constraint graph, adding successor edges.  */
1190
1191 static void
1192 build_succ_graph (void)
1193 {
1194   unsigned i, t;
1195   constraint_t c;
1196
1197   for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
1198     {
1199       struct constraint_expr lhs;
1200       struct constraint_expr rhs;
1201       unsigned int lhsvar;
1202       unsigned int rhsvar;
1203
1204       if (!c)
1205         continue;
1206
1207       lhs = c->lhs;
1208       rhs = c->rhs;
1209       lhsvar = find (get_varinfo_fc (lhs.var)->id);
1210       rhsvar = find (get_varinfo_fc (rhs.var)->id);
1211
1212       if (lhs.type == DEREF)
1213         {
1214           if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1215             add_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1216         }
1217       else if (rhs.type == DEREF)
1218         {
1219           if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1220             add_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1221         }
1222       else if (rhs.type == ADDRESSOF)
1223         {
1224           /* x = &y */
1225           gcc_assert (find (get_varinfo_fc (rhs.var)->id)
1226                       == get_varinfo_fc (rhs.var)->id);
1227           bitmap_set_bit (get_varinfo (lhsvar)->solution, rhsvar);
1228         }
1229       else if (lhsvar > anything_id
1230                && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1231         {
1232           add_graph_edge (graph, lhsvar, rhsvar);
1233         }
1234     }
1235
1236   /* Add edges from STOREDANYTHING to all non-direct nodes.  */
1237   t = find (storedanything_id);
1238   for (i = integer_id + 1; i < FIRST_REF_NODE; ++i)
1239     {
1240       if (!TEST_BIT (graph->direct_nodes, i))
1241         add_graph_edge (graph, find (i), t);
1242     }
1243 }
1244
1245
1246 /* Changed variables on the last iteration.  */
1247 static unsigned int changed_count;
1248 static sbitmap changed;
1249
1250 DEF_VEC_I(unsigned);
1251 DEF_VEC_ALLOC_I(unsigned,heap);
1252
1253
1254 /* Strongly Connected Component visitation info.  */
1255
1256 struct scc_info
1257 {
1258   sbitmap visited;
1259   sbitmap deleted;
1260   unsigned int *dfs;
1261   unsigned int *node_mapping;
1262   int current_index;
1263   VEC(unsigned,heap) *scc_stack;
1264 };
1265
1266
1267 /* Recursive routine to find strongly connected components in GRAPH.
1268    SI is the SCC info to store the information in, and N is the id of current
1269    graph node we are processing.
1270
1271    This is Tarjan's strongly connected component finding algorithm, as
1272    modified by Nuutila to keep only non-root nodes on the stack.
1273    The algorithm can be found in "On finding the strongly connected
1274    connected components in a directed graph" by Esko Nuutila and Eljas
1275    Soisalon-Soininen, in Information Processing Letters volume 49,
1276    number 1, pages 9-14.  */
1277
1278 static void
1279 scc_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1280 {
1281   unsigned int i;
1282   bitmap_iterator bi;
1283   unsigned int my_dfs;
1284
1285   SET_BIT (si->visited, n);
1286   si->dfs[n] = si->current_index ++;
1287   my_dfs = si->dfs[n];
1288
1289   /* Visit all the successors.  */
1290   EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[n], 0, i, bi)
1291     {
1292       unsigned int w;
1293
1294       if (i > LAST_REF_NODE)
1295         break;
1296
1297       w = find (i);
1298       if (TEST_BIT (si->deleted, w))
1299         continue;
1300
1301       if (!TEST_BIT (si->visited, w))
1302         scc_visit (graph, si, w);
1303       {
1304         unsigned int t = find (w);
1305         unsigned int nnode = find (n);
1306         gcc_assert (nnode == n);
1307
1308         if (si->dfs[t] < si->dfs[nnode])
1309           si->dfs[n] = si->dfs[t];
1310       }
1311     }
1312
1313   /* See if any components have been identified.  */
1314   if (si->dfs[n] == my_dfs)
1315     {
1316       if (VEC_length (unsigned, si->scc_stack) > 0
1317           && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
1318         {
1319           bitmap scc = BITMAP_ALLOC (NULL);
1320           bool have_ref_node = n >= FIRST_REF_NODE;
1321           unsigned int lowest_node;
1322           bitmap_iterator bi;
1323
1324           bitmap_set_bit (scc, n);
1325
1326           while (VEC_length (unsigned, si->scc_stack) != 0
1327                  && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
1328             {
1329               unsigned int w = VEC_pop (unsigned, si->scc_stack);
1330
1331               bitmap_set_bit (scc, w);
1332               if (w >= FIRST_REF_NODE)
1333                 have_ref_node = true;
1334             }
1335
1336           lowest_node = bitmap_first_set_bit (scc);
1337           gcc_assert (lowest_node < FIRST_REF_NODE);
1338
1339           /* Collapse the SCC nodes into a single node, and mark the
1340              indirect cycles.  */
1341           EXECUTE_IF_SET_IN_BITMAP (scc, 0, i, bi)
1342             {
1343               if (i < FIRST_REF_NODE)
1344                 {
1345                   if (unite (lowest_node, i))
1346                     unify_nodes (graph, lowest_node, i, false);
1347                 }
1348               else
1349                 {
1350                   unite (lowest_node, i);
1351                   graph->indirect_cycles[i - FIRST_REF_NODE] = lowest_node;
1352                 }
1353             }
1354         }
1355       SET_BIT (si->deleted, n);
1356     }
1357   else
1358     VEC_safe_push (unsigned, heap, si->scc_stack, n);
1359 }
1360
1361 /* Unify node FROM into node TO, updating the changed count if
1362    necessary when UPDATE_CHANGED is true.  */
1363
1364 static void
1365 unify_nodes (constraint_graph_t graph, unsigned int to, unsigned int from,
1366              bool update_changed)
1367 {
1368
1369   gcc_assert (to != from && find (to) == to);
1370   if (dump_file && (dump_flags & TDF_DETAILS))
1371     fprintf (dump_file, "Unifying %s to %s\n",
1372              get_varinfo (from)->name,
1373              get_varinfo (to)->name);
1374
1375   if (update_changed)
1376     stats.unified_vars_dynamic++;
1377   else
1378     stats.unified_vars_static++;
1379
1380   merge_graph_nodes (graph, to, from);
1381   merge_node_constraints (graph, to, from);
1382
1383   if (get_varinfo (from)->no_tbaa_pruning)
1384     get_varinfo (to)->no_tbaa_pruning = true;
1385
1386   /* Mark TO as changed if FROM was changed. If TO was already marked
1387      as changed, decrease the changed count.  */
1388
1389   if (update_changed && TEST_BIT (changed, from))
1390     {
1391       RESET_BIT (changed, from);
1392       if (!TEST_BIT (changed, to))
1393         SET_BIT (changed, to);
1394       else
1395         {
1396           gcc_assert (changed_count > 0);
1397           changed_count--;
1398         }
1399     }
1400   if (get_varinfo (from)->solution)
1401     {
1402       /* If the solution changes because of the merging, we need to mark
1403          the variable as changed.  */
1404       if (bitmap_ior_into (get_varinfo (to)->solution,
1405                            get_varinfo (from)->solution))
1406         {
1407           if (update_changed && !TEST_BIT (changed, to))
1408             {
1409               SET_BIT (changed, to);
1410               changed_count++;
1411             }
1412         }
1413       
1414       BITMAP_FREE (get_varinfo (from)->solution);
1415       BITMAP_FREE (get_varinfo (from)->oldsolution);
1416       
1417       if (stats.iterations > 0)
1418         {
1419           BITMAP_FREE (get_varinfo (to)->oldsolution);
1420           get_varinfo (to)->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
1421         }
1422     }
1423   if (valid_graph_edge (graph, to, to))
1424     {
1425       if (graph->succs[to])
1426         bitmap_clear_bit (graph->succs[to], to);
1427     }
1428 }
1429
1430 /* Information needed to compute the topological ordering of a graph.  */
1431
1432 struct topo_info
1433 {
1434   /* sbitmap of visited nodes.  */
1435   sbitmap visited;
1436   /* Array that stores the topological order of the graph, *in
1437      reverse*.  */
1438   VEC(unsigned,heap) *topo_order;
1439 };
1440
1441
1442 /* Initialize and return a topological info structure.  */
1443
1444 static struct topo_info *
1445 init_topo_info (void)
1446 {
1447   size_t size = graph->size;
1448   struct topo_info *ti = XNEW (struct topo_info);
1449   ti->visited = sbitmap_alloc (size);
1450   sbitmap_zero (ti->visited);
1451   ti->topo_order = VEC_alloc (unsigned, heap, 1);
1452   return ti;
1453 }
1454
1455
1456 /* Free the topological sort info pointed to by TI.  */
1457
1458 static void
1459 free_topo_info (struct topo_info *ti)
1460 {
1461   sbitmap_free (ti->visited);
1462   VEC_free (unsigned, heap, ti->topo_order);
1463   free (ti);
1464 }
1465
1466 /* Visit the graph in topological order, and store the order in the
1467    topo_info structure.  */
1468
1469 static void
1470 topo_visit (constraint_graph_t graph, struct topo_info *ti,
1471             unsigned int n)
1472 {
1473   bitmap_iterator bi;
1474   unsigned int j;
1475
1476   SET_BIT (ti->visited, n);
1477
1478   if (graph->succs[n])
1479     EXECUTE_IF_SET_IN_BITMAP (graph->succs[n], 0, j, bi)
1480       {
1481         if (!TEST_BIT (ti->visited, j))
1482           topo_visit (graph, ti, j);
1483       }
1484
1485   VEC_safe_push (unsigned, heap, ti->topo_order, n);
1486 }
1487
1488 /* Return true if variable N + OFFSET is a legal field of N.  */
1489
1490 static bool
1491 type_safe (unsigned int n, unsigned HOST_WIDE_INT *offset)
1492 {
1493   varinfo_t ninfo = get_varinfo (n);
1494
1495   /* For things we've globbed to single variables, any offset into the
1496      variable acts like the entire variable, so that it becomes offset
1497      0.  */
1498   if (ninfo->is_special_var
1499       || ninfo->is_artificial_var
1500       || ninfo->is_unknown_size_var
1501       || ninfo->is_full_var)
1502     {
1503       *offset = 0;
1504       return true;
1505     }
1506   return (get_varinfo (n)->offset + *offset) < get_varinfo (n)->fullsize;
1507 }
1508
1509 /* Process a constraint C that represents x = *y, using DELTA as the
1510    starting solution.  */
1511
1512 static void
1513 do_sd_constraint (constraint_graph_t graph, constraint_t c,
1514                   bitmap delta)
1515 {
1516   unsigned int lhs = c->lhs.var;
1517   bool flag = false;
1518   bitmap sol = get_varinfo (lhs)->solution;
1519   unsigned int j;
1520   bitmap_iterator bi;
1521
1522   /* For x = *ESCAPED and x = *CALLUSED we want to compute the
1523      reachability set of the rhs var.  As a pointer to a sub-field
1524      of a variable can also reach all other fields of the variable
1525      we simply have to expand the solution to contain all sub-fields
1526      if one sub-field is contained.  */
1527   if (c->rhs.var == find (escaped_id)
1528       || c->rhs.var == find (callused_id))
1529     {
1530       bitmap vars = NULL;
1531       /* In a first pass record all variables we need to add all
1532          sub-fields off.  This avoids quadratic behavior.  */
1533       EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1534         {
1535           varinfo_t v = get_varinfo (j);
1536           if (v->is_full_var)
1537             continue;
1538
1539           v = lookup_vi_for_tree (v->decl);
1540           if (v->next != NULL)
1541             {
1542               if (vars == NULL)
1543                 vars = BITMAP_ALLOC (NULL);
1544               bitmap_set_bit (vars, v->id);
1545             }
1546         }
1547       /* In the second pass now do the addition to the solution and
1548          to speed up solving add it to the delta as well.  */
1549       if (vars != NULL)
1550         {
1551           EXECUTE_IF_SET_IN_BITMAP (vars, 0, j, bi)
1552             {
1553               varinfo_t v = get_varinfo (j);
1554               for (; v != NULL; v = v->next)
1555                 {
1556                   if (bitmap_set_bit (sol, v->id))
1557                     {
1558                       flag = true;
1559                       bitmap_set_bit (delta, v->id);
1560                     }
1561                 }
1562             }
1563           BITMAP_FREE (vars);
1564         }
1565     }
1566
1567   if (bitmap_bit_p (delta, anything_id))
1568     {
1569       flag |= bitmap_set_bit (sol, anything_id);
1570       goto done;
1571     }
1572
1573   /* For each variable j in delta (Sol(y)), add
1574      an edge in the graph from j to x, and union Sol(j) into Sol(x).  */
1575   EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1576     {
1577       unsigned HOST_WIDE_INT roffset = c->rhs.offset;
1578       if (type_safe (j, &roffset))
1579         {
1580           varinfo_t v;
1581           unsigned HOST_WIDE_INT fieldoffset = get_varinfo (j)->offset + roffset;
1582           unsigned int t;
1583
1584           v = first_vi_for_offset (get_varinfo (j), fieldoffset);
1585           /* If the access is outside of the variable we can ignore it.  */
1586           if (!v)
1587             continue;
1588           t = find (v->id);
1589
1590           /* Adding edges from the special vars is pointless.
1591              They don't have sets that can change.  */
1592           if (get_varinfo (t)->is_special_var)
1593             flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1594           /* Merging the solution from ESCAPED needlessly increases
1595              the set.  Use ESCAPED as representative instead.  */
1596           else if (get_varinfo (t)->id == find (escaped_id))
1597             flag |= bitmap_set_bit (sol, escaped_id);
1598           else if (add_graph_edge (graph, lhs, t))
1599             flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1600         }
1601     }
1602
1603 done:
1604   /* If the LHS solution changed, mark the var as changed.  */
1605   if (flag)
1606     {
1607       get_varinfo (lhs)->solution = sol;
1608       if (!TEST_BIT (changed, lhs))
1609         {
1610           SET_BIT (changed, lhs);
1611           changed_count++;
1612         }
1613     }
1614 }
1615
1616 /* Process a constraint C that represents *x = y.  */
1617
1618 static void
1619 do_ds_constraint (constraint_t c, bitmap delta)
1620 {
1621   unsigned int rhs = c->rhs.var;
1622   bitmap sol = get_varinfo (rhs)->solution;
1623   unsigned int j;
1624   bitmap_iterator bi;
1625
1626   /* Our IL does not allow this.  */
1627   gcc_assert (c->rhs.offset == 0);
1628
1629   /* If the solution of y contains ANYTHING simply use the ANYTHING
1630      solution.  This avoids needlessly increasing the points-to sets.  */
1631   if (bitmap_bit_p (sol, anything_id))
1632     sol = get_varinfo (find (anything_id))->solution;
1633
1634   /* If the solution for x contains ANYTHING we have to merge the
1635      solution of y into all pointer variables which we do via
1636      STOREDANYTHING.  */
1637   if (bitmap_bit_p (delta, anything_id))
1638     {
1639       unsigned t = find (storedanything_id);
1640       if (add_graph_edge (graph, t, rhs))
1641         {
1642           if (bitmap_ior_into (get_varinfo (t)->solution, sol))
1643             {
1644               if (!TEST_BIT (changed, t))
1645                 {
1646                   SET_BIT (changed, t);
1647                   changed_count++;
1648                 }
1649             }
1650         }
1651       return;
1652     }
1653
1654   /* For each member j of delta (Sol(x)), add an edge from y to j and
1655      union Sol(y) into Sol(j) */
1656   EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1657     {
1658       unsigned HOST_WIDE_INT loff = c->lhs.offset;
1659       if (type_safe (j, &loff) && !(get_varinfo (j)->is_special_var))
1660         {
1661           varinfo_t v;
1662           unsigned int t;
1663           unsigned HOST_WIDE_INT fieldoffset = get_varinfo (j)->offset + loff;
1664
1665           v = first_vi_for_offset (get_varinfo (j), fieldoffset);
1666           /* If the access is outside of the variable we can ignore it.  */
1667           if (!v)
1668             continue;
1669
1670           if (v->may_have_pointers)
1671             {
1672               t = find (v->id);
1673               if (add_graph_edge (graph, t, rhs))
1674                 {
1675                   if (bitmap_ior_into (get_varinfo (t)->solution, sol))
1676                     {
1677                       if (t == rhs)
1678                         sol = get_varinfo (rhs)->solution;
1679                       if (!TEST_BIT (changed, t))
1680                         {
1681                           SET_BIT (changed, t);
1682                           changed_count++;
1683                         }
1684                     }
1685                 }
1686             }
1687         }
1688     }
1689 }
1690
1691 /* Handle a non-simple (simple meaning requires no iteration),
1692    constraint (IE *x = &y, x = *y, *x = y, and x = y with offsets involved).  */
1693
1694 static void
1695 do_complex_constraint (constraint_graph_t graph, constraint_t c, bitmap delta)
1696 {
1697   if (c->lhs.type == DEREF)
1698     {
1699       if (c->rhs.type == ADDRESSOF)
1700         {
1701           gcc_unreachable();
1702         }
1703       else
1704         {
1705           /* *x = y */
1706           do_ds_constraint (c, delta);
1707         }
1708     }
1709   else if (c->rhs.type == DEREF)
1710     {
1711       /* x = *y */
1712       if (!(get_varinfo (c->lhs.var)->is_special_var))
1713         do_sd_constraint (graph, c, delta);
1714     }
1715   else
1716     {
1717       bitmap tmp;
1718       bitmap solution;
1719       bool flag = false;
1720
1721       gcc_assert (c->rhs.type == SCALAR && c->lhs.type == SCALAR);
1722       solution = get_varinfo (c->rhs.var)->solution;
1723       tmp = get_varinfo (c->lhs.var)->solution;
1724
1725       flag = set_union_with_increment (tmp, solution, c->rhs.offset);
1726
1727       if (flag)
1728         {
1729           get_varinfo (c->lhs.var)->solution = tmp;
1730           if (!TEST_BIT (changed, c->lhs.var))
1731             {
1732               SET_BIT (changed, c->lhs.var);
1733               changed_count++;
1734             }
1735         }
1736     }
1737 }
1738
1739 /* Initialize and return a new SCC info structure.  */
1740
1741 static struct scc_info *
1742 init_scc_info (size_t size)
1743 {
1744   struct scc_info *si = XNEW (struct scc_info);
1745   size_t i;
1746
1747   si->current_index = 0;
1748   si->visited = sbitmap_alloc (size);
1749   sbitmap_zero (si->visited);
1750   si->deleted = sbitmap_alloc (size);
1751   sbitmap_zero (si->deleted);
1752   si->node_mapping = XNEWVEC (unsigned int, size);
1753   si->dfs = XCNEWVEC (unsigned int, size);
1754
1755   for (i = 0; i < size; i++)
1756     si->node_mapping[i] = i;
1757
1758   si->scc_stack = VEC_alloc (unsigned, heap, 1);
1759   return si;
1760 }
1761
1762 /* Free an SCC info structure pointed to by SI */
1763
1764 static void
1765 free_scc_info (struct scc_info *si)
1766 {
1767   sbitmap_free (si->visited);
1768   sbitmap_free (si->deleted);
1769   free (si->node_mapping);
1770   free (si->dfs);
1771   VEC_free (unsigned, heap, si->scc_stack);
1772   free (si);
1773 }
1774
1775
1776 /* Find indirect cycles in GRAPH that occur, using strongly connected
1777    components, and note them in the indirect cycles map.
1778
1779    This technique comes from Ben Hardekopf and Calvin Lin,
1780    "It Pays to be Lazy: Fast and Accurate Pointer Analysis for Millions of
1781    Lines of Code", submitted to PLDI 2007.  */
1782
1783 static void
1784 find_indirect_cycles (constraint_graph_t graph)
1785 {
1786   unsigned int i;
1787   unsigned int size = graph->size;
1788   struct scc_info *si = init_scc_info (size);
1789
1790   for (i = 0; i < MIN (LAST_REF_NODE, size); i ++ )
1791     if (!TEST_BIT (si->visited, i) && find (i) == i)
1792       scc_visit (graph, si, i);
1793
1794   free_scc_info (si);
1795 }
1796
1797 /* Compute a topological ordering for GRAPH, and store the result in the
1798    topo_info structure TI.  */
1799
1800 static void
1801 compute_topo_order (constraint_graph_t graph,
1802                     struct topo_info *ti)
1803 {
1804   unsigned int i;
1805   unsigned int size = graph->size;
1806
1807   for (i = 0; i != size; ++i)
1808     if (!TEST_BIT (ti->visited, i) && find (i) == i)
1809       topo_visit (graph, ti, i);
1810 }
1811
1812 /* Structure used to for hash value numbering of pointer equivalence
1813    classes.  */
1814
1815 typedef struct equiv_class_label
1816 {
1817   hashval_t hashcode;
1818   unsigned int equivalence_class;
1819   bitmap labels;
1820 } *equiv_class_label_t;
1821 typedef const struct equiv_class_label *const_equiv_class_label_t;
1822
1823 /* A hashtable for mapping a bitmap of labels->pointer equivalence
1824    classes.  */
1825 static htab_t pointer_equiv_class_table;
1826
1827 /* A hashtable for mapping a bitmap of labels->location equivalence
1828    classes.  */
1829 static htab_t location_equiv_class_table;
1830
1831 /* Hash function for a equiv_class_label_t */
1832
1833 static hashval_t
1834 equiv_class_label_hash (const void *p)
1835 {
1836   const_equiv_class_label_t const ecl = (const_equiv_class_label_t) p;
1837   return ecl->hashcode;
1838 }
1839
1840 /* Equality function for two equiv_class_label_t's.  */
1841
1842 static int
1843 equiv_class_label_eq (const void *p1, const void *p2)
1844 {
1845   const_equiv_class_label_t const eql1 = (const_equiv_class_label_t) p1;
1846   const_equiv_class_label_t const eql2 = (const_equiv_class_label_t) p2;
1847   return bitmap_equal_p (eql1->labels, eql2->labels);
1848 }
1849
1850 /* Lookup a equivalence class in TABLE by the bitmap of LABELS it
1851    contains.  */
1852
1853 static unsigned int
1854 equiv_class_lookup (htab_t table, bitmap labels)
1855 {
1856   void **slot;
1857   struct equiv_class_label ecl;
1858
1859   ecl.labels = labels;
1860   ecl.hashcode = bitmap_hash (labels);
1861
1862   slot = htab_find_slot_with_hash (table, &ecl,
1863                                    ecl.hashcode, NO_INSERT);
1864   if (!slot)
1865     return 0;
1866   else
1867     return ((equiv_class_label_t) *slot)->equivalence_class;
1868 }
1869
1870
1871 /* Add an equivalence class named EQUIVALENCE_CLASS with labels LABELS
1872    to TABLE.  */
1873
1874 static void
1875 equiv_class_add (htab_t table, unsigned int equivalence_class,
1876                  bitmap labels)
1877 {
1878   void **slot;
1879   equiv_class_label_t ecl = XNEW (struct equiv_class_label);
1880
1881   ecl->labels = labels;
1882   ecl->equivalence_class = equivalence_class;
1883   ecl->hashcode = bitmap_hash (labels);
1884
1885   slot = htab_find_slot_with_hash (table, ecl,
1886                                    ecl->hashcode, INSERT);
1887   gcc_assert (!*slot);
1888   *slot = (void *) ecl;
1889 }
1890
1891 /* Perform offline variable substitution.
1892
1893    This is a worst case quadratic time way of identifying variables
1894    that must have equivalent points-to sets, including those caused by
1895    static cycles, and single entry subgraphs, in the constraint graph.
1896
1897    The technique is described in "Exploiting Pointer and Location
1898    Equivalence to Optimize Pointer Analysis. In the 14th International
1899    Static Analysis Symposium (SAS), August 2007."  It is known as the
1900    "HU" algorithm, and is equivalent to value numbering the collapsed
1901    constraint graph including evaluating unions.
1902
1903    The general method of finding equivalence classes is as follows:
1904    Add fake nodes (REF nodes) and edges for *a = b and a = *b constraints.
1905    Initialize all non-REF nodes to be direct nodes.
1906    For each constraint a = a U {b}, we set pts(a) = pts(a) u {fresh
1907    variable}
1908    For each constraint containing the dereference, we also do the same
1909    thing.
1910
1911    We then compute SCC's in the graph and unify nodes in the same SCC,
1912    including pts sets.
1913
1914    For each non-collapsed node x:
1915     Visit all unvisited explicit incoming edges.
1916     Ignoring all non-pointers, set pts(x) = Union of pts(a) for y
1917     where y->x.
1918     Lookup the equivalence class for pts(x).
1919      If we found one, equivalence_class(x) = found class.
1920      Otherwise, equivalence_class(x) = new class, and new_class is
1921     added to the lookup table.
1922
1923    All direct nodes with the same equivalence class can be replaced
1924    with a single representative node.
1925    All unlabeled nodes (label == 0) are not pointers and all edges
1926    involving them can be eliminated.
1927    We perform these optimizations during rewrite_constraints
1928
1929    In addition to pointer equivalence class finding, we also perform
1930    location equivalence class finding.  This is the set of variables
1931    that always appear together in points-to sets.  We use this to
1932    compress the size of the points-to sets.  */
1933
1934 /* Current maximum pointer equivalence class id.  */
1935 static int pointer_equiv_class;
1936
1937 /* Current maximum location equivalence class id.  */
1938 static int location_equiv_class;
1939
1940 /* Recursive routine to find strongly connected components in GRAPH,
1941    and label it's nodes with DFS numbers.  */
1942
1943 static void
1944 condense_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1945 {
1946   unsigned int i;
1947   bitmap_iterator bi;
1948   unsigned int my_dfs;
1949
1950   gcc_assert (si->node_mapping[n] == n);
1951   SET_BIT (si->visited, n);
1952   si->dfs[n] = si->current_index ++;
1953   my_dfs = si->dfs[n];
1954
1955   /* Visit all the successors.  */
1956   EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
1957     {
1958       unsigned int w = si->node_mapping[i];
1959
1960       if (TEST_BIT (si->deleted, w))
1961         continue;
1962
1963       if (!TEST_BIT (si->visited, w))
1964         condense_visit (graph, si, w);
1965       {
1966         unsigned int t = si->node_mapping[w];
1967         unsigned int nnode = si->node_mapping[n];
1968         gcc_assert (nnode == n);
1969
1970         if (si->dfs[t] < si->dfs[nnode])
1971           si->dfs[n] = si->dfs[t];
1972       }
1973     }
1974
1975   /* Visit all the implicit predecessors.  */
1976   EXECUTE_IF_IN_NONNULL_BITMAP (graph->implicit_preds[n], 0, i, bi)
1977     {
1978       unsigned int w = si->node_mapping[i];
1979
1980       if (TEST_BIT (si->deleted, w))
1981         continue;
1982
1983       if (!TEST_BIT (si->visited, w))
1984         condense_visit (graph, si, w);
1985       {
1986         unsigned int t = si->node_mapping[w];
1987         unsigned int nnode = si->node_mapping[n];
1988         gcc_assert (nnode == n);
1989
1990         if (si->dfs[t] < si->dfs[nnode])
1991           si->dfs[n] = si->dfs[t];
1992       }
1993     }
1994
1995   /* See if any components have been identified.  */
1996   if (si->dfs[n] == my_dfs)
1997     {
1998       while (VEC_length (unsigned, si->scc_stack) != 0
1999              && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
2000         {
2001           unsigned int w = VEC_pop (unsigned, si->scc_stack);
2002           si->node_mapping[w] = n;
2003
2004           if (!TEST_BIT (graph->direct_nodes, w))
2005             RESET_BIT (graph->direct_nodes, n);
2006
2007           /* Unify our nodes.  */
2008           if (graph->preds[w])
2009             {
2010               if (!graph->preds[n])
2011                 graph->preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2012               bitmap_ior_into (graph->preds[n], graph->preds[w]);
2013             }
2014           if (graph->implicit_preds[w])
2015             {
2016               if (!graph->implicit_preds[n])
2017                 graph->implicit_preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2018               bitmap_ior_into (graph->implicit_preds[n],
2019                                graph->implicit_preds[w]);
2020             }
2021           if (graph->points_to[w])
2022             {
2023               if (!graph->points_to[n])
2024                 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2025               bitmap_ior_into (graph->points_to[n],
2026                                graph->points_to[w]);
2027             }
2028         }
2029       SET_BIT (si->deleted, n);
2030     }
2031   else
2032     VEC_safe_push (unsigned, heap, si->scc_stack, n);
2033 }
2034
2035 /* Label pointer equivalences.  */
2036
2037 static void
2038 label_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
2039 {
2040   unsigned int i;
2041   bitmap_iterator bi;
2042   SET_BIT (si->visited, n);
2043
2044   if (!graph->points_to[n])
2045     graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2046
2047   /* Label and union our incoming edges's points to sets.  */
2048   EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
2049     {
2050       unsigned int w = si->node_mapping[i];
2051       if (!TEST_BIT (si->visited, w))
2052         label_visit (graph, si, w);
2053
2054       /* Skip unused edges  */
2055       if (w == n || graph->pointer_label[w] == 0)
2056         continue;
2057
2058       if (graph->points_to[w])
2059         bitmap_ior_into(graph->points_to[n], graph->points_to[w]);
2060     }
2061   /* Indirect nodes get fresh variables.  */
2062   if (!TEST_BIT (graph->direct_nodes, n))
2063     bitmap_set_bit (graph->points_to[n], FIRST_REF_NODE + n);
2064
2065   if (!bitmap_empty_p (graph->points_to[n]))
2066     {
2067       unsigned int label = equiv_class_lookup (pointer_equiv_class_table,
2068                                                graph->points_to[n]);
2069       if (!label)
2070         {
2071           label = pointer_equiv_class++;
2072           equiv_class_add (pointer_equiv_class_table,
2073                            label, graph->points_to[n]);
2074         }
2075       graph->pointer_label[n] = label;
2076     }
2077 }
2078
2079 /* Perform offline variable substitution, discovering equivalence
2080    classes, and eliminating non-pointer variables.  */
2081
2082 static struct scc_info *
2083 perform_var_substitution (constraint_graph_t graph)
2084 {
2085   unsigned int i;
2086   unsigned int size = graph->size;
2087   struct scc_info *si = init_scc_info (size);
2088
2089   bitmap_obstack_initialize (&iteration_obstack);
2090   pointer_equiv_class_table = htab_create (511, equiv_class_label_hash,
2091                                            equiv_class_label_eq, free);
2092   location_equiv_class_table = htab_create (511, equiv_class_label_hash,
2093                                             equiv_class_label_eq, free);
2094   pointer_equiv_class = 1;
2095   location_equiv_class = 1;
2096
2097   /* Condense the nodes, which means to find SCC's, count incoming
2098      predecessors, and unite nodes in SCC's.  */
2099   for (i = 0; i < FIRST_REF_NODE; i++)
2100     if (!TEST_BIT (si->visited, si->node_mapping[i]))
2101       condense_visit (graph, si, si->node_mapping[i]);
2102
2103   sbitmap_zero (si->visited);
2104   /* Actually the label the nodes for pointer equivalences  */
2105   for (i = 0; i < FIRST_REF_NODE; i++)
2106     if (!TEST_BIT (si->visited, si->node_mapping[i]))
2107       label_visit (graph, si, si->node_mapping[i]);
2108
2109   /* Calculate location equivalence labels.  */
2110   for (i = 0; i < FIRST_REF_NODE; i++)
2111     {
2112       bitmap pointed_by;
2113       bitmap_iterator bi;
2114       unsigned int j;
2115       unsigned int label;
2116
2117       if (!graph->pointed_by[i])
2118         continue;
2119       pointed_by = BITMAP_ALLOC (&iteration_obstack);
2120
2121       /* Translate the pointed-by mapping for pointer equivalence
2122          labels.  */
2123       EXECUTE_IF_SET_IN_BITMAP (graph->pointed_by[i], 0, j, bi)
2124         {
2125           bitmap_set_bit (pointed_by,
2126                           graph->pointer_label[si->node_mapping[j]]);
2127         }
2128       /* The original pointed_by is now dead.  */
2129       BITMAP_FREE (graph->pointed_by[i]);
2130
2131       /* Look up the location equivalence label if one exists, or make
2132          one otherwise.  */
2133       label = equiv_class_lookup (location_equiv_class_table,
2134                                   pointed_by);
2135       if (label == 0)
2136         {
2137           label = location_equiv_class++;
2138           equiv_class_add (location_equiv_class_table,
2139                            label, pointed_by);
2140         }
2141       else
2142         {
2143           if (dump_file && (dump_flags & TDF_DETAILS))
2144             fprintf (dump_file, "Found location equivalence for node %s\n",
2145                      get_varinfo (i)->name);
2146           BITMAP_FREE (pointed_by);
2147         }
2148       graph->loc_label[i] = label;
2149
2150     }
2151
2152   if (dump_file && (dump_flags & TDF_DETAILS))
2153     for (i = 0; i < FIRST_REF_NODE; i++)
2154       {
2155         bool direct_node = TEST_BIT (graph->direct_nodes, i);
2156         fprintf (dump_file,
2157                  "Equivalence classes for %s node id %d:%s are pointer: %d"
2158                  ", location:%d\n",
2159                  direct_node ? "Direct node" : "Indirect node", i,
2160                  get_varinfo (i)->name,
2161                  graph->pointer_label[si->node_mapping[i]],
2162                  graph->loc_label[si->node_mapping[i]]);
2163       }
2164
2165   /* Quickly eliminate our non-pointer variables.  */
2166
2167   for (i = 0; i < FIRST_REF_NODE; i++)
2168     {
2169       unsigned int node = si->node_mapping[i];
2170
2171       if (graph->pointer_label[node] == 0)
2172         {
2173           if (dump_file && (dump_flags & TDF_DETAILS))
2174             fprintf (dump_file,
2175                      "%s is a non-pointer variable, eliminating edges.\n",
2176                      get_varinfo (node)->name);
2177           stats.nonpointer_vars++;
2178           clear_edges_for_node (graph, node);
2179         }
2180     }
2181
2182   return si;
2183 }
2184
2185 /* Free information that was only necessary for variable
2186    substitution.  */
2187
2188 static void
2189 free_var_substitution_info (struct scc_info *si)
2190 {
2191   free_scc_info (si);
2192   free (graph->pointer_label);
2193   free (graph->loc_label);
2194   free (graph->pointed_by);
2195   free (graph->points_to);
2196   free (graph->eq_rep);
2197   sbitmap_free (graph->direct_nodes);
2198   htab_delete (pointer_equiv_class_table);
2199   htab_delete (location_equiv_class_table);
2200   bitmap_obstack_release (&iteration_obstack);
2201 }
2202
2203 /* Return an existing node that is equivalent to NODE, which has
2204    equivalence class LABEL, if one exists.  Return NODE otherwise.  */
2205
2206 static unsigned int
2207 find_equivalent_node (constraint_graph_t graph,
2208                       unsigned int node, unsigned int label)
2209 {
2210   /* If the address version of this variable is unused, we can
2211      substitute it for anything else with the same label.
2212      Otherwise, we know the pointers are equivalent, but not the
2213      locations, and we can unite them later.  */
2214
2215   if (!bitmap_bit_p (graph->address_taken, node))
2216     {
2217       gcc_assert (label < graph->size);
2218
2219       if (graph->eq_rep[label] != -1)
2220         {
2221           /* Unify the two variables since we know they are equivalent.  */
2222           if (unite (graph->eq_rep[label], node))
2223             unify_nodes (graph, graph->eq_rep[label], node, false);
2224           return graph->eq_rep[label];
2225         }
2226       else
2227         {
2228           graph->eq_rep[label] = node;
2229           graph->pe_rep[label] = node;
2230         }
2231     }
2232   else
2233     {
2234       gcc_assert (label < graph->size);
2235       graph->pe[node] = label;
2236       if (graph->pe_rep[label] == -1)
2237         graph->pe_rep[label] = node;
2238     }
2239
2240   return node;
2241 }
2242
2243 /* Unite pointer equivalent but not location equivalent nodes in
2244    GRAPH.  This may only be performed once variable substitution is
2245    finished.  */
2246
2247 static void
2248 unite_pointer_equivalences (constraint_graph_t graph)
2249 {
2250   unsigned int i;
2251
2252   /* Go through the pointer equivalences and unite them to their
2253      representative, if they aren't already.  */
2254   for (i = 0; i < FIRST_REF_NODE; i++)
2255     {
2256       unsigned int label = graph->pe[i];
2257       if (label)
2258         {
2259           int label_rep = graph->pe_rep[label];
2260           
2261           if (label_rep == -1)
2262             continue;
2263           
2264           label_rep = find (label_rep);
2265           if (label_rep >= 0 && unite (label_rep, find (i)))
2266             unify_nodes (graph, label_rep, i, false);
2267         }
2268     }
2269 }
2270
2271 /* Move complex constraints to the GRAPH nodes they belong to.  */
2272
2273 static void
2274 move_complex_constraints (constraint_graph_t graph)
2275 {
2276   int i;
2277   constraint_t c;
2278
2279   for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
2280     {
2281       if (c)
2282         {
2283           struct constraint_expr lhs = c->lhs;
2284           struct constraint_expr rhs = c->rhs;
2285
2286           if (lhs.type == DEREF)
2287             {
2288               insert_into_complex (graph, lhs.var, c);
2289             }
2290           else if (rhs.type == DEREF)
2291             {
2292               if (!(get_varinfo (lhs.var)->is_special_var))
2293                 insert_into_complex (graph, rhs.var, c);
2294             }
2295           else if (rhs.type != ADDRESSOF && lhs.var > anything_id
2296                    && (lhs.offset != 0 || rhs.offset != 0))
2297             {
2298               insert_into_complex (graph, rhs.var, c);
2299             }
2300         }
2301     }
2302 }
2303
2304
2305 /* Optimize and rewrite complex constraints while performing
2306    collapsing of equivalent nodes.  SI is the SCC_INFO that is the
2307    result of perform_variable_substitution.  */
2308
2309 static void
2310 rewrite_constraints (constraint_graph_t graph,
2311                      struct scc_info *si)
2312 {
2313   int i;
2314   unsigned int j;
2315   constraint_t c;
2316
2317   for (j = 0; j < graph->size; j++)
2318     gcc_assert (find (j) == j);
2319
2320   for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
2321     {
2322       struct constraint_expr lhs = c->lhs;
2323       struct constraint_expr rhs = c->rhs;
2324       unsigned int lhsvar = find (get_varinfo_fc (lhs.var)->id);
2325       unsigned int rhsvar = find (get_varinfo_fc (rhs.var)->id);
2326       unsigned int lhsnode, rhsnode;
2327       unsigned int lhslabel, rhslabel;
2328
2329       lhsnode = si->node_mapping[lhsvar];
2330       rhsnode = si->node_mapping[rhsvar];
2331       lhslabel = graph->pointer_label[lhsnode];
2332       rhslabel = graph->pointer_label[rhsnode];
2333
2334       /* See if it is really a non-pointer variable, and if so, ignore
2335          the constraint.  */
2336       if (lhslabel == 0)
2337         {
2338           if (dump_file && (dump_flags & TDF_DETAILS))
2339             {
2340               
2341               fprintf (dump_file, "%s is a non-pointer variable,"
2342                        "ignoring constraint:",
2343                        get_varinfo (lhs.var)->name);
2344               dump_constraint (dump_file, c);
2345             }
2346           VEC_replace (constraint_t, constraints, i, NULL);
2347           continue;
2348         }
2349
2350       if (rhslabel == 0)
2351         {
2352           if (dump_file && (dump_flags & TDF_DETAILS))
2353             {
2354               
2355               fprintf (dump_file, "%s is a non-pointer variable,"
2356                        "ignoring constraint:",
2357                        get_varinfo (rhs.var)->name);
2358               dump_constraint (dump_file, c);
2359             }
2360           VEC_replace (constraint_t, constraints, i, NULL);
2361           continue;
2362         }
2363
2364       lhsvar = find_equivalent_node (graph, lhsvar, lhslabel);
2365       rhsvar = find_equivalent_node (graph, rhsvar, rhslabel);
2366       c->lhs.var = lhsvar;
2367       c->rhs.var = rhsvar;
2368
2369     }
2370 }
2371
2372 /* Eliminate indirect cycles involving NODE.  Return true if NODE was
2373    part of an SCC, false otherwise.  */
2374
2375 static bool
2376 eliminate_indirect_cycles (unsigned int node)
2377 {
2378   if (graph->indirect_cycles[node] != -1
2379       && !bitmap_empty_p (get_varinfo (node)->solution))
2380     {
2381       unsigned int i;
2382       VEC(unsigned,heap) *queue = NULL;
2383       int queuepos;
2384       unsigned int to = find (graph->indirect_cycles[node]);
2385       bitmap_iterator bi;
2386
2387       /* We can't touch the solution set and call unify_nodes
2388          at the same time, because unify_nodes is going to do
2389          bitmap unions into it. */
2390
2391       EXECUTE_IF_SET_IN_BITMAP (get_varinfo (node)->solution, 0, i, bi)
2392         {
2393           if (find (i) == i && i != to)
2394             {
2395               if (unite (to, i))
2396                 VEC_safe_push (unsigned, heap, queue, i);
2397             }
2398         }
2399
2400       for (queuepos = 0;
2401            VEC_iterate (unsigned, queue, queuepos, i);
2402            queuepos++)
2403         {
2404           unify_nodes (graph, to, i, true);
2405         }
2406       VEC_free (unsigned, heap, queue);
2407       return true;
2408     }
2409   return false;
2410 }
2411
2412 /* Solve the constraint graph GRAPH using our worklist solver.
2413    This is based on the PW* family of solvers from the "Efficient Field
2414    Sensitive Pointer Analysis for C" paper.
2415    It works by iterating over all the graph nodes, processing the complex
2416    constraints and propagating the copy constraints, until everything stops
2417    changed.  This corresponds to steps 6-8 in the solving list given above.  */
2418
2419 static void
2420 solve_graph (constraint_graph_t graph)
2421 {
2422   unsigned int size = graph->size;
2423   unsigned int i;
2424   bitmap pts;
2425
2426   changed_count = 0;
2427   changed = sbitmap_alloc (size);
2428   sbitmap_zero (changed);
2429
2430   /* Mark all initial non-collapsed nodes as changed.  */
2431   for (i = 0; i < size; i++)
2432     {
2433       varinfo_t ivi = get_varinfo (i);
2434       if (find (i) == i && !bitmap_empty_p (ivi->solution)
2435           && ((graph->succs[i] && !bitmap_empty_p (graph->succs[i]))
2436               || VEC_length (constraint_t, graph->complex[i]) > 0))
2437         {
2438           SET_BIT (changed, i);
2439           changed_count++;
2440         }
2441     }
2442
2443   /* Allocate a bitmap to be used to store the changed bits.  */
2444   pts = BITMAP_ALLOC (&pta_obstack);
2445
2446   while (changed_count > 0)
2447     {
2448       unsigned int i;
2449       struct topo_info *ti = init_topo_info ();
2450       stats.iterations++;
2451
2452       bitmap_obstack_initialize (&iteration_obstack);
2453
2454       compute_topo_order (graph, ti);
2455
2456       while (VEC_length (unsigned, ti->topo_order) != 0)
2457         {
2458
2459           i = VEC_pop (unsigned, ti->topo_order);
2460
2461           /* If this variable is not a representative, skip it.  */
2462           if (find (i) != i)
2463             continue;
2464
2465           /* In certain indirect cycle cases, we may merge this
2466              variable to another.  */
2467           if (eliminate_indirect_cycles (i) && find (i) != i)
2468             continue;
2469
2470           /* If the node has changed, we need to process the
2471              complex constraints and outgoing edges again.  */
2472           if (TEST_BIT (changed, i))
2473             {
2474               unsigned int j;
2475               constraint_t c;
2476               bitmap solution;
2477               VEC(constraint_t,heap) *complex = graph->complex[i];
2478               bool solution_empty;
2479
2480               RESET_BIT (changed, i);
2481               changed_count--;
2482
2483               /* Compute the changed set of solution bits.  */
2484               bitmap_and_compl (pts, get_varinfo (i)->solution,
2485                                 get_varinfo (i)->oldsolution);
2486
2487               if (bitmap_empty_p (pts))
2488                 continue;
2489
2490               bitmap_ior_into (get_varinfo (i)->oldsolution, pts);
2491
2492               solution = get_varinfo (i)->solution;
2493               solution_empty = bitmap_empty_p (solution);
2494
2495               /* Process the complex constraints */
2496               for (j = 0; VEC_iterate (constraint_t, complex, j, c); j++)
2497                 {
2498                   /* XXX: This is going to unsort the constraints in
2499                      some cases, which will occasionally add duplicate
2500                      constraints during unification.  This does not
2501                      affect correctness.  */
2502                   c->lhs.var = find (c->lhs.var);
2503                   c->rhs.var = find (c->rhs.var);
2504
2505                   /* The only complex constraint that can change our
2506                      solution to non-empty, given an empty solution,
2507                      is a constraint where the lhs side is receiving
2508                      some set from elsewhere.  */
2509                   if (!solution_empty || c->lhs.type != DEREF)
2510                     do_complex_constraint (graph, c, pts);
2511                 }
2512
2513               solution_empty = bitmap_empty_p (solution);
2514
2515               if (!solution_empty
2516                   /* Do not propagate the ESCAPED solutions.  */
2517                   && i != find (escaped_id))
2518                 {
2519                   bitmap_iterator bi;
2520
2521                   /* Propagate solution to all successors.  */
2522                   EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i],
2523                                                 0, j, bi)
2524                     {
2525                       bitmap tmp;
2526                       bool flag;
2527
2528                       unsigned int to = find (j);
2529                       tmp = get_varinfo (to)->solution;
2530                       flag = false;
2531
2532                       /* Don't try to propagate to ourselves.  */
2533                       if (to == i)
2534                         continue;
2535
2536                       flag = set_union_with_increment (tmp, pts, 0);
2537
2538                       if (flag)
2539                         {
2540                           get_varinfo (to)->solution = tmp;
2541                           if (!TEST_BIT (changed, to))
2542                             {
2543                               SET_BIT (changed, to);
2544                               changed_count++;
2545                             }
2546                         }
2547                     }
2548                 }
2549             }
2550         }
2551       free_topo_info (ti);
2552       bitmap_obstack_release (&iteration_obstack);
2553     }
2554
2555   BITMAP_FREE (pts);
2556   sbitmap_free (changed);
2557   bitmap_obstack_release (&oldpta_obstack);
2558 }
2559
2560 /* Map from trees to variable infos.  */
2561 static struct pointer_map_t *vi_for_tree;
2562
2563
2564 /* Insert ID as the variable id for tree T in the vi_for_tree map.  */
2565
2566 static void
2567 insert_vi_for_tree (tree t, varinfo_t vi)
2568 {
2569   void **slot = pointer_map_insert (vi_for_tree, t);
2570   gcc_assert (vi);
2571   gcc_assert (*slot == NULL);
2572   *slot = vi;
2573 }
2574
2575 /* Find the variable info for tree T in VI_FOR_TREE.  If T does not
2576    exist in the map, return NULL, otherwise, return the varinfo we found.  */
2577
2578 static varinfo_t
2579 lookup_vi_for_tree (tree t)
2580 {
2581   void **slot = pointer_map_contains (vi_for_tree, t);
2582   if (slot == NULL)
2583     return NULL;
2584
2585   return (varinfo_t) *slot;
2586 }
2587
2588 /* Return a printable name for DECL  */
2589
2590 static const char *
2591 alias_get_name (tree decl)
2592 {
2593   const char *res = get_name (decl);
2594   char *temp;
2595   int num_printed = 0;
2596
2597   if (res != NULL)
2598     return res;
2599
2600   res = "NULL";
2601   if (!dump_file)
2602     return res;
2603
2604   if (TREE_CODE (decl) == SSA_NAME)
2605     {
2606       num_printed = asprintf (&temp, "%s_%u",
2607                               alias_get_name (SSA_NAME_VAR (decl)),
2608                               SSA_NAME_VERSION (decl));
2609     }
2610   else if (DECL_P (decl))
2611     {
2612       num_printed = asprintf (&temp, "D.%u", DECL_UID (decl));
2613     }
2614   if (num_printed > 0)
2615     {
2616       res = ggc_strdup (temp);
2617       free (temp);
2618     }
2619   return res;
2620 }
2621
2622 /* Find the variable id for tree T in the map.
2623    If T doesn't exist in the map, create an entry for it and return it.  */
2624
2625 static varinfo_t
2626 get_vi_for_tree (tree t)
2627 {
2628   void **slot = pointer_map_contains (vi_for_tree, t);
2629   if (slot == NULL)
2630     return get_varinfo (create_variable_info_for (t, alias_get_name (t)));
2631
2632   return (varinfo_t) *slot;
2633 }
2634
2635 /* Get a constraint expression for a new temporary variable.  */
2636
2637 static struct constraint_expr
2638 get_constraint_exp_for_temp (tree t)
2639 {
2640   struct constraint_expr cexpr;
2641
2642   gcc_assert (SSA_VAR_P (t));
2643
2644   cexpr.type = SCALAR;
2645   cexpr.var = get_vi_for_tree (t)->id;
2646   cexpr.offset = 0;
2647
2648   return cexpr;
2649 }
2650
2651 /* Get a constraint expression vector from an SSA_VAR_P node.
2652    If address_p is true, the result will be taken its address of.  */
2653
2654 static void
2655 get_constraint_for_ssa_var (tree t, VEC(ce_s, heap) **results, bool address_p)
2656 {
2657   struct constraint_expr cexpr;
2658   varinfo_t vi;
2659
2660   /* We allow FUNCTION_DECLs here even though it doesn't make much sense.  */
2661   gcc_assert (SSA_VAR_P (t) || DECL_P (t));
2662
2663   /* For parameters, get at the points-to set for the actual parm
2664      decl.  */
2665   if (TREE_CODE (t) == SSA_NAME
2666       && TREE_CODE (SSA_NAME_VAR (t)) == PARM_DECL
2667       && SSA_NAME_IS_DEFAULT_DEF (t))
2668     {
2669       get_constraint_for_ssa_var (SSA_NAME_VAR (t), results, address_p);
2670       return;
2671     }
2672
2673   vi = get_vi_for_tree (t);
2674   cexpr.var = vi->id;
2675   cexpr.type = SCALAR;
2676   cexpr.offset = 0;
2677   /* If we determine the result is "anything", and we know this is readonly,
2678      say it points to readonly memory instead.  */
2679   if (cexpr.var == anything_id && TREE_READONLY (t))
2680     {
2681       gcc_unreachable ();
2682       cexpr.type = ADDRESSOF;
2683       cexpr.var = readonly_id;
2684     }
2685
2686   /* If we are not taking the address of the constraint expr, add all
2687      sub-fiels of the variable as well.  */
2688   if (!address_p)
2689     {
2690       for (; vi; vi = vi->next)
2691         {
2692           cexpr.var = vi->id;
2693           VEC_safe_push (ce_s, heap, *results, &cexpr);
2694         }
2695       return;
2696     }
2697
2698   VEC_safe_push (ce_s, heap, *results, &cexpr);
2699 }
2700
2701 /* Process constraint T, performing various simplifications and then
2702    adding it to our list of overall constraints.  */
2703
2704 static void
2705 process_constraint (constraint_t t)
2706 {
2707   struct constraint_expr rhs = t->rhs;
2708   struct constraint_expr lhs = t->lhs;
2709
2710   gcc_assert (rhs.var < VEC_length (varinfo_t, varmap));
2711   gcc_assert (lhs.var < VEC_length (varinfo_t, varmap));
2712
2713   /* ANYTHING == ANYTHING is pointless.  */
2714   if (lhs.var == anything_id && rhs.var == anything_id)
2715     return;
2716
2717   /* If we have &ANYTHING = something, convert to SOMETHING = &ANYTHING) */
2718   else if (lhs.var == anything_id && lhs.type == ADDRESSOF)
2719     {
2720       rhs = t->lhs;
2721       t->lhs = t->rhs;
2722       t->rhs = rhs;
2723       process_constraint (t);
2724     }
2725   /* This can happen in our IR with things like n->a = *p */
2726   else if (rhs.type == DEREF && lhs.type == DEREF && rhs.var != anything_id)
2727     {
2728       /* Split into tmp = *rhs, *lhs = tmp */
2729       tree rhsdecl = get_varinfo (rhs.var)->decl;
2730       tree pointertype = TREE_TYPE (rhsdecl);
2731       tree pointedtotype = TREE_TYPE (pointertype);
2732       tree tmpvar = create_tmp_var_raw (pointedtotype, "doubledereftmp");
2733       struct constraint_expr tmplhs = get_constraint_exp_for_temp (tmpvar);
2734
2735       process_constraint (new_constraint (tmplhs, rhs));
2736       process_constraint (new_constraint (lhs, tmplhs));
2737     }
2738   else if (rhs.type == ADDRESSOF && lhs.type == DEREF)
2739     {
2740       /* Split into tmp = &rhs, *lhs = tmp */
2741       tree rhsdecl = get_varinfo (rhs.var)->decl;
2742       tree pointertype = TREE_TYPE (rhsdecl);
2743       tree tmpvar = create_tmp_var_raw (pointertype, "derefaddrtmp");
2744       struct constraint_expr tmplhs = get_constraint_exp_for_temp (tmpvar);
2745
2746       process_constraint (new_constraint (tmplhs, rhs));
2747       process_constraint (new_constraint (lhs, tmplhs));
2748     }
2749   else
2750     {
2751       gcc_assert (rhs.type != ADDRESSOF || rhs.offset == 0);
2752       VEC_safe_push (constraint_t, heap, constraints, t);
2753     }
2754 }
2755
2756 /* Return true if T is a type that could contain pointers.  */
2757
2758 static bool
2759 type_could_have_pointers (tree type)
2760 {
2761   if (POINTER_TYPE_P (type))
2762     return true;
2763
2764   if (TREE_CODE (type) == ARRAY_TYPE)
2765     return type_could_have_pointers (TREE_TYPE (type));
2766
2767   return AGGREGATE_TYPE_P (type);
2768 }
2769
2770 /* Return true if T is a variable of a type that could contain
2771    pointers.  */
2772
2773 static bool
2774 could_have_pointers (tree t)
2775 {
2776   return type_could_have_pointers (TREE_TYPE (t));
2777 }
2778
2779 /* Return the position, in bits, of FIELD_DECL from the beginning of its
2780    structure.  */
2781
2782 static HOST_WIDE_INT
2783 bitpos_of_field (const tree fdecl)
2784 {
2785
2786   if (!host_integerp (DECL_FIELD_OFFSET (fdecl), 0)
2787       || !host_integerp (DECL_FIELD_BIT_OFFSET (fdecl), 0))
2788     return -1;
2789
2790   return (TREE_INT_CST_LOW (DECL_FIELD_OFFSET (fdecl)) * 8
2791           + TREE_INT_CST_LOW (DECL_FIELD_BIT_OFFSET (fdecl)));
2792 }
2793
2794
2795 /* Get constraint expressions for offsetting PTR by OFFSET.  Stores the
2796    resulting constraint expressions in *RESULTS.  */
2797
2798 static void
2799 get_constraint_for_ptr_offset (tree ptr, tree offset,
2800                                VEC (ce_s, heap) **results)
2801 {
2802   struct constraint_expr *c;
2803   unsigned int j, n;
2804   unsigned HOST_WIDE_INT rhsunitoffset, rhsoffset;
2805
2806   /* If we do not do field-sensitive PTA adding offsets to pointers
2807      does not change the points-to solution.  */
2808   if (!use_field_sensitive)
2809     {
2810       get_constraint_for (ptr, results);
2811       return;
2812     }
2813
2814   /* If the offset is not a non-negative integer constant that fits
2815      in a HOST_WIDE_INT, we have to fall back to a conservative
2816      solution which includes all sub-fields of all pointed-to
2817      variables of ptr.
2818      ???  As we do not have the ability to express this, fall back
2819      to anything.  */
2820   if (!host_integerp (offset, 1))
2821     {
2822       struct constraint_expr temp;
2823       temp.var = anything_id;
2824       temp.type = SCALAR;
2825       temp.offset = 0;
2826       VEC_safe_push (ce_s, heap, *results, &temp);
2827       return;
2828     }
2829
2830   /* Make sure the bit-offset also fits.  */
2831   rhsunitoffset = TREE_INT_CST_LOW (offset);
2832   rhsoffset = rhsunitoffset * BITS_PER_UNIT;
2833   if (rhsunitoffset != rhsoffset / BITS_PER_UNIT)
2834     {
2835       struct constraint_expr temp;
2836       temp.var = anything_id;
2837       temp.type = SCALAR;
2838       temp.offset = 0;
2839       VEC_safe_push (ce_s, heap, *results, &temp);
2840       return;
2841     }
2842
2843   get_constraint_for (ptr, results);
2844   if (rhsoffset == 0)
2845     return;
2846
2847   /* As we are eventually appending to the solution do not use
2848      VEC_iterate here.  */
2849   n = VEC_length (ce_s, *results);
2850   for (j = 0; j < n; j++)
2851     {
2852       varinfo_t curr;
2853       c = VEC_index (ce_s, *results, j);
2854       curr = get_varinfo (c->var);
2855
2856       if (c->type == ADDRESSOF
2857           && !curr->is_full_var)
2858         {
2859           varinfo_t temp, curr = get_varinfo (c->var);
2860
2861           /* Search the sub-field which overlaps with the
2862              pointed-to offset.  As we deal with positive offsets
2863              only, we can start the search from the current variable.  */
2864           temp = first_vi_for_offset (curr, curr->offset + rhsoffset);
2865
2866           /* If the result is outside of the variable we have to provide
2867              a conservative result, as the variable is still reachable
2868              from the resulting pointer (even though it technically
2869              cannot point to anything).  The last sub-field is such
2870              a conservative result.
2871              ???  If we always had a sub-field for &object + 1 then
2872              we could represent this in a more precise way.  */
2873           if (temp == NULL)
2874             {
2875               temp = curr;
2876               while (temp->next != NULL)
2877                 temp = temp->next;
2878               continue;
2879             }
2880
2881           /* If the found variable is not exactly at the pointed to
2882              result, we have to include the next variable in the
2883              solution as well.  Otherwise two increments by offset / 2
2884              do not result in the same or a conservative superset
2885              solution.  */
2886           if (temp->offset != curr->offset + rhsoffset
2887               && temp->next != NULL)
2888             {
2889               struct constraint_expr c2;
2890               c2.var = temp->next->id;
2891               c2.type = ADDRESSOF;
2892               c2.offset = 0;
2893               VEC_safe_push (ce_s, heap, *results, &c2);
2894             }
2895           c->var = temp->id;
2896           c->offset = 0;
2897         }
2898       else if (c->type == ADDRESSOF
2899                /* If this varinfo represents a full variable just use it.  */
2900                && curr->is_full_var)
2901         c->offset = 0;
2902       else
2903         c->offset = rhsoffset;
2904     }
2905 }
2906
2907
2908 /* Given a COMPONENT_REF T, return the constraint_expr vector for it.
2909    If address_p is true the result will be taken its address of.  */
2910
2911 static void
2912 get_constraint_for_component_ref (tree t, VEC(ce_s, heap) **results,
2913                                   bool address_p)
2914 {
2915   tree orig_t = t;
2916   HOST_WIDE_INT bitsize = -1;
2917   HOST_WIDE_INT bitmaxsize = -1;
2918   HOST_WIDE_INT bitpos;
2919   tree forzero;
2920   struct constraint_expr *result;
2921
2922   /* Some people like to do cute things like take the address of
2923      &0->a.b */
2924   forzero = t;
2925   while (!SSA_VAR_P (forzero) && !CONSTANT_CLASS_P (forzero))
2926     forzero = TREE_OPERAND (forzero, 0);
2927
2928   if (CONSTANT_CLASS_P (forzero) && integer_zerop (forzero))
2929     {
2930       struct constraint_expr temp;
2931
2932       temp.offset = 0;
2933       temp.var = integer_id;
2934       temp.type = SCALAR;
2935       VEC_safe_push (ce_s, heap, *results, &temp);
2936       return;
2937     }
2938
2939   t = get_ref_base_and_extent (t, &bitpos, &bitsize, &bitmaxsize);
2940
2941   /* Pretend to take the address of the base, we'll take care of
2942      adding the required subset of sub-fields below.  */
2943   get_constraint_for_1 (t, results, true);
2944   gcc_assert (VEC_length (ce_s, *results) == 1);
2945   result = VEC_last (ce_s, *results);
2946
2947   /* This can also happen due to weird offsetof type macros.  */
2948   if (TREE_CODE (t) != ADDR_EXPR && result->type == ADDRESSOF)
2949     result->type = SCALAR;
2950
2951   if (result->type == SCALAR
2952       && get_varinfo (result->var)->is_full_var)
2953     /* For single-field vars do not bother about the offset.  */
2954     result->offset = 0;
2955   else if (result->type == SCALAR)
2956     {
2957       /* In languages like C, you can access one past the end of an
2958          array.  You aren't allowed to dereference it, so we can
2959          ignore this constraint. When we handle pointer subtraction,
2960          we may have to do something cute here.  */
2961
2962       if ((unsigned HOST_WIDE_INT)bitpos < get_varinfo (result->var)->fullsize
2963           && bitmaxsize != 0)
2964         {
2965           /* It's also not true that the constraint will actually start at the
2966              right offset, it may start in some padding.  We only care about
2967              setting the constraint to the first actual field it touches, so
2968              walk to find it.  */
2969           struct constraint_expr cexpr = *result;
2970           varinfo_t curr;
2971           VEC_pop (ce_s, *results);
2972           cexpr.offset = 0;
2973           for (curr = get_varinfo (cexpr.var); curr; curr = curr->next)
2974             {
2975               if (ranges_overlap_p (curr->offset, curr->size,
2976                                     bitpos, bitmaxsize))
2977                 {
2978                   cexpr.var = curr->id;
2979                   VEC_safe_push (ce_s, heap, *results, &cexpr);
2980                   if (address_p)
2981                     break;
2982                 }
2983             }
2984           /* If we are going to take the address of this field then
2985              to be able to compute reachability correctly add at least
2986              the last field of the variable.  */
2987           if (address_p
2988               && VEC_length (ce_s, *results) == 0)
2989             {
2990               curr = get_varinfo (cexpr.var);
2991               while (curr->next != NULL)
2992                 curr = curr->next;
2993               cexpr.var = curr->id;
2994               VEC_safe_push (ce_s, heap, *results, &cexpr);
2995             }
2996           else
2997             /* Assert that we found *some* field there. The user couldn't be
2998                accessing *only* padding.  */
2999             /* Still the user could access one past the end of an array
3000                embedded in a struct resulting in accessing *only* padding.  */
3001             gcc_assert (VEC_length (ce_s, *results) >= 1
3002                         || ref_contains_array_ref (orig_t));
3003         }
3004       else if (bitmaxsize == 0)
3005         {
3006           if (dump_file && (dump_flags & TDF_DETAILS))
3007             fprintf (dump_file, "Access to zero-sized part of variable,"
3008                      "ignoring\n");
3009         }
3010       else
3011         if (dump_file && (dump_flags & TDF_DETAILS))
3012           fprintf (dump_file, "Access to past the end of variable, ignoring\n");
3013     }
3014   else if (bitmaxsize == -1)
3015     {
3016       /* We can't handle DEREF constraints with unknown size, we'll
3017          get the wrong answer.  Punt and return anything.  */
3018       result->var = anything_id;
3019       result->offset = 0;
3020     }
3021   else
3022     result->offset = bitpos;
3023 }
3024
3025
3026 /* Dereference the constraint expression CONS, and return the result.
3027    DEREF (ADDRESSOF) = SCALAR
3028    DEREF (SCALAR) = DEREF
3029    DEREF (DEREF) = (temp = DEREF1; result = DEREF(temp))
3030    This is needed so that we can handle dereferencing DEREF constraints.  */
3031
3032 static void
3033 do_deref (VEC (ce_s, heap) **constraints)
3034 {
3035   struct constraint_expr *c;
3036   unsigned int i = 0;
3037
3038   for (i = 0; VEC_iterate (ce_s, *constraints, i, c); i++)
3039     {
3040       if (c->type == SCALAR)
3041         c->type = DEREF;
3042       else if (c->type == ADDRESSOF)
3043         c->type = SCALAR;
3044       else if (c->type == DEREF)
3045         {
3046           tree tmpvar = create_tmp_var_raw (ptr_type_node, "dereftmp");
3047           struct constraint_expr tmplhs = get_constraint_exp_for_temp (tmpvar);
3048           process_constraint (new_constraint (tmplhs, *c));
3049           c->var = tmplhs.var;
3050         }
3051       else
3052         gcc_unreachable ();
3053     }
3054 }
3055
3056 /* Given a tree T, return the constraint expression for it.  */
3057
3058 static void
3059 get_constraint_for_1 (tree t, VEC (ce_s, heap) **results, bool address_p)
3060 {
3061   struct constraint_expr temp;
3062
3063   /* x = integer is all glommed to a single variable, which doesn't
3064      point to anything by itself.  That is, of course, unless it is an
3065      integer constant being treated as a pointer, in which case, we
3066      will return that this is really the addressof anything.  This
3067      happens below, since it will fall into the default case. The only
3068      case we know something about an integer treated like a pointer is
3069      when it is the NULL pointer, and then we just say it points to
3070      NULL.
3071
3072      Do not do that if -fno-delete-null-pointer-checks though, because
3073      in that case *NULL does not fail, so it _should_ alias *anything.
3074      It is not worth adding a new option or renaming the existing one,
3075      since this case is relatively obscure.  */
3076   if (flag_delete_null_pointer_checks
3077       && TREE_CODE (t) == INTEGER_CST
3078       && integer_zerop (t))
3079     {
3080       temp.var = nothing_id;
3081       temp.type = ADDRESSOF;
3082       temp.offset = 0;
3083       VEC_safe_push (ce_s, heap, *results, &temp);
3084       return;
3085     }
3086
3087   /* String constants are read-only.  */
3088   if (TREE_CODE (t) == STRING_CST)
3089     {
3090       temp.var = readonly_id;
3091       temp.type = SCALAR;
3092       temp.offset = 0;
3093       VEC_safe_push (ce_s, heap, *results, &temp);
3094       return;
3095     }
3096
3097   switch (TREE_CODE_CLASS (TREE_CODE (t)))
3098     {
3099     case tcc_expression:
3100       {
3101         switch (TREE_CODE (t))
3102           {
3103           case ADDR_EXPR:
3104             {
3105               struct constraint_expr *c;
3106               unsigned int i;
3107               tree exp = TREE_OPERAND (t, 0);
3108
3109               get_constraint_for_1 (exp, results, true);
3110
3111               for (i = 0; VEC_iterate (ce_s, *results, i, c); i++)
3112                 {
3113                   if (c->type == DEREF)
3114                     c->type = SCALAR;
3115                   else
3116                     c->type = ADDRESSOF;
3117                 }
3118               return;
3119             }
3120             break;
3121           default:;
3122           }
3123         break;
3124       }
3125     case tcc_reference:
3126       {
3127         switch (TREE_CODE (t))
3128           {
3129           case INDIRECT_REF:
3130             {
3131               get_constraint_for_1 (TREE_OPERAND (t, 0), results, address_p);
3132               do_deref (results);
3133               return;
3134             }
3135           case ARRAY_REF:
3136           case ARRAY_RANGE_REF:
3137           case COMPONENT_REF:
3138             get_constraint_for_component_ref (t, results, address_p);
3139             return;
3140           default:;
3141           }
3142         break;
3143       }
3144     case tcc_exceptional:
3145       {
3146         switch (TREE_CODE (t))
3147           {
3148           case SSA_NAME:
3149             {
3150               get_constraint_for_ssa_var (t, results, address_p);
3151               return;
3152             }
3153           default:;
3154           }
3155         break;
3156       }
3157     case tcc_declaration:
3158       {
3159         get_constraint_for_ssa_var (t, results, address_p);
3160         return;
3161       }
3162     default:;
3163     }
3164
3165   /* The default fallback is a constraint from anything.  */
3166   temp.type = ADDRESSOF;
3167   temp.var = anything_id;
3168   temp.offset = 0;
3169   VEC_safe_push (ce_s, heap, *results, &temp);
3170 }
3171
3172 /* Given a gimple tree T, return the constraint expression vector for it.  */
3173
3174 static void
3175 get_constraint_for (tree t, VEC (ce_s, heap) **results)
3176 {
3177   gcc_assert (VEC_length (ce_s, *results) == 0);
3178
3179   get_constraint_for_1 (t, results, false);
3180 }
3181
3182 /* Handle the structure copy case where we have a simple structure copy
3183    between LHS and RHS that is of SIZE (in bits)
3184
3185    For each field of the lhs variable (lhsfield)
3186      For each field of the rhs variable at lhsfield.offset (rhsfield)
3187        add the constraint lhsfield = rhsfield
3188
3189    If we fail due to some kind of type unsafety or other thing we
3190    can't handle, return false.  We expect the caller to collapse the
3191    variable in that case.  */
3192
3193 static bool
3194 do_simple_structure_copy (const struct constraint_expr lhs,
3195                           const struct constraint_expr rhs,
3196                           const unsigned HOST_WIDE_INT size)
3197 {
3198   varinfo_t p = get_varinfo (lhs.var);
3199   unsigned HOST_WIDE_INT pstart, last;
3200   pstart = p->offset;
3201   last = p->offset + size;
3202   for (; p && p->offset < last; p = p->next)
3203     {
3204       varinfo_t q;
3205       struct constraint_expr templhs = lhs;
3206       struct constraint_expr temprhs = rhs;
3207       unsigned HOST_WIDE_INT fieldoffset;
3208
3209       templhs.var = p->id;
3210       q = get_varinfo (temprhs.var);
3211       fieldoffset = p->offset - pstart;
3212       q = first_vi_for_offset (q, q->offset + fieldoffset);
3213       if (!q)
3214         return false;
3215       temprhs.var = q->id;
3216       process_constraint (new_constraint (templhs, temprhs));
3217     }
3218   return true;
3219 }
3220
3221
3222 /* Handle the structure copy case where we have a  structure copy between a
3223    aggregate on the LHS and a dereference of a pointer on the RHS
3224    that is of SIZE (in bits)
3225
3226    For each field of the lhs variable (lhsfield)
3227        rhs.offset = lhsfield->offset
3228        add the constraint lhsfield = rhs
3229 */
3230
3231 static void
3232 do_rhs_deref_structure_copy (const struct constraint_expr lhs,
3233                              const struct constraint_expr rhs,
3234                              const unsigned HOST_WIDE_INT size)
3235 {
3236   varinfo_t p = get_varinfo (lhs.var);
3237   unsigned HOST_WIDE_INT pstart,last;
3238   pstart = p->offset;
3239   last = p->offset + size;
3240
3241   for (; p && p->offset < last; p = p->next)
3242     {
3243       varinfo_t q;
3244       struct constraint_expr templhs = lhs;
3245       struct constraint_expr temprhs = rhs;
3246       unsigned HOST_WIDE_INT fieldoffset;
3247
3248
3249       if (templhs.type == SCALAR)
3250         templhs.var = p->id;
3251       else
3252         templhs.offset = p->offset;
3253
3254       q = get_varinfo (temprhs.var);
3255       fieldoffset = p->offset - pstart;
3256       temprhs.offset += fieldoffset;
3257       process_constraint (new_constraint (templhs, temprhs));
3258     }
3259 }
3260
3261 /* Handle the structure copy case where we have a structure copy
3262    between an aggregate on the RHS and a dereference of a pointer on
3263    the LHS that is of SIZE (in bits)
3264
3265    For each field of the rhs variable (rhsfield)
3266        lhs.offset = rhsfield->offset
3267        add the constraint lhs = rhsfield
3268 */
3269
3270 static void
3271 do_lhs_deref_structure_copy (const struct constraint_expr lhs,
3272                              const struct constraint_expr rhs,
3273                              const unsigned HOST_WIDE_INT size)
3274 {
3275   varinfo_t p = get_varinfo (rhs.var);
3276   unsigned HOST_WIDE_INT pstart,last;
3277   pstart = p->offset;
3278   last = p->offset + size;
3279
3280   for (; p && p->offset < last; p = p->next)
3281     {
3282       varinfo_t q;
3283       struct constraint_expr templhs = lhs;
3284       struct constraint_expr temprhs = rhs;
3285       unsigned HOST_WIDE_INT fieldoffset;
3286
3287
3288       if (temprhs.type == SCALAR)
3289         temprhs.var = p->id;
3290       else
3291         temprhs.offset = p->offset;
3292
3293       q = get_varinfo (templhs.var);
3294       fieldoffset = p->offset - pstart;
3295       templhs.offset += fieldoffset;
3296       process_constraint (new_constraint (templhs, temprhs));
3297     }
3298 }
3299
3300 /* Sometimes, frontends like to give us bad type information.  This
3301    function will collapse all the fields from VAR to the end of VAR,
3302    into VAR, so that we treat those fields as a single variable.
3303    We return the variable they were collapsed into.  */
3304
3305 static unsigned int
3306 collapse_rest_of_var (unsigned int var)
3307 {
3308   varinfo_t currvar = get_varinfo (var);
3309   varinfo_t field;
3310
3311   for (field = currvar->next; field; field = field->next)
3312     {
3313       if (dump_file)
3314         fprintf (dump_file, "Type safety: Collapsing var %s into %s\n",
3315                  field->name, currvar->name);
3316
3317       gcc_assert (field->collapsed_to == 0);
3318       field->collapsed_to = currvar->id;
3319     }
3320
3321   currvar->next = NULL;
3322   currvar->size = currvar->fullsize - currvar->offset;
3323
3324   return currvar->id;
3325 }
3326
3327 /* Handle aggregate copies by expanding into copies of the respective
3328    fields of the structures.  */
3329
3330 static void
3331 do_structure_copy (tree lhsop, tree rhsop)
3332 {
3333   struct constraint_expr lhs, rhs, tmp;
3334   VEC (ce_s, heap) *lhsc = NULL, *rhsc = NULL;
3335   varinfo_t p;
3336   unsigned HOST_WIDE_INT lhssize;
3337   unsigned HOST_WIDE_INT rhssize;
3338
3339   /* Pretend we are taking the address of the constraint exprs.
3340      We deal with walking the sub-fields ourselves.  */
3341   get_constraint_for_1 (lhsop, &lhsc, true);
3342   get_constraint_for_1 (rhsop, &rhsc, true);
3343   gcc_assert (VEC_length (ce_s, lhsc) == 1);
3344   gcc_assert (VEC_length (ce_s, rhsc) == 1);
3345   lhs = *(VEC_last (ce_s, lhsc));
3346   rhs = *(VEC_last (ce_s, rhsc));
3347
3348   VEC_free (ce_s, heap, lhsc);
3349   VEC_free (ce_s, heap, rhsc);
3350
3351   /* If we have special var = x, swap it around.  */
3352   if (lhs.var <= integer_id && !(get_varinfo (rhs.var)->is_special_var))
3353     {
3354       tmp = lhs;
3355       lhs = rhs;
3356       rhs = tmp;
3357     }
3358
3359   /*  This is fairly conservative for the RHS == ADDRESSOF case, in that it's
3360       possible it's something we could handle.  However, most cases falling
3361       into this are dealing with transparent unions, which are slightly
3362       weird. */
3363   if (rhs.type == ADDRESSOF && !(get_varinfo (rhs.var)->is_special_var))
3364     {
3365       rhs.type = ADDRESSOF;
3366       rhs.var = anything_id;
3367     }
3368
3369   /* If the RHS is a special var, or an addressof, set all the LHS fields to
3370      that special var.  */
3371   if (rhs.var <= integer_id)
3372     {
3373       for (p = get_varinfo (lhs.var); p; p = p->next)
3374         {
3375           struct constraint_expr templhs = lhs;
3376           struct constraint_expr temprhs = rhs;
3377
3378           if (templhs.type == SCALAR )
3379             templhs.var = p->id;
3380           else
3381             templhs.offset += p->offset;
3382           process_constraint (new_constraint (templhs, temprhs));
3383         }
3384     }
3385   else
3386     {
3387       tree rhstype = TREE_TYPE (rhsop);
3388       tree lhstype = TREE_TYPE (lhsop);
3389       tree rhstypesize;
3390       tree lhstypesize;
3391
3392       lhstypesize = DECL_P (lhsop) ? DECL_SIZE (lhsop) : TYPE_SIZE (lhstype);
3393       rhstypesize = DECL_P (rhsop) ? DECL_SIZE (rhsop) : TYPE_SIZE (rhstype);
3394
3395       /* If we have a variably sized types on the rhs or lhs, and a deref
3396          constraint, add the constraint, lhsconstraint = &ANYTHING.
3397          This is conservatively correct because either the lhs is an unknown
3398          sized var (if the constraint is SCALAR), or the lhs is a DEREF
3399          constraint, and every variable it can point to must be unknown sized
3400          anyway, so we don't need to worry about fields at all.  */
3401       if ((rhs.type == DEREF && TREE_CODE (rhstypesize) != INTEGER_CST)
3402           || (lhs.type == DEREF && TREE_CODE (lhstypesize) != INTEGER_CST))
3403         {
3404           rhs.var = anything_id;
3405           rhs.type = ADDRESSOF;
3406           rhs.offset = 0;
3407           process_constraint (new_constraint (lhs, rhs));
3408           return;
3409         }
3410
3411       /* The size only really matters insofar as we don't set more or less of
3412          the variable.  If we hit an unknown size var, the size should be the
3413          whole darn thing.  */
3414       if (get_varinfo (rhs.var)->is_unknown_size_var)
3415         rhssize = ~0;
3416       else
3417         rhssize = TREE_INT_CST_LOW (rhstypesize);
3418
3419       if (get_varinfo (lhs.var)->is_unknown_size_var)
3420         lhssize = ~0;
3421       else
3422         lhssize = TREE_INT_CST_LOW (lhstypesize);
3423
3424
3425       if (rhs.type == SCALAR && lhs.type == SCALAR)
3426         {
3427           if (!do_simple_structure_copy (lhs, rhs, MIN (lhssize, rhssize)))
3428             {
3429               lhs.var = collapse_rest_of_var (get_varinfo_fc (lhs.var)->id);
3430               rhs.var = collapse_rest_of_var (get_varinfo_fc (rhs.var)->id);
3431               lhs.offset = 0;
3432               rhs.offset = 0;
3433               lhs.type = SCALAR;
3434               rhs.type = SCALAR;
3435               process_constraint (new_constraint (lhs, rhs));
3436             }
3437         }
3438       else if (lhs.type != DEREF && rhs.type == DEREF)
3439         do_rhs_deref_structure_copy (lhs, rhs, MIN (lhssize, rhssize));
3440       else if (lhs.type == DEREF && rhs.type != DEREF)
3441         do_lhs_deref_structure_copy (lhs, rhs, MIN (lhssize, rhssize));
3442       else
3443         {
3444           tree pointedtotype = lhstype;
3445           tree tmpvar;
3446
3447           gcc_assert (rhs.type == DEREF && lhs.type == DEREF);
3448           tmpvar = create_tmp_var_raw (pointedtotype, "structcopydereftmp");
3449           do_structure_copy (tmpvar, rhsop);
3450           do_structure_copy (lhsop, tmpvar);
3451         }
3452     }
3453 }
3454
3455 /* Create a constraint ID = OP.  */
3456
3457 static void
3458 make_constraint_to (unsigned id, tree op)
3459 {
3460   VEC(ce_s, heap) *rhsc = NULL;
3461   struct constraint_expr *c;
3462   struct constraint_expr includes;
3463   unsigned int j;
3464
3465   includes.var = id;
3466   includes.offset = 0;
3467   includes.type = SCALAR;
3468
3469   get_constraint_for (op, &rhsc);
3470   for (j = 0; VEC_iterate (ce_s, rhsc, j, c); j++)
3471     process_constraint (new_constraint (includes, *c));
3472   VEC_free (ce_s, heap, rhsc);
3473 }
3474
3475 /* Make constraints necessary to make OP escape.  */
3476
3477 static void
3478 make_escape_constraint (tree op)
3479 {
3480   make_constraint_to (escaped_id, op);
3481 }
3482
3483 /* For non-IPA mode, generate constraints necessary for a call on the
3484    RHS.  */
3485
3486 static void
3487 handle_rhs_call (gimple stmt, VEC(ce_s, heap) **results)
3488 {
3489   struct constraint_expr rhsc;
3490   unsigned i;
3491
3492   for (i = 0; i < gimple_call_num_args (stmt); ++i)
3493     {
3494       tree arg = gimple_call_arg (stmt, i);
3495
3496       /* Find those pointers being passed, and make sure they end up
3497          pointing to anything.  */
3498       if (could_have_pointers (arg))
3499         make_escape_constraint (arg);
3500     }
3501
3502   /* The static chain escapes as well.  */
3503   if (gimple_call_chain (stmt))
3504     make_escape_constraint (gimple_call_chain (stmt));
3505
3506   /* Regular functions return escaped addresses.  */
3507   rhsc.var = escaped_id;
3508   rhsc.offset = 0;
3509   rhsc.type = ADDRESSOF;
3510   VEC_safe_push (ce_s, heap, *results, &rhsc);
3511 }
3512
3513 /* For non-IPA mode, generate constraints necessary for a call
3514    that returns a pointer and assigns it to LHS.  This simply makes
3515    the LHS point to global and escaped variables.  */
3516
3517 static void
3518 handle_lhs_call (tree lhs, int flags, VEC(ce_s, heap) *rhsc)
3519 {
3520   VEC(ce_s, heap) *lhsc = NULL;
3521   unsigned int j;
3522   struct constraint_expr *lhsp;
3523
3524   get_constraint_for (lhs, &lhsc);
3525
3526   if (flags & ECF_MALLOC)
3527     {
3528       struct constraint_expr rhsc;
3529       tree heapvar = heapvar_lookup (lhs);
3530       varinfo_t vi;
3531
3532       if (heapvar == NULL)
3533         {
3534           heapvar = create_tmp_var_raw (ptr_type_node, "HEAP");
3535           DECL_EXTERNAL (heapvar) = 1;
3536           get_var_ann (heapvar)->is_heapvar = 1;
3537           if (gimple_referenced_vars (cfun))
3538             add_referenced_var (heapvar);
3539           heapvar_insert (lhs, heapvar);
3540         }
3541
3542       rhsc.var = create_variable_info_for (heapvar,
3543                                            alias_get_name (heapvar));
3544       vi = get_varinfo (rhsc.var);
3545       vi->is_artificial_var = 1;
3546       vi->is_heap_var = 1;
3547       vi->is_unknown_size_var = true;
3548       vi->fullsize = ~0;
3549       vi->size = ~0;
3550       rhsc.type = ADDRESSOF;
3551       rhsc.offset = 0;
3552       for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp); j++)
3553         process_constraint (new_constraint (*lhsp, rhsc));
3554     }
3555   else if (VEC_length (ce_s, rhsc) > 0)
3556     {
3557       struct constraint_expr *lhsp, *rhsp;
3558       unsigned int i, j;
3559       /* If the store is to a global decl make sure to
3560          add proper escape constraints.  */
3561       lhs = get_base_address (lhs);
3562       if (lhs
3563           && DECL_P (lhs)
3564           && is_global_var (lhs))
3565         {
3566           struct constraint_expr tmpc;
3567           tmpc.var = escaped_id;
3568           tmpc.offset = 0;
3569           tmpc.type = SCALAR;
3570           VEC_safe_push (ce_s, heap, lhsc, &tmpc);
3571         }
3572       for (i = 0; VEC_iterate (ce_s, lhsc, i, lhsp); ++i)
3573         for (j = 0; VEC_iterate (ce_s, rhsc, j, rhsp); ++j)
3574           process_constraint (new_constraint (*lhsp, *rhsp));
3575     }
3576   VEC_free (ce_s, heap, lhsc);
3577 }
3578
3579 /* For non-IPA mode, generate constraints necessary for a call of a
3580    const function that returns a pointer in the statement STMT.  */
3581
3582 static void
3583 handle_const_call (gimple stmt, VEC(ce_s, heap) **results)
3584 {
3585   struct constraint_expr rhsc, tmpc;
3586   tree tmpvar = NULL_TREE;
3587   unsigned int k;
3588
3589   /* Treat nested const functions the same as pure functions as far
3590      as the static chain is concerned.  */
3591   if (gimple_call_chain (stmt))
3592     {
3593       make_constraint_to (callused_id, gimple_call_chain (stmt));
3594       rhsc.var = callused_id;
3595       rhsc.offset = 0;
3596       rhsc.type = SCALAR;
3597       VEC_safe_push (ce_s, heap, *results, &rhsc);
3598     }
3599
3600   /* May return arguments.  */
3601   for (k = 0; k < gimple_call_num_args (stmt); ++k)
3602     {
3603       tree arg = gimple_call_arg (stmt, k);
3604
3605       if (could_have_pointers (arg))
3606         {
3607           VEC(ce_s, heap) *argc = NULL;
3608           struct constraint_expr *argp;
3609           int i;
3610
3611           /* We always use a temporary here, otherwise we end up with
3612              a quadratic amount of constraints for
3613                large_struct = const_call (large_struct);
3614              with field-sensitive PTA.  */
3615           if (tmpvar == NULL_TREE)
3616             {
3617               tmpvar = create_tmp_var_raw (ptr_type_node, "consttmp");
3618               tmpc = get_constraint_exp_for_temp (tmpvar);
3619             }
3620
3621           get_constraint_for (arg, &argc);
3622           for (i = 0; VEC_iterate (ce_s, argc, i, argp); i++)
3623             process_constraint (new_constraint (tmpc, *argp));
3624           VEC_free (ce_s, heap, argc);
3625         }
3626     }
3627   if (tmpvar != NULL_TREE)
3628     VEC_safe_push (ce_s, heap, *results, &tmpc);
3629
3630   /* May return addresses of globals.  */
3631   rhsc.var = nonlocal_id;
3632   rhsc.offset = 0;
3633   rhsc.type = ADDRESSOF;
3634   VEC_safe_push (ce_s, heap, *results, &rhsc);
3635 }
3636
3637 /* For non-IPA mode, generate constraints necessary for a call to a
3638    pure function in statement STMT.  */
3639
3640 static void
3641 handle_pure_call (gimple stmt, VEC(ce_s, heap) **results)
3642 {
3643   struct constraint_expr rhsc;
3644   unsigned i;
3645   bool need_callused = false;
3646
3647   /* Memory reached from pointer arguments is call-used.  */
3648   for (i = 0; i < gimple_call_num_args (stmt); ++i)
3649     {
3650       tree arg = gimple_call_arg (stmt, i);
3651
3652       if (could_have_pointers (arg))
3653         {
3654           make_constraint_to (callused_id, arg);
3655           need_callused = true;
3656         }
3657     }
3658
3659   /* The static chain is used as well.  */
3660   if (gimple_call_chain (stmt))
3661     {
3662       make_constraint_to (callused_id, gimple_call_chain (stmt));
3663       need_callused = true;
3664     }
3665
3666   /* Pure functions may return callused and escaped memory.  */
3667   if (need_callused)
3668     {
3669       rhsc.var = callused_id;
3670       rhsc.offset = 0;
3671       rhsc.type = SCALAR;
3672       VEC_safe_push (ce_s, heap, *results, &rhsc);
3673     }
3674   rhsc.var = escaped_id;
3675   rhsc.offset = 0;
3676   rhsc.type = ADDRESSOF;
3677   VEC_safe_push (ce_s, heap, *results, &rhsc);
3678 }
3679
3680 /* Walk statement T setting up aliasing constraints according to the
3681    references found in T.  This function is the main part of the
3682    constraint builder.  AI points to auxiliary alias information used
3683    when building alias sets and computing alias grouping heuristics.  */
3684
3685 static void
3686 find_func_aliases (gimple origt)
3687 {
3688   gimple t = origt;
3689   VEC(ce_s, heap) *lhsc = NULL;
3690   VEC(ce_s, heap) *rhsc = NULL;
3691   struct constraint_expr *c;
3692   enum escape_type stmt_escape_type;
3693
3694   /* Now build constraints expressions.  */
3695   if (gimple_code (t) == GIMPLE_PHI)
3696     {
3697       gcc_assert (!AGGREGATE_TYPE_P (TREE_TYPE (gimple_phi_result (t))));
3698
3699       /* Only care about pointers and structures containing
3700          pointers.  */
3701       if (could_have_pointers (gimple_phi_result (t)))
3702         {
3703           size_t i;
3704           unsigned int j;
3705
3706           /* For a phi node, assign all the arguments to
3707              the result.  */
3708           get_constraint_for (gimple_phi_result (t), &lhsc);
3709           for (i = 0; i < gimple_phi_num_args (t); i++)
3710             {
3711               tree rhstype;
3712               tree strippedrhs = PHI_ARG_DEF (t, i);
3713
3714               STRIP_NOPS (strippedrhs);
3715               rhstype = TREE_TYPE (strippedrhs);
3716               get_constraint_for (gimple_phi_arg_def (t, i), &rhsc);
3717
3718               for (j = 0; VEC_iterate (ce_s, lhsc, j, c); j++)
3719                 {
3720                   struct constraint_expr *c2;
3721                   while (VEC_length (ce_s, rhsc) > 0)
3722                     {
3723                       c2 = VEC_last (ce_s, rhsc);
3724                       process_constraint (new_constraint (*c, *c2));
3725                       VEC_pop (ce_s, rhsc);
3726                     }
3727                 }
3728             }
3729         }
3730     }
3731   /* In IPA mode, we need to generate constraints to pass call
3732      arguments through their calls.   There are two cases,
3733      either a GIMPLE_CALL returning a value, or just a plain
3734      GIMPLE_CALL when we are not.
3735
3736      In non-ipa mode, we need to generate constraints for each
3737      pointer passed by address.  */
3738   else if (is_gimple_call (t))
3739     {
3740       if (!in_ipa_mode)
3741         {
3742           VEC(ce_s, heap) *rhsc = NULL;
3743           int flags = gimple_call_flags (t);
3744
3745           /* Const functions can return their arguments and addresses
3746              of global memory but not of escaped memory.  */
3747           if (flags & (ECF_CONST|ECF_NOVOPS))
3748             {
3749               if (gimple_call_lhs (t)
3750                   && could_have_pointers (gimple_call_lhs (t)))
3751                 handle_const_call (t, &rhsc);
3752             }
3753           /* Pure functions can return addresses in and of memory
3754              reachable from their arguments, but they are not an escape
3755              point for reachable memory of their arguments.  */
3756           else if (flags & (ECF_PURE|ECF_LOOPING_CONST_OR_PURE))
3757             handle_pure_call (t, &rhsc);
3758           else
3759             handle_rhs_call (t, &rhsc);
3760           if (gimple_call_lhs (t)
3761               && could_have_pointers (gimple_call_lhs (t)))
3762             handle_lhs_call (gimple_call_lhs (t), flags, rhsc);
3763           VEC_free (ce_s, heap, rhsc);
3764         }
3765       else
3766         {
3767           tree lhsop;
3768           varinfo_t fi;
3769           int i = 1;
3770           size_t j;
3771           tree decl;
3772
3773           lhsop = gimple_call_lhs (t);
3774           decl = gimple_call_fndecl (t);
3775
3776           /* If we can directly resolve the function being called, do so.
3777              Otherwise, it must be some sort of indirect expression that
3778              we should still be able to handle.  */
3779           if (decl)
3780             fi = get_vi_for_tree (decl);
3781           else
3782             {
3783               decl = gimple_call_fn (t);
3784               fi = get_vi_for_tree (decl);
3785             }
3786
3787           /* Assign all the passed arguments to the appropriate incoming
3788              parameters of the function.  */
3789           for (j = 0; j < gimple_call_num_args (t); j++)
3790             {
3791               struct constraint_expr lhs ;
3792               struct constraint_expr *rhsp;
3793               tree arg = gimple_call_arg (t, j);
3794
3795               get_constraint_for (arg, &rhsc);
3796               if (TREE_CODE (decl) != FUNCTION_DECL)
3797                 {
3798                   lhs.type = DEREF;
3799                   lhs.var = fi->id;
3800                   lhs.offset = i;
3801                 }
3802               else
3803                 {
3804                   lhs.type = SCALAR;
3805                   lhs.var = first_vi_for_offset (fi, i)->id;
3806                   lhs.offset = 0;
3807                 }
3808               while (VEC_length (ce_s, rhsc) != 0)
3809                 {
3810                   rhsp = VEC_last (ce_s, rhsc);
3811                   process_constraint (new_constraint (lhs, *rhsp));
3812                   VEC_pop (ce_s, rhsc);
3813                 }
3814               i++;
3815             }
3816
3817           /* If we are returning a value, assign it to the result.  */
3818           if (lhsop)
3819             {
3820               struct constraint_expr rhs;
3821               struct constraint_expr *lhsp;
3822               unsigned int j = 0;
3823
3824               get_constraint_for (lhsop, &lhsc);
3825               if (TREE_CODE (decl) != FUNCTION_DECL)
3826                 {
3827                   rhs.type = DEREF;
3828                   rhs.var = fi->id;
3829                   rhs.offset = i;
3830                 }
3831               else
3832                 {
3833                   rhs.type = SCALAR;
3834                   rhs.var = first_vi_for_offset (fi, i)->id;
3835                   rhs.offset = 0;
3836                 }
3837               for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp); j++)
3838                 process_constraint (new_constraint (*lhsp, rhs));
3839             }
3840         }
3841     }
3842   /* Otherwise, just a regular assignment statement.  Only care about
3843      operations with pointer result, others are dealt with as escape
3844      points if they have pointer operands.  */
3845   else if (is_gimple_assign (t)
3846            && could_have_pointers (gimple_assign_lhs (t)))
3847     {
3848       /* Otherwise, just a regular assignment statement.  */
3849       tree lhsop = gimple_assign_lhs (t);
3850       tree rhsop = (gimple_num_ops (t) == 2) ? gimple_assign_rhs1 (t) : NULL;
3851
3852       if (rhsop && AGGREGATE_TYPE_P (TREE_TYPE (lhsop)))
3853         do_structure_copy (lhsop, rhsop);
3854       else
3855         {
3856           unsigned int j;
3857           struct constraint_expr temp;
3858           get_constraint_for (lhsop, &lhsc);
3859
3860           if (gimple_assign_rhs_code (t) == POINTER_PLUS_EXPR)
3861             get_constraint_for_ptr_offset (gimple_assign_rhs1 (t),
3862                                            gimple_assign_rhs2 (t), &rhsc);
3863           else if ((CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (t))
3864                     && !(POINTER_TYPE_P (gimple_expr_type (t))
3865                          && !POINTER_TYPE_P (TREE_TYPE (rhsop))))
3866                    || gimple_assign_single_p (t))
3867             get_constraint_for (rhsop, &rhsc);
3868           else
3869             {
3870               temp.type = ADDRESSOF;
3871               temp.var = anything_id;
3872               temp.offset = 0;
3873               VEC_safe_push (ce_s, heap, rhsc, &temp);
3874             }
3875           for (j = 0; VEC_iterate (ce_s, lhsc, j, c); j++)
3876             {
3877               struct constraint_expr *c2;
3878               unsigned int k;
3879
3880               for (k = 0; VEC_iterate (ce_s, rhsc, k, c2); k++)
3881                 process_constraint (new_constraint (*c, *c2));
3882             }
3883         }
3884     }
3885   else if (gimple_code (t) == GIMPLE_CHANGE_DYNAMIC_TYPE)
3886     {
3887       unsigned int j;
3888
3889       get_constraint_for (gimple_cdt_location (t), &lhsc);
3890       for (j = 0; VEC_iterate (ce_s, lhsc, j, c); ++j)
3891         get_varinfo (c->var)->no_tbaa_pruning = true;
3892     }
3893
3894   stmt_escape_type = is_escape_site (t);
3895   if (stmt_escape_type == ESCAPE_STORED_IN_GLOBAL)
3896     {
3897       gcc_assert (is_gimple_assign (t));
3898       if (gimple_assign_rhs_code (t) == ADDR_EXPR)
3899         {
3900           tree rhs = gimple_assign_rhs1 (t);
3901           tree base = get_base_address (TREE_OPERAND (rhs, 0));
3902           if (base
3903               && (!DECL_P (base)
3904                   || !is_global_var (base)))
3905             make_escape_constraint (rhs);
3906         }
3907       else if (get_gimple_rhs_class (gimple_assign_rhs_code (t))
3908                == GIMPLE_SINGLE_RHS)
3909         {
3910           if (could_have_pointers (gimple_assign_rhs1 (t)))
3911             make_escape_constraint (gimple_assign_rhs1 (t));
3912         }
3913       else
3914         gcc_unreachable ();
3915     }
3916   else if (stmt_escape_type == ESCAPE_BAD_CAST)
3917     {
3918       gcc_assert (is_gimple_assign (t));
3919       gcc_assert (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (t))
3920                   || gimple_assign_rhs_code (t) == VIEW_CONVERT_EXPR);
3921       make_escape_constraint (gimple_assign_rhs1 (t));
3922     }
3923   else if (stmt_escape_type == ESCAPE_TO_ASM)
3924     {
3925       unsigned i;
3926       for (i = 0; i < gimple_asm_noutputs (t); ++i)
3927         {
3928           tree op = TREE_VALUE (gimple_asm_output_op (t, i));
3929           if (op && could_have_pointers (op))
3930             /* Strictly we'd only need the constraints from ESCAPED and
3931                NONLOCAL.  */
3932             make_escape_constraint (op);
3933         }
3934       for (i = 0; i < gimple_asm_ninputs (t); ++i)
3935         {
3936           tree op = TREE_VALUE (gimple_asm_input_op (t, i));
3937           if (op && could_have_pointers (op))
3938             /* Strictly we'd only need the constraint to ESCAPED.  */
3939             make_escape_constraint (op);
3940         }
3941     }
3942
3943   /* After promoting variables and computing aliasing we will
3944      need to re-scan most statements.  FIXME: Try to minimize the
3945      number of statements re-scanned.  It's not really necessary to
3946      re-scan *all* statements.  */
3947   if (!in_ipa_mode)
3948     gimple_set_modified (origt, true);
3949   VEC_free (ce_s, heap, rhsc);
3950   VEC_free (ce_s, heap, lhsc);
3951 }
3952
3953
3954 /* Find the first varinfo in the same variable as START that overlaps with
3955    OFFSET.
3956    Effectively, walk the chain of fields for the variable START to find the
3957    first field that overlaps with OFFSET.
3958    Return NULL if we can't find one.  */
3959
3960 static varinfo_t
3961 first_vi_for_offset (varinfo_t start, unsigned HOST_WIDE_INT offset)
3962 {
3963   varinfo_t curr = start;
3964   while (curr)
3965     {
3966       /* We may not find a variable in the field list with the actual
3967          offset when when we have glommed a structure to a variable.
3968          In that case, however, offset should still be within the size
3969          of the variable. */
3970       if (offset >= curr->offset && offset < (curr->offset +  curr->size))
3971         return curr;
3972       curr = curr->next;
3973     }
3974   return NULL;
3975 }
3976
3977
3978 /* Insert the varinfo FIELD into the field list for BASE, at the front
3979    of the list.  */
3980
3981 static void
3982 insert_into_field_list (varinfo_t base, varinfo_t field)
3983 {
3984   varinfo_t prev = base;
3985   varinfo_t curr = base->next;
3986
3987   field->next = curr;
3988   prev->next = field;
3989 }
3990
3991 /* Insert the varinfo FIELD into the field list for BASE, ordered by
3992    offset.  */
3993
3994 static void
3995 insert_into_field_list_sorted (varinfo_t base, varinfo_t field)
3996 {
3997   varinfo_t prev = base;
3998   varinfo_t curr = base->next;
3999
4000   if (curr == NULL)
4001     {
4002       prev->next = field;
4003       field->next = NULL;
4004     }
4005   else
4006     {
4007       while (curr)
4008         {
4009           if (field->offset <= curr->offset)
4010             break;
4011           prev = curr;
4012           curr = curr->next;
4013         }
4014       field->next = prev->next;
4015       prev->next = field;
4016     }
4017 }
4018
4019 /* This structure is used during pushing fields onto the fieldstack
4020    to track the offset of the field, since bitpos_of_field gives it
4021    relative to its immediate containing type, and we want it relative
4022    to the ultimate containing object.  */
4023
4024 struct fieldoff
4025 {
4026   /* Offset from the base of the base containing object to this field.  */
4027   HOST_WIDE_INT offset;
4028
4029   /* Size, in bits, of the field.  */
4030   unsigned HOST_WIDE_INT size;
4031
4032   unsigned has_unknown_size : 1;
4033
4034   unsigned may_have_pointers : 1;
4035 };
4036 typedef struct fieldoff fieldoff_s;
4037
4038 DEF_VEC_O(fieldoff_s);
4039 DEF_VEC_ALLOC_O(fieldoff_s,heap);
4040
4041 /* qsort comparison function for two fieldoff's PA and PB */
4042
4043 static int
4044 fieldoff_compare (const void *pa, const void *pb)
4045 {
4046   const fieldoff_s *foa = (const fieldoff_s *)pa;
4047   const fieldoff_s *fob = (const fieldoff_s *)pb;
4048   unsigned HOST_WIDE_INT foasize, fobsize;
4049
4050   if (foa->offset < fob->offset)
4051     return -1;
4052   else if (foa->offset > fob->offset)
4053     return 1;
4054
4055   foasize = foa->size;
4056   fobsize = fob->size;
4057   if (foasize < fobsize)
4058     return -1;
4059   else if (foasize > fobsize)
4060     return 1;
4061   return 0;
4062 }
4063
4064 /* Sort a fieldstack according to the field offset and sizes.  */
4065 static void
4066 sort_fieldstack (VEC(fieldoff_s,heap) *fieldstack)
4067 {
4068   qsort (VEC_address (fieldoff_s, fieldstack),
4069          VEC_length (fieldoff_s, fieldstack),
4070          sizeof (fieldoff_s),
4071          fieldoff_compare);
4072 }
4073
4074 /* Return true if V is a tree that we can have subvars for.
4075    Normally, this is any aggregate type.  Also complex
4076    types which are not gimple registers can have subvars.  */
4077
4078 static inline bool
4079 var_can_have_subvars (const_tree v)
4080 {
4081   /* Volatile variables should never have subvars.  */
4082   if (TREE_THIS_VOLATILE (v))
4083     return false;
4084
4085   /* Non decls or memory tags can never have subvars.  */
4086   if (!DECL_P (v) || MTAG_P (v))
4087     return false;
4088
4089   /* Aggregates without overlapping fields can have subvars.  */
4090   if (TREE_CODE (TREE_TYPE (v)) == RECORD_TYPE)
4091     return true;
4092
4093   return false;
4094 }
4095
4096 /* Given a TYPE, and a vector of field offsets FIELDSTACK, push all
4097    the fields of TYPE onto fieldstack, recording their offsets along
4098    the way.
4099
4100    OFFSET is used to keep track of the offset in this entire
4101    structure, rather than just the immediately containing structure.
4102    Returns the number of fields pushed.  */
4103
4104 static int
4105 push_fields_onto_fieldstack (tree type, VEC(fieldoff_s,heap) **fieldstack,
4106                              HOST_WIDE_INT offset)
4107 {
4108   tree field;
4109   int count = 0;
4110
4111   if (TREE_CODE (type) != RECORD_TYPE)
4112     return 0;
4113
4114   /* If the vector of fields is growing too big, bail out early.
4115      Callers check for VEC_length <= MAX_FIELDS_FOR_FIELD_SENSITIVE, make
4116      sure this fails.  */
4117   if (VEC_length (fieldoff_s, *fieldstack) > MAX_FIELDS_FOR_FIELD_SENSITIVE)
4118     return 0;
4119
4120   for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
4121     if (TREE_CODE (field) == FIELD_DECL)
4122       {
4123         bool push = false;
4124         int pushed = 0;
4125         HOST_WIDE_INT foff = bitpos_of_field (field);
4126
4127         if (!var_can_have_subvars (field)
4128             || TREE_CODE (TREE_TYPE (field)) == QUAL_UNION_TYPE
4129             || TREE_CODE (TREE_TYPE (field)) == UNION_TYPE)
4130           push = true;
4131         else if (!(pushed = push_fields_onto_fieldstack
4132                    (TREE_TYPE (field), fieldstack, offset + foff))
4133                  && (DECL_SIZE (field)
4134                      && !integer_zerop (DECL_SIZE (field))))
4135           /* Empty structures may have actual size, like in C++.  So
4136              see if we didn't push any subfields and the size is
4137              nonzero, push the field onto the stack.  */
4138           push = true;
4139
4140         if (push)
4141           {
4142             fieldoff_s *pair = NULL;
4143             bool has_unknown_size = false;
4144
4145             if (!VEC_empty (fieldoff_s, *fieldstack))
4146               pair = VEC_last (fieldoff_s, *fieldstack);
4147
4148             if (!DECL_SIZE (field)
4149                 || !host_integerp (DECL_SIZE (field), 1))
4150               has_unknown_size = true;
4151
4152             /* If adjacent fields do not contain pointers merge them.  */
4153             if (pair
4154                 && !pair->may_have_pointers
4155                 && !could_have_pointers (field)
4156                 && !pair->has_unknown_size
4157                 && !has_unknown_size
4158                 && pair->offset + (HOST_WIDE_INT)pair->size == offset + foff)
4159               {
4160                 pair = VEC_last (fieldoff_s, *fieldstack);
4161                 pair->size += TREE_INT_CST_LOW (DECL_SIZE (field));
4162               }
4163             else
4164               {
4165                 pair = VEC_safe_push (fieldoff_s, heap, *fieldstack, NULL);
4166                 pair->offset = offset + foff;
4167                 pair->has_unknown_size = has_unknown_size;
4168                 if (!has_unknown_size)
4169                   pair->size = TREE_INT_CST_LOW (DECL_SIZE (field));
4170                 else
4171                   pair->size = -1;
4172                 pair->may_have_pointers = could_have_pointers (field);
4173                 count++;
4174               }
4175           }
4176         else
4177           count += pushed;
4178       }
4179
4180   return count;
4181 }
4182
4183 /* Create a constraint ID = &FROM.  */
4184
4185 static void
4186 make_constraint_from (varinfo_t vi, int from)
4187 {
4188   struct constraint_expr lhs, rhs;
4189
4190   lhs.var = vi->id;
4191   lhs.offset = 0;
4192   lhs.type = SCALAR;
4193
4194   rhs.var = from;
4195   rhs.offset = 0;
4196   rhs.type = ADDRESSOF;
4197   process_constraint (new_constraint (lhs, rhs));
4198 }
4199
4200 /* Count the number of arguments DECL has, and set IS_VARARGS to true
4201    if it is a varargs function.  */
4202
4203 static unsigned int
4204 count_num_arguments (tree decl, bool *is_varargs)
4205 {
4206   unsigned int i = 0;
4207   tree t;
4208
4209   for (t = TYPE_ARG_TYPES (TREE_TYPE (decl));
4210        t;
4211        t = TREE_CHAIN (t))
4212     {
4213       if (TREE_VALUE (t) == void_type_node)
4214         break;
4215       i++;
4216     }
4217
4218   if (!t)
4219     *is_varargs = true;
4220   return i;
4221 }
4222
4223 /* Creation function node for DECL, using NAME, and return the index
4224    of the variable we've created for the function.  */
4225
4226 static unsigned int
4227 create_function_info_for (tree decl, const char *name)
4228 {
4229   unsigned int index = VEC_length (varinfo_t, varmap);
4230   varinfo_t vi;
4231   tree arg;
4232   unsigned int i;
4233   bool is_varargs = false;
4234
4235   /* Create the variable info.  */
4236
4237   vi = new_var_info (decl, index, name);
4238   vi->decl = decl;
4239   vi->offset = 0;
4240   vi->size = 1;
4241   vi->fullsize = count_num_arguments (decl, &is_varargs) + 1;
4242   insert_vi_for_tree (vi->decl, vi);
4243   VEC_safe_push (varinfo_t, heap, varmap, vi);
4244
4245   stats.total_vars++;
4246
4247   /* If it's varargs, we don't know how many arguments it has, so we
4248      can't do much.  */
4249   if (is_varargs)
4250     {
4251       vi->fullsize = ~0;
4252       vi->size = ~0;
4253       vi->is_unknown_size_var = true;
4254       return index;
4255     }
4256
4257
4258   arg = DECL_ARGUMENTS (decl);
4259
4260   /* Set up variables for each argument.  */
4261   for (i = 1; i < vi->fullsize; i++)
4262     {
4263       varinfo_t argvi;
4264       const char *newname;
4265       char *tempname;
4266       unsigned int newindex;
4267       tree argdecl = decl;
4268
4269       if (arg)
4270         argdecl = arg;
4271
4272       newindex = VEC_length (varinfo_t, varmap);
4273       asprintf (&tempname, "%s.arg%d", name, i-1);
4274       newname = ggc_strdup (tempname);
4275       free (tempname);
4276
4277       argvi = new_var_info (argdecl, newindex, newname);
4278       argvi->decl = argdecl;
4279       VEC_safe_push (varinfo_t, heap, varmap, argvi);
4280       argvi->offset = i;
4281       argvi->size = 1;
4282       argvi->is_full_var = true;
4283       argvi->fullsize = vi->fullsize;
4284       insert_into_field_list_sorted (vi, argvi);
4285       stats.total_vars ++;
4286       if (arg)
4287         {
4288           insert_vi_for_tree (arg, argvi);
4289           arg = TREE_CHAIN (arg);
4290         }
4291     }
4292
4293   /* Create a variable for the return var.  */
4294   if (DECL_RESULT (decl) != NULL
4295       || !VOID_TYPE_P (TREE_TYPE (TREE_TYPE (decl))))
4296     {
4297       varinfo_t resultvi;
4298       const char *newname;
4299       char *tempname;
4300       unsigned int newindex;
4301       tree resultdecl = decl;
4302
4303       vi->fullsize ++;
4304
4305       if (DECL_RESULT (decl))
4306         resultdecl = DECL_RESULT (decl);
4307
4308       newindex = VEC_length (varinfo_t, varmap);
4309       asprintf (&tempname, "%s.result", name);
4310       newname = ggc_strdup (tempname);
4311       free (tempname);
4312
4313       resultvi = new_var_info (resultdecl, newindex, newname);
4314       resultvi->decl = resultdecl;
4315       VEC_safe_push (varinfo_t, heap, varmap, resultvi);
4316       resultvi->offset = i;
4317       resultvi->size = 1;
4318       resultvi->fullsize = vi->fullsize;
4319       resultvi->is_full_var = true;
4320       insert_into_field_list_sorted (vi, resultvi);
4321       stats.total_vars ++;
4322       if (DECL_RESULT (decl))
4323         insert_vi_for_tree (DECL_RESULT (decl), resultvi);
4324     }
4325   return index;
4326 }
4327
4328
4329 /* Return true if FIELDSTACK contains fields that overlap.
4330    FIELDSTACK is assumed to be sorted by offset.  */
4331
4332 static bool
4333 check_for_overlaps (VEC (fieldoff_s,heap) *fieldstack)
4334 {
4335   fieldoff_s *fo = NULL;
4336   unsigned int i;
4337   HOST_WIDE_INT lastoffset = -1;
4338
4339   for (i = 0; VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
4340     {
4341       if (fo->offset == lastoffset)
4342         return true;
4343       lastoffset = fo->offset;
4344     }
4345   return false;
4346 }
4347
4348 /* Create a varinfo structure for NAME and DECL, and add it to VARMAP.
4349    This will also create any varinfo structures necessary for fields
4350    of DECL.  */
4351
4352 static unsigned int
4353 create_variable_info_for (tree decl, const char *name)
4354 {
4355   unsigned int index = VEC_length (varinfo_t, varmap);
4356   varinfo_t vi;
4357   tree decl_type = TREE_TYPE (decl);
4358   tree declsize = DECL_P (decl) ? DECL_SIZE (decl) : TYPE_SIZE (decl_type);
4359   bool is_global = DECL_P (decl) ? is_global_var (decl) : false;
4360   VEC (fieldoff_s,heap) *fieldstack = NULL;
4361
4362   if (TREE_CODE (decl) == FUNCTION_DECL && in_ipa_mode)
4363     return create_function_info_for (decl, name);
4364
4365   if (var_can_have_subvars (decl) && use_field_sensitive
4366       && (!var_ann (decl)
4367           || var_ann (decl)->noalias_state == 0)
4368       && (!var_ann (decl)
4369           || !var_ann (decl)->is_heapvar))
4370     push_fields_onto_fieldstack (decl_type, &fieldstack, 0);
4371
4372   /* If the variable doesn't have subvars, we may end up needing to
4373      sort the field list and create fake variables for all the
4374      fields.  */
4375   vi = new_var_info (decl, index, name);
4376   vi->decl = decl;
4377   vi->offset = 0;
4378   vi->may_have_pointers = could_have_pointers (decl);
4379   if (!declsize
4380       || !host_integerp (declsize, 1))
4381     {
4382       vi->is_unknown_size_var = true;
4383       vi->fullsize = ~0;
4384       vi->size = ~0;
4385     }
4386   else
4387     {
4388       vi->fullsize = TREE_INT_CST_LOW (declsize);
4389       vi->size = vi->fullsize;
4390     }
4391
4392   insert_vi_for_tree (vi->decl, vi);
4393   VEC_safe_push (varinfo_t, heap, varmap, vi);
4394   if (is_global && (!flag_whole_program || !in_ipa_mode)
4395       && vi->may_have_pointers)
4396     {
4397       if (var_ann (decl)
4398           && var_ann (decl)->noalias_state == NO_ALIAS_ANYTHING)
4399         make_constraint_from (vi, vi->id);
4400       else
4401         make_constraint_from (vi, escaped_id);
4402     }
4403
4404   stats.total_vars++;
4405   if (use_field_sensitive
4406       && !vi->is_unknown_size_var
4407       && var_can_have_subvars (decl)
4408       && VEC_length (fieldoff_s, fieldstack) > 1
4409       && VEC_length (fieldoff_s, fieldstack) <= MAX_FIELDS_FOR_FIELD_SENSITIVE)
4410     {
4411       unsigned int newindex = VEC_length (varinfo_t, varmap);
4412       fieldoff_s *fo = NULL;
4413       bool notokay = false;
4414       unsigned int i;
4415
4416       for (i = 0; !notokay && VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
4417         {
4418           if (fo->has_unknown_size
4419               || fo->offset < 0)
4420             {
4421               notokay = true;
4422               break;
4423             }
4424         }
4425
4426       /* We can't sort them if we have a field with a variable sized type,
4427          which will make notokay = true.  In that case, we are going to return
4428          without creating varinfos for the fields anyway, so sorting them is a
4429          waste to boot.  */
4430       if (!notokay)
4431         {
4432           sort_fieldstack (fieldstack);
4433           /* Due to some C++ FE issues, like PR 22488, we might end up
4434              what appear to be overlapping fields even though they,
4435              in reality, do not overlap.  Until the C++ FE is fixed,
4436              we will simply disable field-sensitivity for these cases.  */
4437           notokay = check_for_overlaps (fieldstack);
4438         }
4439
4440
4441       if (VEC_length (fieldoff_s, fieldstack) != 0)
4442         fo = VEC_index (fieldoff_s, fieldstack, 0);
4443
4444       if (fo == NULL || notokay)
4445         {
4446           vi->is_unknown_size_var = 1;
4447           vi->fullsize = ~0;
4448           vi->size = ~0;
4449           vi->is_full_var = true;
4450           VEC_free (fieldoff_s, heap, fieldstack);
4451           return index;
4452         }
4453
4454       vi->size = fo->size;
4455       vi->offset = fo->offset;
4456       vi->may_have_pointers = fo->may_have_pointers;
4457       for (i = VEC_length (fieldoff_s, fieldstack) - 1;
4458            i >= 1 && VEC_iterate (fieldoff_s, fieldstack, i, fo);
4459            i--)
4460         {
4461           varinfo_t newvi;
4462           const char *newname = "NULL";
4463           char *tempname;
4464
4465           newindex = VEC_length (varinfo_t, varmap);
4466           if (dump_file)
4467             {
4468               asprintf (&tempname, "%s." HOST_WIDE_INT_PRINT_DEC
4469                         "+" HOST_WIDE_INT_PRINT_DEC,
4470                         vi->name, fo->offset, fo->size);
4471               newname = ggc_strdup (tempname);
4472               free (tempname);
4473             }
4474           newvi = new_var_info (decl, newindex, newname);
4475           newvi->offset = fo->offset;
4476           newvi->size = fo->size;
4477           newvi->fullsize = vi->fullsize;
4478           newvi->may_have_pointers = fo->may_have_pointers;
4479           insert_into_field_list (vi, newvi);
4480           VEC_safe_push (varinfo_t, heap, varmap, newvi);
4481           if (is_global && (!flag_whole_program || !in_ipa_mode)
4482               && newvi->may_have_pointers)
4483             make_constraint_from (newvi, escaped_id);
4484
4485           stats.total_vars++;
4486         }
4487     }
4488   else
4489     vi->is_full_var = true;
4490
4491   VEC_free (fieldoff_s, heap, fieldstack);
4492
4493   return index;
4494 }
4495
4496 /* Print out the points-to solution for VAR to FILE.  */
4497
4498 void
4499 dump_solution_for_var (FILE *file, unsigned int var)
4500 {
4501   varinfo_t vi = get_varinfo (var);
4502   unsigned int i;
4503   bitmap_iterator bi;
4504
4505   if (find (var) != var)
4506     {
4507       varinfo_t vipt = get_varinfo (find (var));
4508       fprintf (file, "%s = same as %s\n", vi->name, vipt->name);
4509     }
4510   else
4511     {
4512       fprintf (file, "%s = { ", vi->name);
4513       EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
4514         {
4515           fprintf (file, "%s ", get_varinfo (i)->name);
4516         }
4517       fprintf (file, "}");
4518       if (vi->no_tbaa_pruning)
4519         fprintf (file, " no-tbaa-pruning");
4520       fprintf (file, "\n");
4521     }
4522 }
4523
4524 /* Print the points-to solution for VAR to stdout.  */
4525
4526 void
4527 debug_solution_for_var (unsigned int var)
4528 {
4529   dump_solution_for_var (stdout, var);
4530 }
4531
4532 /* Create varinfo structures for all of the variables in the
4533    function for intraprocedural mode.  */
4534
4535 static void
4536 intra_create_variable_infos (void)
4537 {
4538   tree t;
4539   struct constraint_expr lhs, rhs;
4540
4541   /* For each incoming pointer argument arg, create the constraint ARG
4542      = NONLOCAL or a dummy variable if flag_argument_noalias is set.  */
4543   for (t = DECL_ARGUMENTS (current_function_decl); t; t = TREE_CHAIN (t))
4544     {
4545       varinfo_t p;
4546
4547       if (!could_have_pointers (t))
4548         continue;
4549
4550       /* If flag_argument_noalias is set, then function pointer
4551          arguments are guaranteed not to point to each other.  In that
4552          case, create an artificial variable PARM_NOALIAS and the
4553          constraint ARG = &PARM_NOALIAS.  */
4554       if (POINTER_TYPE_P (TREE_TYPE (t)) && flag_argument_noalias > 0)
4555         {
4556           varinfo_t vi;
4557           tree heapvar = heapvar_lookup (t);
4558
4559           lhs.offset = 0;
4560           lhs.type = SCALAR;
4561           lhs.var  = get_vi_for_tree (t)->id;
4562
4563           if (heapvar == NULL_TREE)
4564             {
4565               var_ann_t ann;
4566               heapvar = create_tmp_var_raw (ptr_type_node,
4567                                             "PARM_NOALIAS");
4568               DECL_EXTERNAL (heapvar) = 1;
4569               if (gimple_referenced_vars (cfun))
4570                 add_referenced_var (heapvar);
4571
4572               heapvar_insert (t, heapvar);
4573
4574               ann = get_var_ann (heapvar);
4575               ann->is_heapvar = 1;
4576               if (flag_argument_noalias == 1)
4577                 ann->noalias_state = NO_ALIAS;
4578               else if (flag_argument_noalias == 2)
4579                 ann->noalias_state = NO_ALIAS_GLOBAL;
4580               else if (flag_argument_noalias == 3)
4581                 ann->noalias_state = NO_ALIAS_ANYTHING;
4582               else
4583                 gcc_unreachable ();
4584             }
4585
4586           vi = get_vi_for_tree (heapvar);
4587           vi->is_artificial_var = 1;
4588           vi->is_heap_var = 1;
4589           vi->is_unknown_size_var = true;
4590           vi->fullsize = ~0;
4591           vi->size = ~0;
4592           rhs.var = vi->id;
4593           rhs.type = ADDRESSOF;
4594           rhs.offset = 0;
4595           for (p = get_varinfo (lhs.var); p; p = p->next)
4596             {
4597               struct constraint_expr temp = lhs;
4598               temp.var = p->id;
4599               process_constraint (new_constraint (temp, rhs));
4600             }
4601         }
4602       else
4603         {
4604           varinfo_t arg_vi = get_vi_for_tree (t);
4605
4606           for (p = arg_vi; p; p = p->next)
4607             make_constraint_from (p, nonlocal_id);
4608         }
4609     }
4610
4611   /* Add a constraint for a result decl that is passed by reference.  */
4612   if (DECL_RESULT (cfun->decl)
4613       && DECL_BY_REFERENCE (DECL_RESULT (cfun->decl)))
4614     {
4615       varinfo_t p, result_vi = get_vi_for_tree (DECL_RESULT (cfun->decl));
4616
4617       for (p = result_vi; p; p = p->next)
4618         make_constraint_from (p, nonlocal_id);
4619     }
4620
4621   /* Add a constraint for the incoming static chain parameter.  */
4622   if (cfun->static_chain_decl != NULL_TREE)
4623     {
4624       varinfo_t p, chain_vi = get_vi_for_tree (cfun->static_chain_decl);
4625
4626       for (p = chain_vi; p; p = p->next)
4627         make_constraint_from (p, nonlocal_id);
4628     }
4629 }
4630
4631 /* Structure used to put solution bitmaps in a hashtable so they can
4632    be shared among variables with the same points-to set.  */
4633
4634 typedef struct shared_bitmap_info
4635 {
4636   bitmap pt_vars;
4637   hashval_t hashcode;
4638 } *shared_bitmap_info_t;
4639 typedef const struct shared_bitmap_info *const_shared_bitmap_info_t;
4640
4641 static htab_t shared_bitmap_table;
4642
4643 /* Hash function for a shared_bitmap_info_t */
4644
4645 static hashval_t
4646 shared_bitmap_hash (const void *p)
4647 {
4648   const_shared_bitmap_info_t const bi = (const_shared_bitmap_info_t) p;
4649   return bi->hashcode;
4650 }
4651
4652 /* Equality function for two shared_bitmap_info_t's. */
4653
4654 static int
4655 shared_bitmap_eq (const void *p1, const void *p2)
4656 {
4657   const_shared_bitmap_info_t const sbi1 = (const_shared_bitmap_info_t) p1;
4658   const_shared_bitmap_info_t const sbi2 = (const_shared_bitmap_info_t) p2;
4659   return bitmap_equal_p (sbi1->pt_vars, sbi2->pt_vars);
4660 }
4661
4662 /* Lookup a bitmap in the shared bitmap hashtable, and return an already
4663    existing instance if there is one, NULL otherwise.  */
4664
4665 static bitmap
4666 shared_bitmap_lookup (bitmap pt_vars)
4667 {
4668   void **slot;
4669   struct shared_bitmap_info sbi;
4670
4671   sbi.pt_vars = pt_vars;
4672   sbi.hashcode = bitmap_hash (pt_vars);
4673
4674   slot = htab_find_slot_with_hash (shared_bitmap_table, &sbi,
4675                                    sbi.hashcode, NO_INSERT);
4676   if (!slot)
4677     return NULL;
4678   else
4679     return ((shared_bitmap_info_t) *slot)->pt_vars;
4680 }
4681
4682
4683 /* Add a bitmap to the shared bitmap hashtable.  */
4684
4685 static void
4686 shared_bitmap_add (bitmap pt_vars)
4687 {
4688   void **slot;
4689   shared_bitmap_info_t sbi = XNEW (struct shared_bitmap_info);
4690
4691   sbi->pt_vars = pt_vars;
4692   sbi->hashcode = bitmap_hash (pt_vars);
4693
4694   slot = htab_find_slot_with_hash (shared_bitmap_table, sbi,
4695                                    sbi->hashcode, INSERT);
4696   gcc_assert (!*slot);
4697   *slot = (void *) sbi;
4698 }
4699
4700
4701 /* Set bits in INTO corresponding to the variable uids in solution set
4702    FROM, which came from variable PTR.
4703    For variables that are actually dereferenced, we also use type
4704    based alias analysis to prune the points-to sets.
4705    IS_DEREFED is true if PTR was directly dereferenced, which we use to
4706    help determine whether we are we are allowed to prune using TBAA.
4707    If NO_TBAA_PRUNING is true, we do not perform any TBAA pruning of
4708    the from set.  Returns the number of pruned variables.  */
4709
4710 static unsigned
4711 set_uids_in_ptset (tree ptr, bitmap into, bitmap from, bool is_derefed,
4712                    bool no_tbaa_pruning)
4713 {
4714   unsigned int i;
4715   bitmap_iterator bi;
4716   unsigned pruned = 0;
4717
4718   gcc_assert (POINTER_TYPE_P (TREE_TYPE (ptr)));
4719
4720   EXECUTE_IF_SET_IN_BITMAP (from, 0, i, bi)
4721     {
4722       varinfo_t vi = get_varinfo (i);
4723
4724       /* The only artificial variables that are allowed in a may-alias
4725          set are heap variables.  */
4726       if (vi->is_artificial_var && !vi->is_heap_var)
4727         continue;
4728
4729       if (TREE_CODE (vi->decl) == VAR_DECL
4730           || TREE_CODE (vi->decl) == PARM_DECL
4731           || TREE_CODE (vi->decl) == RESULT_DECL)
4732         {
4733           /* Just add VI->DECL to the alias set.
4734              Don't type prune artificial vars or points-to sets
4735              for pointers that have not been dereferenced or with
4736              type-based pruning disabled.  */
4737           if (vi->is_artificial_var
4738               || !is_derefed
4739               || no_tbaa_pruning
4740               || vi->no_tbaa_pruning)
4741             bitmap_set_bit (into, DECL_UID (vi->decl));
4742           else
4743             {
4744               alias_set_type var_alias_set, mem_alias_set;
4745               var_alias_set = get_alias_set (vi->decl);
4746               mem_alias_set = get_alias_set (TREE_TYPE (TREE_TYPE (ptr)));
4747               if (may_alias_p (SSA_NAME_VAR (ptr), mem_alias_set,
4748                                vi->decl, var_alias_set, true))
4749                 bitmap_set_bit (into, DECL_UID (vi->decl));
4750               else
4751                 ++pruned;
4752             }
4753         }
4754     }
4755
4756   return pruned;
4757 }
4758
4759
4760 static bool have_alias_info = false;
4761
4762 /* Emit a note for the pointer initialization point DEF.  */
4763
4764 static void
4765 emit_pointer_definition (tree ptr, bitmap visited)
4766 {
4767   gimple def = SSA_NAME_DEF_STMT (ptr);
4768   if (gimple_code (def) == GIMPLE_PHI)
4769     {
4770       use_operand_p argp;
4771       ssa_op_iter oi;
4772
4773       FOR_EACH_PHI_ARG (argp, def, oi, SSA_OP_USE)
4774         {
4775           tree arg = USE_FROM_PTR (argp);
4776           if (TREE_CODE (arg) == SSA_NAME)
4777             {
4778               if (bitmap_set_bit (visited, SSA_NAME_VERSION (arg)))
4779                 emit_pointer_definition (arg, visited);
4780             }
4781           else
4782             inform (0, "initialized from %qE", arg);
4783         }
4784     }
4785   else if (!gimple_nop_p (def))
4786     inform (gimple_location (def), "initialized from here");
4787 }
4788
4789 /* Emit a strict aliasing warning for dereferencing the pointer PTR.  */
4790
4791 static void
4792 emit_alias_warning (tree ptr)
4793 {
4794   gimple use;
4795   imm_use_iterator ui;
4796   bool warned = false;
4797
4798   FOR_EACH_IMM_USE_STMT (use, ui, ptr)
4799     {
4800       tree deref = NULL_TREE;
4801
4802       if (gimple_has_lhs (use))
4803         {
4804           tree lhs = get_base_address (gimple_get_lhs (use));
4805           if (lhs
4806               && INDIRECT_REF_P (lhs)
4807               && TREE_OPERAND (lhs, 0) == ptr)
4808             deref = lhs;
4809         }
4810       if (gimple_assign_single_p (use))
4811         {
4812           tree rhs = get_base_address (gimple_assign_rhs1 (use));
4813           if (rhs
4814               && INDIRECT_REF_P (rhs)
4815               && TREE_OPERAND (rhs, 0) == ptr)
4816             deref = rhs;
4817         }
4818       else if (is_gimple_call (use))
4819         {
4820           unsigned i;
4821           for (i = 0; i < gimple_call_num_args (use); ++i)
4822             {
4823               tree op = get_base_address (gimple_call_arg (use, i));
4824               if (op
4825                   && INDIRECT_REF_P (op)
4826                   && TREE_OPERAND (op, 0) == ptr)
4827                 deref = op;
4828             }
4829         }
4830       if (deref
4831           && !TREE_NO_WARNING (deref))
4832         {
4833           TREE_NO_WARNING (deref) = 1;
4834           warned |= warning_at (gimple_location (use), OPT_Wstrict_aliasing,
4835                                 "dereferencing pointer %qD does break "
4836                                 "strict-aliasing rules", SSA_NAME_VAR (ptr));
4837         }
4838     }
4839   if (warned)
4840     {
4841       bitmap visited = BITMAP_ALLOC (NULL);
4842       emit_pointer_definition (ptr, visited);
4843       BITMAP_FREE (visited);
4844     }
4845 }
4846
4847 /* Given a pointer variable P, fill in its points-to set, or return
4848    false if we can't.
4849    Rather than return false for variables that point-to anything, we
4850    instead find the corresponding SMT, and merge in its aliases.  In
4851    addition to these aliases, we also set the bits for the SMT's
4852    themselves and their subsets, as SMT's are still in use by
4853    non-SSA_NAME's, and pruning may eliminate every one of their
4854    aliases.  In such a case, if we did not include the right set of
4855    SMT's in the points-to set of the variable, we'd end up with
4856    statements that do not conflict but should.  */
4857
4858 bool
4859 find_what_p_points_to (tree p)
4860 {
4861   tree lookup_p = p;
4862   varinfo_t vi;
4863
4864   if (!have_alias_info)
4865     return false;
4866
4867   /* For parameters, get at the points-to set for the actual parm
4868      decl.  */
4869   if (TREE_CODE (p) == SSA_NAME
4870       && TREE_CODE (SSA_NAME_VAR (p)) == PARM_DECL
4871       && SSA_NAME_IS_DEFAULT_DEF (p))
4872     lookup_p = SSA_NAME_VAR (p);
4873
4874   vi = lookup_vi_for_tree (lookup_p);
4875   if (vi)
4876     {
4877       if (vi->is_artificial_var)
4878         return false;
4879
4880       /* See if this is a field or a structure.  */
4881       if (vi->size != vi->fullsize)
4882         {
4883           /* Nothing currently asks about structure fields directly,
4884              but when they do, we need code here to hand back the
4885              points-to set.  */
4886           return false;
4887         }
4888       else
4889         {
4890           struct ptr_info_def *pi = get_ptr_info (p);
4891           unsigned int i, pruned;
4892           bitmap_iterator bi;
4893           bool was_pt_anything = false;
4894           bitmap finished_solution;
4895           bitmap result;
4896
4897           if (!pi->memory_tag_needed)
4898             return false;
4899
4900           /* This variable may have been collapsed, let's get the real
4901              variable.  */
4902           vi = get_varinfo (find (vi->id));
4903
4904           /* Translate artificial variables into SSA_NAME_PTR_INFO
4905              attributes.  */
4906           EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
4907             {
4908               varinfo_t vi = get_varinfo (i);
4909
4910               if (vi->is_artificial_var)
4911                 {
4912                   /* FIXME.  READONLY should be handled better so that
4913                      flow insensitive aliasing can disregard writable
4914                      aliases.  */
4915                   if (vi->id == nothing_id)
4916                     pi->pt_null = 1;
4917                   else if (vi->id == anything_id
4918                            || vi->id == nonlocal_id
4919                            || vi->id == escaped_id)
4920                     was_pt_anything = 1;
4921                   else if (vi->id == callused_id)
4922                     gcc_unreachable ();
4923                   else if (vi->id == readonly_id)
4924                     was_pt_anything = 1;
4925                   else if (vi->id == integer_id)
4926                     was_pt_anything = 1;
4927                   else if (vi->is_heap_var)
4928                     pi->pt_global_mem = 1;
4929                 }
4930             }
4931
4932           /* Instead of doing extra work, simply do not create
4933              points-to information for pt_anything pointers.  This
4934              will cause the operand scanner to fall back to the
4935              type-based SMT and its aliases.  Which is the best
4936              we could do here for the points-to set as well.  */
4937           if (was_pt_anything)
4938             return false;
4939
4940           /* Share the final set of variables when possible.  */
4941           finished_solution = BITMAP_GGC_ALLOC ();
4942           stats.points_to_sets_created++;
4943
4944           pruned = set_uids_in_ptset (p, finished_solution, vi->solution,
4945                                       pi->is_dereferenced,
4946                                       vi->no_tbaa_pruning);
4947           result = shared_bitmap_lookup (finished_solution);
4948
4949           if (!result)
4950             {
4951               shared_bitmap_add (finished_solution);
4952               pi->pt_vars = finished_solution;
4953             }
4954           else
4955             {
4956               pi->pt_vars = result;
4957               bitmap_clear (finished_solution);
4958             }
4959
4960           if (bitmap_empty_p (pi->pt_vars))
4961             {
4962               pi->pt_vars = NULL;
4963               if (pruned > 0
4964                   && !pi->pt_null
4965                   && pi->is_dereferenced
4966                   && warn_strict_aliasing > 0
4967                   && !SSA_NAME_IS_DEFAULT_DEF (p))
4968                 {
4969                   if (dump_file && dump_flags & TDF_DETAILS)
4970                     {
4971                       fprintf (dump_file, "alias warning for ");
4972                       print_generic_expr (dump_file, p, 0);
4973                       fprintf (dump_file, "\n");
4974                     }
4975                   emit_alias_warning (p);
4976                 }
4977             }
4978
4979           return true;
4980         }
4981     }
4982
4983   return false;
4984 }
4985
4986 /* Mark the ESCAPED solution as call clobbered.  Returns false if
4987    pt_anything escaped which needs all locals that have their address
4988    taken marked call clobbered as well.  */
4989
4990 bool
4991 clobber_what_escaped (void)
4992 {
4993   varinfo_t vi;
4994   unsigned int i;
4995   bitmap_iterator bi;
4996
4997   if (!have_alias_info)
4998     return false;
4999
5000   /* This variable may have been collapsed, let's get the real
5001      variable for escaped_id.  */
5002   vi = get_varinfo (find (escaped_id));
5003
5004   /* If call-used memory escapes we need to include it in the
5005      set of escaped variables.  This can happen if a pure
5006      function returns a pointer and this pointer escapes.  */
5007   if (bitmap_bit_p (vi->solution, callused_id))
5008     {
5009       varinfo_t cu_vi = get_varinfo (find (callused_id));
5010       bitmap_ior_into (vi->solution, cu_vi->solution);
5011     }
5012
5013   /* Mark variables in the solution call-clobbered.  */
5014   EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
5015     {
5016       varinfo_t vi = get_varinfo (i);
5017
5018       if (vi->is_artificial_var)
5019         {
5020           /* nothing_id and readonly_id do not cause any
5021              call clobber ops.  For anything_id and integer_id
5022              we need to clobber all addressable vars.  */
5023           if (vi->id == anything_id
5024               || vi->id == integer_id)
5025             return false;
5026         }
5027
5028       /* Only artificial heap-vars are further interesting.  */
5029       if (vi->is_artificial_var && !vi->is_heap_var)
5030         continue;
5031
5032       if ((TREE_CODE (vi->decl) == VAR_DECL
5033            || TREE_CODE (vi->decl) == PARM_DECL
5034            || TREE_CODE (vi->decl) == RESULT_DECL)
5035           && !unmodifiable_var_p (vi->decl))
5036         mark_call_clobbered (vi->decl, ESCAPE_TO_CALL);
5037     }
5038
5039   return true;
5040 }
5041
5042 /* Compute the call-used variables.  */
5043
5044 void
5045 compute_call_used_vars (void)
5046 {
5047   varinfo_t vi;
5048   unsigned int i;
5049   bitmap_iterator bi;
5050   bool has_anything_id = false;
5051
5052   if (!have_alias_info)
5053     return;
5054
5055   /* This variable may have been collapsed, let's get the real
5056      variable for escaped_id.  */
5057   vi = get_varinfo (find (callused_id));
5058
5059   /* Mark variables in the solution call-clobbered.  */
5060   EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
5061     {
5062       varinfo_t vi = get_varinfo (i);
5063
5064       if (vi->is_artificial_var)
5065         {
5066           /* For anything_id and integer_id we need to make
5067              all local addressable vars call-used.  */
5068           if (vi->id == anything_id
5069               || vi->id == integer_id)
5070             has_anything_id = true;
5071         }
5072
5073       /* Only artificial heap-vars are further interesting.  */
5074       if (vi->is_artificial_var && !vi->is_heap_var)
5075         continue;
5076
5077       if ((TREE_CODE (vi->decl) == VAR_DECL
5078            || TREE_CODE (vi->decl) == PARM_DECL
5079            || TREE_CODE (vi->decl) == RESULT_DECL)
5080           && !unmodifiable_var_p (vi->decl))
5081         bitmap_set_bit (gimple_call_used_vars (cfun), DECL_UID (vi->decl));
5082     }
5083
5084   /* If anything is call-used, add all addressable locals to the set.  */
5085   if (has_anything_id)
5086     bitmap_ior_into (gimple_call_used_vars (cfun),
5087                      gimple_addressable_vars (cfun));
5088 }
5089
5090
5091 /* Dump points-to information to OUTFILE.  */
5092
5093 void
5094 dump_sa_points_to_info (FILE *outfile)
5095 {
5096   unsigned int i;
5097
5098   fprintf (outfile, "\nPoints-to sets\n\n");
5099
5100   if (dump_flags & TDF_STATS)
5101     {
5102       fprintf (outfile, "Stats:\n");
5103       fprintf (outfile, "Total vars:               %d\n", stats.total_vars);
5104       fprintf (outfile, "Non-pointer vars:          %d\n",
5105                stats.nonpointer_vars);
5106       fprintf (outfile, "Statically unified vars:  %d\n",
5107                stats.unified_vars_static);
5108       fprintf (outfile, "Dynamically unified vars: %d\n",
5109                stats.unified_vars_dynamic);
5110       fprintf (outfile, "Iterations:               %d\n", stats.iterations);
5111       fprintf (outfile, "Number of edges:          %d\n", stats.num_edges);
5112       fprintf (outfile, "Number of implicit edges: %d\n",
5113                stats.num_implicit_edges);
5114     }
5115
5116   for (i = 0; i < VEC_length (varinfo_t, varmap); i++)
5117     dump_solution_for_var (outfile, i);
5118 }
5119
5120
5121 /* Debug points-to information to stderr.  */
5122
5123 void
5124 debug_sa_points_to_info (void)
5125 {
5126   dump_sa_points_to_info (stderr);
5127 }
5128
5129
5130 /* Initialize the always-existing constraint variables for NULL
5131    ANYTHING, READONLY, and INTEGER */
5132
5133 static void
5134 init_base_vars (void)
5135 {
5136   struct constraint_expr lhs, rhs;
5137
5138   /* Create the NULL variable, used to represent that a variable points
5139      to NULL.  */
5140   nothing_tree = create_tmp_var_raw (void_type_node, "NULL");
5141   var_nothing = new_var_info (nothing_tree, nothing_id, "NULL");
5142   insert_vi_for_tree (nothing_tree, var_nothing);
5143   var_nothing->is_artificial_var = 1;
5144   var_nothing->offset = 0;
5145   var_nothing->size = ~0;
5146   var_nothing->fullsize = ~0;
5147   var_nothing->is_special_var = 1;
5148   VEC_safe_push (varinfo_t, heap, varmap, var_nothing);
5149
5150   /* Create the ANYTHING variable, used to represent that a variable
5151      points to some unknown piece of memory.  */
5152   anything_tree = create_tmp_var_raw (void_type_node, "ANYTHING");
5153   var_anything = new_var_info (anything_tree, anything_id, "ANYTHING");
5154   insert_vi_for_tree (anything_tree, var_anything);
5155   var_anything->is_artificial_var = 1;
5156   var_anything->size = ~0;
5157   var_anything->offset = 0;
5158   var_anything->next = NULL;
5159   var_anything->fullsize = ~0;
5160   var_anything->is_special_var = 1;
5161
5162   /* Anything points to anything.  This makes deref constraints just
5163      work in the presence of linked list and other p = *p type loops,
5164      by saying that *ANYTHING = ANYTHING. */
5165   VEC_safe_push (varinfo_t, heap, varmap, var_anything);
5166   lhs.type = SCALAR;
5167   lhs.var = anything_id;
5168   lhs.offset = 0;
5169   rhs.type = ADDRESSOF;
5170   rhs.var = anything_id;
5171   rhs.offset = 0;
5172
5173   /* This specifically does not use process_constraint because
5174      process_constraint ignores all anything = anything constraints, since all
5175      but this one are redundant.  */
5176   VEC_safe_push (constraint_t, heap, constraints, new_constraint (lhs, rhs));
5177
5178   /* Create the READONLY variable, used to represent that a variable
5179      points to readonly memory.  */
5180   readonly_tree = create_tmp_var_raw (void_type_node, "READONLY");
5181   var_readonly = new_var_info (readonly_tree, readonly_id, "READONLY");
5182   var_readonly->is_artificial_var = 1;
5183   var_readonly->offset = 0;
5184   var_readonly->size = ~0;
5185   var_readonly->fullsize = ~0;
5186   var_readonly->next = NULL;
5187   var_readonly->is_special_var = 1;
5188   insert_vi_for_tree (readonly_tree, var_readonly);
5189   VEC_safe_push (varinfo_t, heap, varmap, var_readonly);
5190
5191   /* readonly memory points to anything, in order to make deref
5192      easier.  In reality, it points to anything the particular
5193      readonly variable can point to, but we don't track this
5194      separately. */
5195   lhs.type = SCALAR;
5196   lhs.var = readonly_id;
5197   lhs.offset = 0;
5198   rhs.type = ADDRESSOF;
5199   rhs.var = readonly_id;  /* FIXME */
5200   rhs.offset = 0;
5201   process_constraint (new_constraint (lhs, rhs));
5202
5203   /* Create the ESCAPED variable, used to represent the set of escaped
5204      memory.  */
5205   escaped_tree = create_tmp_var_raw (void_type_node, "ESCAPED");
5206   var_escaped = new_var_info (escaped_tree, escaped_id, "ESCAPED");
5207   insert_vi_for_tree (escaped_tree, var_escaped);
5208   var_escaped->is_artificial_var = 1;
5209   var_escaped->offset = 0;
5210   var_escaped->size = ~0;
5211   var_escaped->fullsize = ~0;
5212   var_escaped->is_special_var = 0;
5213   VEC_safe_push (varinfo_t, heap, varmap, var_escaped);
5214   gcc_assert (VEC_index (varinfo_t, varmap, 3) == var_escaped);
5215
5216   /* ESCAPED = *ESCAPED, because escaped is may-deref'd at calls, etc.  */
5217   lhs.type = SCALAR;
5218   lhs.var = escaped_id;
5219   lhs.offset = 0;
5220   rhs.type = DEREF;
5221   rhs.var = escaped_id;
5222   rhs.offset = 0;
5223   process_constraint (new_constraint (lhs, rhs));
5224
5225   /* Create the NONLOCAL variable, used to represent the set of nonlocal
5226      memory.  */
5227   nonlocal_tree = create_tmp_var_raw (void_type_node, "NONLOCAL");
5228   var_nonlocal = new_var_info (nonlocal_tree, nonlocal_id, "NONLOCAL");
5229   insert_vi_for_tree (nonlocal_tree, var_nonlocal);
5230   var_nonlocal->is_artificial_var = 1;
5231   var_nonlocal->offset = 0;
5232   var_nonlocal->size = ~0;
5233   var_nonlocal->fullsize = ~0;
5234   var_nonlocal->is_special_var = 1;
5235   VEC_safe_push (varinfo_t, heap, varmap, var_nonlocal);
5236
5237   /* Nonlocal memory points to escaped (which includes nonlocal),
5238      in order to make deref easier.  */
5239   lhs.type = SCALAR;
5240   lhs.var = nonlocal_id;
5241   lhs.offset = 0;
5242   rhs.type = ADDRESSOF;
5243   rhs.var = escaped_id;
5244   rhs.offset = 0;
5245   process_constraint (new_constraint (lhs, rhs));
5246
5247   /* Create the CALLUSED variable, used to represent the set of call-used
5248      memory.  */
5249   callused_tree = create_tmp_var_raw (void_type_node, "CALLUSED");
5250   var_callused = new_var_info (callused_tree, callused_id, "CALLUSED");
5251   insert_vi_for_tree (callused_tree, var_callused);
5252   var_callused->is_artificial_var = 1;
5253   var_callused->offset = 0;
5254   var_callused->size = ~0;
5255   var_callused->fullsize = ~0;
5256   var_callused->is_special_var = 0;
5257   VEC_safe_push (varinfo_t, heap, varmap, var_callused);
5258
5259   /* CALLUSED = *CALLUSED, because call-used is may-deref'd at calls, etc.  */
5260   lhs.type = SCALAR;
5261   lhs.var = callused_id;
5262   lhs.offset = 0;
5263   rhs.type = DEREF;
5264   rhs.var = callused_id;
5265   rhs.offset = 0;
5266   process_constraint (new_constraint (lhs, rhs));
5267
5268   /* Create the STOREDANYTHING variable, used to represent the set of
5269      variables stored to *ANYTHING.  */
5270   storedanything_tree = create_tmp_var_raw (ptr_type_node, "STOREDANYTHING");
5271   var_storedanything = new_var_info (storedanything_tree, storedanything_id,
5272                                      "STOREDANYTHING");
5273   insert_vi_for_tree (storedanything_tree, var_storedanything);
5274   var_storedanything->is_artificial_var = 1;
5275   var_storedanything->offset = 0;
5276   var_storedanything->size = ~0;
5277   var_storedanything->fullsize = ~0;
5278   var_storedanything->is_special_var = 0;
5279   VEC_safe_push (varinfo_t, heap, varmap, var_storedanything);
5280
5281   /* Create the INTEGER variable, used to represent that a variable points
5282      to an INTEGER.  */
5283   integer_tree = create_tmp_var_raw (void_type_node, "INTEGER");
5284   var_integer = new_var_info (integer_tree, integer_id, "INTEGER");
5285   insert_vi_for_tree (integer_tree, var_integer);
5286   var_integer->is_artificial_var = 1;
5287   var_integer->size = ~0;
5288   var_integer->fullsize = ~0;
5289   var_integer->offset = 0;
5290   var_integer->next = NULL;
5291   var_integer->is_special_var = 1;
5292   VEC_safe_push (varinfo_t, heap, varmap, var_integer);
5293
5294   /* INTEGER = ANYTHING, because we don't know where a dereference of
5295      a random integer will point to.  */
5296   lhs.type = SCALAR;
5297   lhs.var = integer_id;
5298   lhs.offset = 0;
5299   rhs.type = ADDRESSOF;
5300   rhs.var = anything_id;
5301   rhs.offset = 0;
5302   process_constraint (new_constraint (lhs, rhs));
5303
5304   /* *ESCAPED = &ESCAPED.  This is true because we have to assume
5305      everything pointed to by escaped can also point to escaped. */
5306   lhs.type = DEREF;
5307   lhs.var = escaped_id;
5308   lhs.offset = 0;
5309   rhs.type = ADDRESSOF;
5310   rhs.var = escaped_id;
5311   rhs.offset = 0;
5312   process_constraint (new_constraint (lhs, rhs));
5313
5314   /* *ESCAPED = &NONLOCAL.  This is true because we have to assume
5315      everything pointed to by escaped can also point to nonlocal. */
5316   lhs.type = DEREF;
5317   lhs.var = escaped_id;
5318   lhs.offset = 0;
5319   rhs.type = ADDRESSOF;
5320   rhs.var = nonlocal_id;
5321   rhs.offset = 0;
5322   process_constraint (new_constraint (lhs, rhs));
5323 }
5324
5325 /* Initialize things necessary to perform PTA */
5326
5327 static void
5328 init_alias_vars (void)
5329 {
5330   use_field_sensitive = (MAX_FIELDS_FOR_FIELD_SENSITIVE > 1);
5331
5332   bitmap_obstack_initialize (&pta_obstack);
5333   bitmap_obstack_initialize (&oldpta_obstack);
5334   bitmap_obstack_initialize (&predbitmap_obstack);
5335
5336   constraint_pool = create_alloc_pool ("Constraint pool",
5337                                        sizeof (struct constraint), 30);
5338   variable_info_pool = create_alloc_pool ("Variable info pool",
5339                                           sizeof (struct variable_info), 30);
5340   constraints = VEC_alloc (constraint_t, heap, 8);
5341   varmap = VEC_alloc (varinfo_t, heap, 8);
5342   vi_for_tree = pointer_map_create ();
5343
5344   memset (&stats, 0, sizeof (stats));
5345   shared_bitmap_table = htab_create (511, shared_bitmap_hash,
5346                                      shared_bitmap_eq, free);
5347   init_base_vars ();
5348 }
5349
5350 /* Remove the REF and ADDRESS edges from GRAPH, as well as all the
5351    predecessor edges.  */
5352
5353 static void
5354 remove_preds_and_fake_succs (constraint_graph_t graph)
5355 {
5356   unsigned int i;
5357
5358   /* Clear the implicit ref and address nodes from the successor
5359      lists.  */
5360   for (i = 0; i < FIRST_REF_NODE; i++)
5361     {
5362       if (graph->succs[i])
5363         bitmap_clear_range (graph->succs[i], FIRST_REF_NODE,
5364                             FIRST_REF_NODE * 2);
5365     }
5366
5367   /* Free the successor list for the non-ref nodes.  */
5368   for (i = FIRST_REF_NODE; i < graph->size; i++)
5369     {
5370       if (graph->succs[i])
5371         BITMAP_FREE (graph->succs[i]);
5372     }
5373
5374   /* Now reallocate the size of the successor list as, and blow away
5375      the predecessor bitmaps.  */
5376   graph->size = VEC_length (varinfo_t, varmap);
5377   graph->succs = XRESIZEVEC (bitmap, graph->succs, graph->size);
5378
5379   free (graph->implicit_preds);
5380   graph->implicit_preds = NULL;
5381   free (graph->preds);
5382   graph->preds = NULL;
5383   bitmap_obstack_release (&predbitmap_obstack);
5384 }
5385
5386 /* Compute the set of variables we can't TBAA prune.  */
5387
5388 static void
5389 compute_tbaa_pruning (void)
5390 {
5391   unsigned int size = VEC_length (varinfo_t, varmap);
5392   unsigned int i;
5393   bool any;
5394
5395   changed_count = 0;
5396   changed = sbitmap_alloc (size);
5397   sbitmap_zero (changed);
5398
5399   /* Mark all initial no_tbaa_pruning nodes as changed.  */
5400   any = false;
5401   for (i = 0; i < size; ++i)
5402     {
5403       varinfo_t ivi = get_varinfo (i);
5404
5405       if (find (i) == i && ivi->no_tbaa_pruning)
5406         {
5407           any = true;
5408           if ((graph->succs[i] && !bitmap_empty_p (graph->succs[i]))
5409               || VEC_length (constraint_t, graph->complex[i]) > 0)
5410             {
5411               SET_BIT (changed, i);
5412               ++changed_count;
5413             }
5414         }
5415     }
5416
5417   while (changed_count > 0)
5418     {
5419       struct topo_info *ti = init_topo_info ();
5420       ++stats.iterations;
5421
5422       compute_topo_order (graph, ti);
5423
5424       while (VEC_length (unsigned, ti->topo_order) != 0)
5425         {
5426           bitmap_iterator bi;
5427
5428           i = VEC_pop (unsigned, ti->topo_order);
5429
5430           /* If this variable is not a representative, skip it.  */
5431           if (find (i) != i)
5432             continue;
5433
5434           /* If the node has changed, we need to process the complex
5435              constraints and outgoing edges again.  */
5436           if (TEST_BIT (changed, i))
5437             {
5438               unsigned int j;
5439               constraint_t c;
5440               VEC(constraint_t,heap) *complex = graph->complex[i];
5441
5442               RESET_BIT (changed, i);
5443               --changed_count;
5444
5445               /* Process the complex copy constraints.  */
5446               for (j = 0; VEC_iterate (constraint_t, complex, j, c); ++j)
5447                 {
5448                   if (c->lhs.type == SCALAR && c->rhs.type == SCALAR)
5449                     {
5450                       varinfo_t lhsvi = get_varinfo (find (c->lhs.var));
5451
5452                       if (!lhsvi->no_tbaa_pruning)
5453                         {
5454                           lhsvi->no_tbaa_pruning = true;
5455                           if (!TEST_BIT (changed, lhsvi->id))
5456                             {
5457                               SET_BIT (changed, lhsvi->id);
5458                               ++changed_count;
5459                             }
5460                         }
5461                     }
5462                 }
5463
5464               /* Propagate to all successors.  */
5465               EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i], 0, j, bi)
5466                 {
5467                   unsigned int to = find (j);
5468                   varinfo_t tovi = get_varinfo (to);
5469
5470                   /* Don't propagate to ourselves.  */
5471                   if (to == i)
5472                     continue;
5473
5474                   if (!tovi->no_tbaa_pruning)
5475                     {
5476                       tovi->no_tbaa_pruning = true;
5477                       if (!TEST_BIT (changed, to))
5478                         {
5479                           SET_BIT (changed, to);
5480                           ++changed_count;
5481                         }
5482                     }
5483                 }
5484             }
5485         }
5486
5487       free_topo_info (ti);
5488     }
5489
5490   sbitmap_free (changed);
5491
5492   if (any)
5493     {
5494       for (i = 0; i < size; ++i)
5495         {
5496           varinfo_t ivi = get_varinfo (i);
5497           varinfo_t ivip = get_varinfo (find (i));
5498
5499           if (ivip->no_tbaa_pruning)
5500             {
5501               tree var = ivi->decl;
5502
5503               if (TREE_CODE (var) == SSA_NAME)
5504                 var = SSA_NAME_VAR (var);
5505
5506               if (POINTER_TYPE_P (TREE_TYPE (var)))
5507                 {
5508                   DECL_NO_TBAA_P (var) = 1;
5509
5510                   /* Tell the RTL layer that this pointer can alias
5511                      anything.  */
5512                   DECL_POINTER_ALIAS_SET (var) = 0;
5513                 }
5514             }
5515         }
5516     }
5517 }
5518
5519 /* Create points-to sets for the current function.  See the comments
5520    at the start of the file for an algorithmic overview.  */
5521
5522 void
5523 compute_points_to_sets (void)
5524 {
5525   struct scc_info *si;
5526   basic_block bb;
5527
5528   timevar_push (TV_TREE_PTA);
5529
5530   init_alias_vars ();
5531   init_alias_heapvars ();
5532
5533   intra_create_variable_infos ();
5534
5535   /* Now walk all statements and derive aliases.  */
5536   FOR_EACH_BB (bb)
5537     {
5538       gimple_stmt_iterator gsi;
5539
5540       for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5541         {
5542           gimple phi = gsi_stmt (gsi);
5543
5544           if (is_gimple_reg (gimple_phi_result (phi)))
5545             find_func_aliases (phi);
5546         }
5547
5548       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5549         find_func_aliases (gsi_stmt (gsi));
5550     }
5551
5552
5553   if (dump_file)
5554     {
5555       fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
5556       dump_constraints (dump_file);
5557     }
5558
5559   if (dump_file)
5560     fprintf (dump_file,
5561              "\nCollapsing static cycles and doing variable "
5562              "substitution\n");
5563
5564   init_graph (VEC_length (varinfo_t, varmap) * 2);
5565   
5566   if (dump_file)
5567     fprintf (dump_file, "Building predecessor graph\n");
5568   build_pred_graph ();
5569   
5570   if (dump_file)
5571     fprintf (dump_file, "Detecting pointer and location "
5572              "equivalences\n");
5573   si = perform_var_substitution (graph);
5574   
5575   if (dump_file)
5576     fprintf (dump_file, "Rewriting constraints and unifying "
5577              "variables\n");
5578   rewrite_constraints (graph, si);
5579
5580   build_succ_graph ();
5581   free_var_substitution_info (si);
5582
5583   if (dump_file && (dump_flags & TDF_GRAPH))
5584     dump_constraint_graph (dump_file);
5585
5586   move_complex_constraints (graph);
5587
5588   if (dump_file)
5589     fprintf (dump_file, "Uniting pointer but not location equivalent "
5590              "variables\n");
5591   unite_pointer_equivalences (graph);
5592
5593   if (dump_file)
5594     fprintf (dump_file, "Finding indirect cycles\n");
5595   find_indirect_cycles (graph);
5596
5597   /* Implicit nodes and predecessors are no longer necessary at this
5598      point. */
5599   remove_preds_and_fake_succs (graph);
5600
5601   if (dump_file)
5602     fprintf (dump_file, "Solving graph\n");
5603
5604   solve_graph (graph);
5605
5606   compute_tbaa_pruning ();
5607
5608   if (dump_file)
5609     dump_sa_points_to_info (dump_file);
5610
5611   have_alias_info = true;
5612
5613   timevar_pop (TV_TREE_PTA);
5614 }
5615
5616
5617 /* Delete created points-to sets.  */
5618
5619 void
5620 delete_points_to_sets (void)
5621 {
5622   unsigned int i;
5623
5624   htab_delete (shared_bitmap_table);
5625   if (dump_file && (dump_flags & TDF_STATS))
5626     fprintf (dump_file, "Points to sets created:%d\n",
5627              stats.points_to_sets_created);
5628
5629   pointer_map_destroy (vi_for_tree);
5630   bitmap_obstack_release (&pta_obstack);
5631   VEC_free (constraint_t, heap, constraints);
5632
5633   for (i = 0; i < graph->size; i++)
5634     VEC_free (constraint_t, heap, graph->complex[i]);
5635   free (graph->complex);
5636
5637   free (graph->rep);
5638   free (graph->succs);
5639   free (graph->pe);
5640   free (graph->pe_rep);
5641   free (graph->indirect_cycles);
5642   free (graph);
5643
5644   VEC_free (varinfo_t, heap, varmap);
5645   free_alloc_pool (variable_info_pool);
5646   free_alloc_pool (constraint_pool);
5647   have_alias_info = false;
5648 }
5649
5650 /* Return true if we should execute IPA PTA.  */
5651 static bool
5652 gate_ipa_pta (void)
5653 {
5654   return (flag_ipa_pta
5655           /* Don't bother doing anything if the program has errors.  */
5656           && !(errorcount || sorrycount));
5657 }
5658
5659 /* Execute the driver for IPA PTA.  */
5660 static unsigned int
5661 ipa_pta_execute (void)
5662 {
5663   struct cgraph_node *node;
5664   struct scc_info *si;
5665
5666   in_ipa_mode = 1;
5667   init_alias_heapvars ();
5668   init_alias_vars ();
5669
5670   for (node = cgraph_nodes; node; node = node->next)
5671     {
5672       unsigned int varid;
5673
5674       varid = create_function_info_for (node->decl,
5675                                         cgraph_node_name (node));
5676       if (node->local.externally_visible)
5677         {
5678           varinfo_t fi = get_varinfo (varid);
5679           for (; fi; fi = fi->next)
5680             make_constraint_from (fi, anything_id);
5681         }
5682     }
5683   for (node = cgraph_nodes; node; node = node->next)
5684     {
5685       if (node->analyzed)
5686         {
5687           struct function *func = DECL_STRUCT_FUNCTION (node->decl);
5688           basic_block bb;
5689           tree old_func_decl = current_function_decl;
5690           if (dump_file)
5691             fprintf (dump_file,
5692                      "Generating constraints for %s\n",
5693                      cgraph_node_name (node));
5694           push_cfun (func);
5695           current_function_decl = node->decl;
5696
5697           FOR_EACH_BB_FN (bb, func)
5698             {
5699               gimple_stmt_iterator gsi;
5700
5701               for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
5702                    gsi_next (&gsi))
5703                 {
5704                   gimple phi = gsi_stmt (gsi);
5705
5706                   if (is_gimple_reg (gimple_phi_result (phi)))
5707                     find_func_aliases (phi);
5708                 }
5709
5710               for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5711                 find_func_aliases (gsi_stmt (gsi));
5712             }
5713           current_function_decl = old_func_decl;
5714           pop_cfun ();
5715         }
5716       else
5717         {
5718           /* Make point to anything.  */
5719         }
5720     }
5721
5722   if (dump_file)
5723     {
5724       fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
5725       dump_constraints (dump_file);
5726     }
5727
5728   if (dump_file)
5729     fprintf (dump_file,
5730              "\nCollapsing static cycles and doing variable "
5731              "substitution:\n");
5732
5733   init_graph (VEC_length (varinfo_t, varmap) * 2);
5734   build_pred_graph ();
5735   si = perform_var_substitution (graph);
5736   rewrite_constraints (graph, si);
5737
5738   build_succ_graph ();
5739   free_var_substitution_info (si);
5740   move_complex_constraints (graph);
5741   unite_pointer_equivalences (graph);
5742   find_indirect_cycles (graph);
5743
5744   /* Implicit nodes and predecessors are no longer necessary at this
5745      point. */
5746   remove_preds_and_fake_succs (graph);
5747
5748   if (dump_file)
5749     fprintf (dump_file, "\nSolving graph\n");
5750
5751   solve_graph (graph);
5752
5753   if (dump_file)
5754     dump_sa_points_to_info (dump_file);
5755
5756   in_ipa_mode = 0;
5757   delete_alias_heapvars ();
5758   delete_points_to_sets ();
5759   return 0;
5760 }
5761
5762 struct simple_ipa_opt_pass pass_ipa_pta =
5763 {
5764  {
5765   SIMPLE_IPA_PASS,
5766   "pta",                                /* name */
5767   gate_ipa_pta,                 /* gate */
5768   ipa_pta_execute,                      /* execute */
5769   NULL,                                 /* sub */
5770   NULL,                                 /* next */
5771   0,                                    /* static_pass_number */
5772   TV_IPA_PTA,                   /* tv_id */
5773   0,                                    /* properties_required */
5774   0,                                    /* properties_provided */
5775   0,                                    /* properties_destroyed */
5776   0,                                    /* todo_flags_start */
5777   TODO_update_ssa                       /* todo_flags_finish */
5778  }
5779 };
5780
5781 /* Initialize the heapvar for statement mapping.  */
5782 void
5783 init_alias_heapvars (void)
5784 {
5785   if (!heapvar_for_stmt)
5786     heapvar_for_stmt = htab_create_ggc (11, tree_map_hash, tree_map_eq,
5787                                         NULL);
5788 }
5789
5790 void
5791 delete_alias_heapvars (void)
5792 {
5793   htab_delete (heapvar_for_stmt);
5794   heapvar_for_stmt = NULL;
5795 }
5796
5797 #include "gt-tree-ssa-structalias.h"