OSDN Git Service

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