OSDN Git Service

2009-06-14 Richard Guenther <rguenther@suse.de>
[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 static void get_constraint_for_1 (tree, VEC (ce_s, heap) **, bool);
3084
3085 /* Given a tree T, return the constraint expression for taking the
3086    address of it.  */
3087
3088 static void
3089 get_constraint_for_address_of (tree t, VEC (ce_s, heap) **results)
3090 {
3091   struct constraint_expr *c;
3092   unsigned int i;
3093
3094   get_constraint_for_1 (t, results, true);
3095
3096   for (i = 0; VEC_iterate (ce_s, *results, i, c); i++)
3097     {
3098       if (c->type == DEREF)
3099         c->type = SCALAR;
3100       else
3101         c->type = ADDRESSOF;
3102     }
3103 }
3104
3105 /* Given a tree T, return the constraint expression for it.  */
3106
3107 static void
3108 get_constraint_for_1 (tree t, VEC (ce_s, heap) **results, bool address_p)
3109 {
3110   struct constraint_expr temp;
3111
3112   /* x = integer is all glommed to a single variable, which doesn't
3113      point to anything by itself.  That is, of course, unless it is an
3114      integer constant being treated as a pointer, in which case, we
3115      will return that this is really the addressof anything.  This
3116      happens below, since it will fall into the default case. The only
3117      case we know something about an integer treated like a pointer is
3118      when it is the NULL pointer, and then we just say it points to
3119      NULL.
3120
3121      Do not do that if -fno-delete-null-pointer-checks though, because
3122      in that case *NULL does not fail, so it _should_ alias *anything.
3123      It is not worth adding a new option or renaming the existing one,
3124      since this case is relatively obscure.  */
3125   if (flag_delete_null_pointer_checks
3126       && ((TREE_CODE (t) == INTEGER_CST
3127            && integer_zerop (t))
3128           /* The only valid CONSTRUCTORs in gimple with pointer typed
3129              elements are zero-initializer.  */
3130           || TREE_CODE (t) == CONSTRUCTOR))
3131     {
3132       temp.var = nothing_id;
3133       temp.type = ADDRESSOF;
3134       temp.offset = 0;
3135       VEC_safe_push (ce_s, heap, *results, &temp);
3136       return;
3137     }
3138
3139   /* String constants are read-only.  */
3140   if (TREE_CODE (t) == STRING_CST)
3141     {
3142       temp.var = readonly_id;
3143       temp.type = SCALAR;
3144       temp.offset = 0;
3145       VEC_safe_push (ce_s, heap, *results, &temp);
3146       return;
3147     }
3148
3149   switch (TREE_CODE_CLASS (TREE_CODE (t)))
3150     {
3151     case tcc_expression:
3152       {
3153         switch (TREE_CODE (t))
3154           {
3155           case ADDR_EXPR:
3156             get_constraint_for_address_of (TREE_OPERAND (t, 0), results);
3157             return;
3158           default:;
3159           }
3160         break;
3161       }
3162     case tcc_reference:
3163       {
3164         switch (TREE_CODE (t))
3165           {
3166           case INDIRECT_REF:
3167             {
3168               get_constraint_for_1 (TREE_OPERAND (t, 0), results, address_p);
3169               do_deref (results);
3170               return;
3171             }
3172           case ARRAY_REF:
3173           case ARRAY_RANGE_REF:
3174           case COMPONENT_REF:
3175             get_constraint_for_component_ref (t, results, address_p);
3176             return;
3177           case VIEW_CONVERT_EXPR:
3178             get_constraint_for_1 (TREE_OPERAND (t, 0), results, address_p);
3179             return;
3180           /* We are missing handling for TARGET_MEM_REF here.  */
3181           default:;
3182           }
3183         break;
3184       }
3185     case tcc_exceptional:
3186       {
3187         switch (TREE_CODE (t))
3188           {
3189           case SSA_NAME:
3190             {
3191               get_constraint_for_ssa_var (t, results, address_p);
3192               return;
3193             }
3194           default:;
3195           }
3196         break;
3197       }
3198     case tcc_declaration:
3199       {
3200         get_constraint_for_ssa_var (t, results, address_p);
3201         return;
3202       }
3203     default:;
3204     }
3205
3206   /* The default fallback is a constraint from anything.  */
3207   temp.type = ADDRESSOF;
3208   temp.var = anything_id;
3209   temp.offset = 0;
3210   VEC_safe_push (ce_s, heap, *results, &temp);
3211 }
3212
3213 /* Given a gimple tree T, return the constraint expression vector for it.  */
3214
3215 static void
3216 get_constraint_for (tree t, VEC (ce_s, heap) **results)
3217 {
3218   gcc_assert (VEC_length (ce_s, *results) == 0);
3219
3220   get_constraint_for_1 (t, results, false);
3221 }
3222
3223 /* Handle aggregate copies by expanding into copies of the respective
3224    fields of the structures.  */
3225
3226 static void
3227 do_structure_copy (tree lhsop, tree rhsop)
3228 {
3229   struct constraint_expr *lhsp, *rhsp;
3230   VEC (ce_s, heap) *lhsc = NULL, *rhsc = NULL;
3231   unsigned j;
3232
3233   get_constraint_for (lhsop, &lhsc);
3234   get_constraint_for (rhsop, &rhsc);
3235   lhsp = VEC_index (ce_s, lhsc, 0);
3236   rhsp = VEC_index (ce_s, rhsc, 0);
3237   if (lhsp->type == DEREF
3238       || (lhsp->type == ADDRESSOF && lhsp->var == anything_id)
3239       || rhsp->type == DEREF)
3240     {
3241       struct constraint_expr tmp;
3242       tree tmpvar = create_tmp_var_raw (ptr_type_node,
3243                                         "structcopydereftmp");
3244       tmp.var = get_vi_for_tree (tmpvar)->id;
3245       tmp.type = SCALAR;
3246       tmp.offset = 0;
3247       for (j = 0; VEC_iterate (ce_s, rhsc, j, rhsp); ++j)
3248         process_constraint (new_constraint (tmp, *rhsp));
3249       for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp); ++j)
3250         process_constraint (new_constraint (*lhsp, tmp));
3251     }
3252   else if (lhsp->type == SCALAR
3253            && (rhsp->type == SCALAR
3254                || rhsp->type == ADDRESSOF))
3255     {
3256       tree lhsbase, rhsbase;
3257       HOST_WIDE_INT lhssize, lhsmaxsize, lhsoffset;
3258       HOST_WIDE_INT rhssize, rhsmaxsize, rhsoffset;
3259       unsigned k = 0;
3260       lhsbase = get_ref_base_and_extent (lhsop, &lhsoffset,
3261                                          &lhssize, &lhsmaxsize);
3262       rhsbase = get_ref_base_and_extent (rhsop, &rhsoffset,
3263                                          &rhssize, &rhsmaxsize);
3264       for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp);)
3265         {
3266           varinfo_t lhsv, rhsv;
3267           rhsp = VEC_index (ce_s, rhsc, k);
3268           lhsv = get_varinfo (lhsp->var);
3269           rhsv = get_varinfo (rhsp->var);
3270           if (lhsv->may_have_pointers
3271               && ranges_overlap_p (lhsv->offset + rhsoffset, lhsv->size,
3272                                    rhsv->offset + lhsoffset, rhsv->size))
3273             process_constraint (new_constraint (*lhsp, *rhsp));
3274           if (lhsv->offset + rhsoffset + lhsv->size
3275               > rhsv->offset + lhsoffset + rhsv->size)
3276             {
3277               ++k;
3278               if (k >= VEC_length (ce_s, rhsc))
3279                 break;
3280             }
3281           else
3282             ++j;
3283         }
3284     }
3285   else
3286     gcc_unreachable ();
3287
3288   VEC_free (ce_s, heap, lhsc);
3289   VEC_free (ce_s, heap, rhsc);
3290 }
3291
3292 /* Create a constraint ID = OP.  */
3293
3294 static void
3295 make_constraint_to (unsigned id, tree op)
3296 {
3297   VEC(ce_s, heap) *rhsc = NULL;
3298   struct constraint_expr *c;
3299   struct constraint_expr includes;
3300   unsigned int j;
3301
3302   includes.var = id;
3303   includes.offset = 0;
3304   includes.type = SCALAR;
3305
3306   get_constraint_for (op, &rhsc);
3307   for (j = 0; VEC_iterate (ce_s, rhsc, j, c); j++)
3308     process_constraint (new_constraint (includes, *c));
3309   VEC_free (ce_s, heap, rhsc);
3310 }
3311
3312 /* Make constraints necessary to make OP escape.  */
3313
3314 static void
3315 make_escape_constraint (tree op)
3316 {
3317   make_constraint_to (escaped_id, op);
3318 }
3319
3320 /* For non-IPA mode, generate constraints necessary for a call on the
3321    RHS.  */
3322
3323 static void
3324 handle_rhs_call (gimple stmt, VEC(ce_s, heap) **results)
3325 {
3326   struct constraint_expr rhsc;
3327   unsigned i;
3328
3329   for (i = 0; i < gimple_call_num_args (stmt); ++i)
3330     {
3331       tree arg = gimple_call_arg (stmt, i);
3332
3333       /* Find those pointers being passed, and make sure they end up
3334          pointing to anything.  */
3335       if (could_have_pointers (arg))
3336         make_escape_constraint (arg);
3337     }
3338
3339   /* The static chain escapes as well.  */
3340   if (gimple_call_chain (stmt))
3341     make_escape_constraint (gimple_call_chain (stmt));
3342
3343   /* And if we applied NRV the address of the return slot escapes as well.  */
3344   if (gimple_call_return_slot_opt_p (stmt)
3345       && gimple_call_lhs (stmt) != NULL_TREE
3346       && TREE_ADDRESSABLE (gimple_call_lhs (stmt)))
3347     {
3348       VEC(ce_s, heap) *tmpc = NULL;
3349       struct constraint_expr lhsc, *c;
3350       get_constraint_for_address_of (gimple_call_lhs (stmt), &tmpc);
3351       lhsc.var = escaped_id;
3352       lhsc.offset = 0;
3353       lhsc.type = SCALAR;
3354       for (i = 0; VEC_iterate (ce_s, tmpc, i, c); ++i)
3355         process_constraint (new_constraint (lhsc, *c));
3356       VEC_free(ce_s, heap, tmpc);
3357     }
3358
3359   /* Regular functions return nonlocal memory.  */
3360   rhsc.var = nonlocal_id;
3361   rhsc.offset = 0;
3362   rhsc.type = SCALAR;
3363   VEC_safe_push (ce_s, heap, *results, &rhsc);
3364 }
3365
3366 /* For non-IPA mode, generate constraints necessary for a call
3367    that returns a pointer and assigns it to LHS.  This simply makes
3368    the LHS point to global and escaped variables.  */
3369
3370 static void
3371 handle_lhs_call (tree lhs, int flags, VEC(ce_s, heap) *rhsc)
3372 {
3373   VEC(ce_s, heap) *lhsc = NULL;
3374   unsigned int j;
3375   struct constraint_expr *lhsp;
3376
3377   get_constraint_for (lhs, &lhsc);
3378
3379   if (flags & ECF_MALLOC)
3380     {
3381       struct constraint_expr rhsc;
3382       tree heapvar = heapvar_lookup (lhs);
3383       varinfo_t vi;
3384
3385       if (heapvar == NULL)
3386         {
3387           heapvar = create_tmp_var_raw (ptr_type_node, "HEAP");
3388           DECL_EXTERNAL (heapvar) = 1;
3389           get_var_ann (heapvar)->is_heapvar = 1;
3390           if (gimple_referenced_vars (cfun))
3391             add_referenced_var (heapvar);
3392           heapvar_insert (lhs, heapvar);
3393         }
3394
3395       rhsc.var = create_variable_info_for (heapvar,
3396                                            alias_get_name (heapvar));
3397       vi = get_varinfo (rhsc.var);
3398       vi->is_artificial_var = 1;
3399       vi->is_heap_var = 1;
3400       vi->is_unknown_size_var = true;
3401       vi->fullsize = ~0;
3402       vi->size = ~0;
3403       rhsc.type = ADDRESSOF;
3404       rhsc.offset = 0;
3405       for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp); j++)
3406         process_constraint (new_constraint (*lhsp, rhsc));
3407     }
3408   else if (VEC_length (ce_s, rhsc) > 0)
3409     {
3410       struct constraint_expr *lhsp, *rhsp;
3411       unsigned int i, j;
3412       /* If the store is to a global decl make sure to
3413          add proper escape constraints.  */
3414       lhs = get_base_address (lhs);
3415       if (lhs
3416           && DECL_P (lhs)
3417           && is_global_var (lhs))
3418         {
3419           struct constraint_expr tmpc;
3420           tmpc.var = escaped_id;
3421           tmpc.offset = 0;
3422           tmpc.type = SCALAR;
3423           VEC_safe_push (ce_s, heap, lhsc, &tmpc);
3424         }
3425       for (i = 0; VEC_iterate (ce_s, lhsc, i, lhsp); ++i)
3426         for (j = 0; VEC_iterate (ce_s, rhsc, j, rhsp); ++j)
3427           process_constraint (new_constraint (*lhsp, *rhsp));
3428     }
3429   VEC_free (ce_s, heap, lhsc);
3430 }
3431
3432 /* For non-IPA mode, generate constraints necessary for a call of a
3433    const function that returns a pointer in the statement STMT.  */
3434
3435 static void
3436 handle_const_call (gimple stmt, VEC(ce_s, heap) **results)
3437 {
3438   struct constraint_expr rhsc, tmpc = {SCALAR, 0, 0};
3439   tree tmpvar = NULL_TREE;
3440   unsigned int k;
3441
3442   /* Treat nested const functions the same as pure functions as far
3443      as the static chain is concerned.  */
3444   if (gimple_call_chain (stmt))
3445     {
3446       make_constraint_to (callused_id, gimple_call_chain (stmt));
3447       rhsc.var = callused_id;
3448       rhsc.offset = 0;
3449       rhsc.type = SCALAR;
3450       VEC_safe_push (ce_s, heap, *results, &rhsc);
3451     }
3452
3453   /* May return arguments.  */
3454   for (k = 0; k < gimple_call_num_args (stmt); ++k)
3455     {
3456       tree arg = gimple_call_arg (stmt, k);
3457
3458       if (could_have_pointers (arg))
3459         {
3460           VEC(ce_s, heap) *argc = NULL;
3461           struct constraint_expr *argp;
3462           int i;
3463
3464           /* We always use a temporary here, otherwise we end up with
3465              a quadratic amount of constraints for
3466                large_struct = const_call (large_struct);
3467              with field-sensitive PTA.  */
3468           if (tmpvar == NULL_TREE)
3469             {
3470               tmpvar = create_tmp_var_raw (ptr_type_node, "consttmp");
3471               tmpc = get_constraint_exp_for_temp (tmpvar);
3472             }
3473
3474           get_constraint_for (arg, &argc);
3475           for (i = 0; VEC_iterate (ce_s, argc, i, argp); i++)
3476             process_constraint (new_constraint (tmpc, *argp));
3477           VEC_free (ce_s, heap, argc);
3478         }
3479     }
3480   if (tmpvar != NULL_TREE)
3481     VEC_safe_push (ce_s, heap, *results, &tmpc);
3482
3483   /* May return addresses of globals.  */
3484   rhsc.var = nonlocal_id;
3485   rhsc.offset = 0;
3486   rhsc.type = ADDRESSOF;
3487   VEC_safe_push (ce_s, heap, *results, &rhsc);
3488 }
3489
3490 /* For non-IPA mode, generate constraints necessary for a call to a
3491    pure function in statement STMT.  */
3492
3493 static void
3494 handle_pure_call (gimple stmt, VEC(ce_s, heap) **results)
3495 {
3496   struct constraint_expr rhsc;
3497   unsigned i;
3498   bool need_callused = false;
3499
3500   /* Memory reached from pointer arguments is call-used.  */
3501   for (i = 0; i < gimple_call_num_args (stmt); ++i)
3502     {
3503       tree arg = gimple_call_arg (stmt, i);
3504
3505       if (could_have_pointers (arg))
3506         {
3507           make_constraint_to (callused_id, arg);
3508           need_callused = true;
3509         }
3510     }
3511
3512   /* The static chain is used as well.  */
3513   if (gimple_call_chain (stmt))
3514     {
3515       make_constraint_to (callused_id, gimple_call_chain (stmt));
3516       need_callused = true;
3517     }
3518
3519   /* Pure functions may return callused and nonlocal memory.  */
3520   if (need_callused)
3521     {
3522       rhsc.var = callused_id;
3523       rhsc.offset = 0;
3524       rhsc.type = SCALAR;
3525       VEC_safe_push (ce_s, heap, *results, &rhsc);
3526     }
3527   rhsc.var = nonlocal_id;
3528   rhsc.offset = 0;
3529   rhsc.type = SCALAR;
3530   VEC_safe_push (ce_s, heap, *results, &rhsc);
3531 }
3532
3533 /* Walk statement T setting up aliasing constraints according to the
3534    references found in T.  This function is the main part of the
3535    constraint builder.  AI points to auxiliary alias information used
3536    when building alias sets and computing alias grouping heuristics.  */
3537
3538 static void
3539 find_func_aliases (gimple origt)
3540 {
3541   gimple t = origt;
3542   VEC(ce_s, heap) *lhsc = NULL;
3543   VEC(ce_s, heap) *rhsc = NULL;
3544   struct constraint_expr *c;
3545   enum escape_type stmt_escape_type;
3546
3547   /* Now build constraints expressions.  */
3548   if (gimple_code (t) == GIMPLE_PHI)
3549     {
3550       gcc_assert (!AGGREGATE_TYPE_P (TREE_TYPE (gimple_phi_result (t))));
3551
3552       /* Only care about pointers and structures containing
3553          pointers.  */
3554       if (could_have_pointers (gimple_phi_result (t)))
3555         {
3556           size_t i;
3557           unsigned int j;
3558
3559           /* For a phi node, assign all the arguments to
3560              the result.  */
3561           get_constraint_for (gimple_phi_result (t), &lhsc);
3562           for (i = 0; i < gimple_phi_num_args (t); i++)
3563             {
3564               tree rhstype;
3565               tree strippedrhs = PHI_ARG_DEF (t, i);
3566
3567               STRIP_NOPS (strippedrhs);
3568               rhstype = TREE_TYPE (strippedrhs);
3569               get_constraint_for (gimple_phi_arg_def (t, i), &rhsc);
3570
3571               for (j = 0; VEC_iterate (ce_s, lhsc, j, c); j++)
3572                 {
3573                   struct constraint_expr *c2;
3574                   while (VEC_length (ce_s, rhsc) > 0)
3575                     {
3576                       c2 = VEC_last (ce_s, rhsc);
3577                       process_constraint (new_constraint (*c, *c2));
3578                       VEC_pop (ce_s, rhsc);
3579                     }
3580                 }
3581             }
3582         }
3583     }
3584   /* In IPA mode, we need to generate constraints to pass call
3585      arguments through their calls.   There are two cases,
3586      either a GIMPLE_CALL returning a value, or just a plain
3587      GIMPLE_CALL when we are not.
3588
3589      In non-ipa mode, we need to generate constraints for each
3590      pointer passed by address.  */
3591   else if (is_gimple_call (t))
3592     {
3593       if (!in_ipa_mode)
3594         {
3595           VEC(ce_s, heap) *rhsc = NULL;
3596           int flags = gimple_call_flags (t);
3597
3598           /* Const functions can return their arguments and addresses
3599              of global memory but not of escaped memory.  */
3600           if (flags & (ECF_CONST|ECF_NOVOPS))
3601             {
3602               if (gimple_call_lhs (t)
3603                   && could_have_pointers (gimple_call_lhs (t)))
3604                 handle_const_call (t, &rhsc);
3605             }
3606           /* Pure functions can return addresses in and of memory
3607              reachable from their arguments, but they are not an escape
3608              point for reachable memory of their arguments.  */
3609           else if (flags & (ECF_PURE|ECF_LOOPING_CONST_OR_PURE))
3610             handle_pure_call (t, &rhsc);
3611           else
3612             handle_rhs_call (t, &rhsc);
3613           if (gimple_call_lhs (t)
3614               && could_have_pointers (gimple_call_lhs (t)))
3615             handle_lhs_call (gimple_call_lhs (t), flags, rhsc);
3616           VEC_free (ce_s, heap, rhsc);
3617         }
3618       else
3619         {
3620           tree lhsop;
3621           varinfo_t fi;
3622           int i = 1;
3623           size_t j;
3624           tree decl;
3625
3626           lhsop = gimple_call_lhs (t);
3627           decl = gimple_call_fndecl (t);
3628
3629           /* If we can directly resolve the function being called, do so.
3630              Otherwise, it must be some sort of indirect expression that
3631              we should still be able to handle.  */
3632           if (decl)
3633             fi = get_vi_for_tree (decl);
3634           else
3635             {
3636               decl = gimple_call_fn (t);
3637               fi = get_vi_for_tree (decl);
3638             }
3639
3640           /* Assign all the passed arguments to the appropriate incoming
3641              parameters of the function.  */
3642           for (j = 0; j < gimple_call_num_args (t); j++)
3643             {
3644               struct constraint_expr lhs ;
3645               struct constraint_expr *rhsp;
3646               tree arg = gimple_call_arg (t, j);
3647
3648               get_constraint_for (arg, &rhsc);
3649               if (TREE_CODE (decl) != FUNCTION_DECL)
3650                 {
3651                   lhs.type = DEREF;
3652                   lhs.var = fi->id;
3653                   lhs.offset = i;
3654                 }
3655               else
3656                 {
3657                   lhs.type = SCALAR;
3658                   lhs.var = first_vi_for_offset (fi, i)->id;
3659                   lhs.offset = 0;
3660                 }
3661               while (VEC_length (ce_s, rhsc) != 0)
3662                 {
3663                   rhsp = VEC_last (ce_s, rhsc);
3664                   process_constraint (new_constraint (lhs, *rhsp));
3665                   VEC_pop (ce_s, rhsc);
3666                 }
3667               i++;
3668             }
3669
3670           /* If we are returning a value, assign it to the result.  */
3671           if (lhsop)
3672             {
3673               struct constraint_expr rhs;
3674               struct constraint_expr *lhsp;
3675               unsigned int j = 0;
3676
3677               get_constraint_for (lhsop, &lhsc);
3678               if (TREE_CODE (decl) != FUNCTION_DECL)
3679                 {
3680                   rhs.type = DEREF;
3681                   rhs.var = fi->id;
3682                   rhs.offset = i;
3683                 }
3684               else
3685                 {
3686                   rhs.type = SCALAR;
3687                   rhs.var = first_vi_for_offset (fi, i)->id;
3688                   rhs.offset = 0;
3689                 }
3690               for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp); j++)
3691                 process_constraint (new_constraint (*lhsp, rhs));
3692             }
3693         }
3694     }
3695   /* Otherwise, just a regular assignment statement.  Only care about
3696      operations with pointer result, others are dealt with as escape
3697      points if they have pointer operands.  */
3698   else if (is_gimple_assign (t)
3699            && could_have_pointers (gimple_assign_lhs (t)))
3700     {
3701       /* Otherwise, just a regular assignment statement.  */
3702       tree lhsop = gimple_assign_lhs (t);
3703       tree rhsop = (gimple_num_ops (t) == 2) ? gimple_assign_rhs1 (t) : NULL;
3704
3705       if (rhsop && AGGREGATE_TYPE_P (TREE_TYPE (lhsop)))
3706         do_structure_copy (lhsop, rhsop);
3707       else
3708         {
3709           unsigned int j;
3710           struct constraint_expr temp;
3711           get_constraint_for (lhsop, &lhsc);
3712
3713           if (gimple_assign_rhs_code (t) == POINTER_PLUS_EXPR)
3714             get_constraint_for_ptr_offset (gimple_assign_rhs1 (t),
3715                                            gimple_assign_rhs2 (t), &rhsc);
3716           else if ((CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (t))
3717                     && !(POINTER_TYPE_P (gimple_expr_type (t))
3718                          && !POINTER_TYPE_P (TREE_TYPE (rhsop))))
3719                    || gimple_assign_single_p (t))
3720             get_constraint_for (rhsop, &rhsc);
3721           else
3722             {
3723               temp.type = ADDRESSOF;
3724               temp.var = anything_id;
3725               temp.offset = 0;
3726               VEC_safe_push (ce_s, heap, rhsc, &temp);
3727             }
3728           for (j = 0; VEC_iterate (ce_s, lhsc, j, c); j++)
3729             {
3730               struct constraint_expr *c2;
3731               unsigned int k;
3732
3733               for (k = 0; VEC_iterate (ce_s, rhsc, k, c2); k++)
3734                 process_constraint (new_constraint (*c, *c2));
3735             }
3736         }
3737     }
3738
3739   stmt_escape_type = is_escape_site (t);
3740   if (stmt_escape_type == ESCAPE_STORED_IN_GLOBAL)
3741     {
3742       gcc_assert (is_gimple_assign (t));
3743       if (gimple_assign_rhs_code (t) == ADDR_EXPR)
3744         {
3745           tree rhs = gimple_assign_rhs1 (t);
3746           tree base = get_base_address (TREE_OPERAND (rhs, 0));
3747           if (base
3748               && (!DECL_P (base)
3749                   || !is_global_var (base)))
3750             make_escape_constraint (rhs);
3751         }
3752       else if (get_gimple_rhs_class (gimple_assign_rhs_code (t))
3753                == GIMPLE_SINGLE_RHS)
3754         {
3755           if (could_have_pointers (gimple_assign_rhs1 (t)))
3756             make_escape_constraint (gimple_assign_rhs1 (t));
3757         }
3758       else
3759         gcc_unreachable ();
3760     }
3761   else if (stmt_escape_type == ESCAPE_BAD_CAST)
3762     {
3763       gcc_assert (is_gimple_assign (t));
3764       gcc_assert (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (t))
3765                   || gimple_assign_rhs_code (t) == VIEW_CONVERT_EXPR);
3766       make_escape_constraint (gimple_assign_rhs1 (t));
3767     }
3768   else if (stmt_escape_type == ESCAPE_TO_ASM)
3769     {
3770       unsigned i, noutputs;
3771       const char **oconstraints;
3772       const char *constraint;
3773       bool allows_mem, allows_reg, is_inout;
3774
3775       noutputs = gimple_asm_noutputs (t);
3776       oconstraints = XALLOCAVEC (const char *, noutputs);
3777
3778       for (i = 0; i < noutputs; ++i)
3779         {
3780           tree link = gimple_asm_output_op (t, i);
3781           tree op = TREE_VALUE (link);
3782
3783           constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
3784           oconstraints[i] = constraint;
3785           parse_output_constraint (&constraint, i, 0, 0, &allows_mem,
3786                                    &allows_reg, &is_inout);
3787
3788           /* A memory constraint makes the address of the operand escape.  */
3789           if (!allows_reg && allows_mem)
3790             make_escape_constraint (build_fold_addr_expr (op));
3791
3792           /* The asm may read global memory, so outputs may point to
3793              any global memory.  */
3794           if (op && could_have_pointers (op))
3795             {
3796               VEC(ce_s, heap) *lhsc = NULL;
3797               struct constraint_expr rhsc, *lhsp;
3798               unsigned j;
3799               get_constraint_for (op, &lhsc);
3800               rhsc.var = nonlocal_id;
3801               rhsc.offset = 0;
3802               rhsc.type = SCALAR;
3803               for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp); j++)
3804                 process_constraint (new_constraint (*lhsp, rhsc));
3805               VEC_free (ce_s, heap, lhsc);
3806             }
3807         }
3808       for (i = 0; i < gimple_asm_ninputs (t); ++i)
3809         {
3810           tree link = gimple_asm_input_op (t, i);
3811           tree op = TREE_VALUE (link);
3812
3813           constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
3814
3815           parse_input_constraint (&constraint, 0, 0, noutputs, 0, oconstraints,
3816                                   &allows_mem, &allows_reg);
3817
3818           /* A memory constraint makes the address of the operand escape.  */
3819           if (!allows_reg && allows_mem)
3820             make_escape_constraint (build_fold_addr_expr (op));
3821           /* Strictly we'd only need the constraint to ESCAPED if
3822              the asm clobbers memory, otherwise using CALLUSED
3823              would be enough.  */
3824           else if (op && could_have_pointers (op))
3825             make_escape_constraint (op);
3826         }
3827     }
3828
3829   VEC_free (ce_s, heap, rhsc);
3830   VEC_free (ce_s, heap, lhsc);
3831 }
3832
3833
3834 /* Find the first varinfo in the same variable as START that overlaps with
3835    OFFSET.  Return NULL if we can't find one.  */
3836
3837 static varinfo_t
3838 first_vi_for_offset (varinfo_t start, unsigned HOST_WIDE_INT offset)
3839 {
3840   /* If the offset is outside of the variable, bail out.  */
3841   if (offset >= start->fullsize)
3842     return NULL;
3843
3844   /* If we cannot reach offset from start, lookup the first field
3845      and start from there.  */
3846   if (start->offset > offset)
3847     start = lookup_vi_for_tree (start->decl);
3848
3849   while (start)
3850     {
3851       /* We may not find a variable in the field list with the actual
3852          offset when when we have glommed a structure to a variable.
3853          In that case, however, offset should still be within the size
3854          of the variable. */
3855       if (offset >= start->offset
3856           && offset < (start->offset + start->size))
3857         return start;
3858
3859       start= start->next;
3860     }
3861
3862   return NULL;
3863 }
3864
3865 /* Find the first varinfo in the same variable as START that overlaps with
3866    OFFSET.  If there is no such varinfo the varinfo directly preceding
3867    OFFSET is returned.  */
3868
3869 static varinfo_t
3870 first_or_preceding_vi_for_offset (varinfo_t start,
3871                                   unsigned HOST_WIDE_INT offset)
3872 {
3873   /* If we cannot reach offset from start, lookup the first field
3874      and start from there.  */
3875   if (start->offset > offset)
3876     start = lookup_vi_for_tree (start->decl);
3877
3878   /* We may not find a variable in the field list with the actual
3879      offset when when we have glommed a structure to a variable.
3880      In that case, however, offset should still be within the size
3881      of the variable.
3882      If we got beyond the offset we look for return the field
3883      directly preceding offset which may be the last field.  */
3884   while (start->next
3885          && offset >= start->offset
3886          && !(offset < (start->offset + start->size)))
3887     start = start->next;
3888
3889   return start;
3890 }
3891
3892
3893 /* Insert the varinfo FIELD into the field list for BASE, at the front
3894    of the list.  */
3895
3896 static void
3897 insert_into_field_list (varinfo_t base, varinfo_t field)
3898 {
3899   varinfo_t prev = base;
3900   varinfo_t curr = base->next;
3901
3902   field->next = curr;
3903   prev->next = field;
3904 }
3905
3906 /* Insert the varinfo FIELD into the field list for BASE, ordered by
3907    offset.  */
3908
3909 static void
3910 insert_into_field_list_sorted (varinfo_t base, varinfo_t field)
3911 {
3912   varinfo_t prev = base;
3913   varinfo_t curr = base->next;
3914
3915   if (curr == NULL)
3916     {
3917       prev->next = field;
3918       field->next = NULL;
3919     }
3920   else
3921     {
3922       while (curr)
3923         {
3924           if (field->offset <= curr->offset)
3925             break;
3926           prev = curr;
3927           curr = curr->next;
3928         }
3929       field->next = prev->next;
3930       prev->next = field;
3931     }
3932 }
3933
3934 /* This structure is used during pushing fields onto the fieldstack
3935    to track the offset of the field, since bitpos_of_field gives it
3936    relative to its immediate containing type, and we want it relative
3937    to the ultimate containing object.  */
3938
3939 struct fieldoff
3940 {
3941   /* Offset from the base of the base containing object to this field.  */
3942   HOST_WIDE_INT offset;
3943
3944   /* Size, in bits, of the field.  */
3945   unsigned HOST_WIDE_INT size;
3946
3947   unsigned has_unknown_size : 1;
3948
3949   unsigned may_have_pointers : 1;
3950 };
3951 typedef struct fieldoff fieldoff_s;
3952
3953 DEF_VEC_O(fieldoff_s);
3954 DEF_VEC_ALLOC_O(fieldoff_s,heap);
3955
3956 /* qsort comparison function for two fieldoff's PA and PB */
3957
3958 static int
3959 fieldoff_compare (const void *pa, const void *pb)
3960 {
3961   const fieldoff_s *foa = (const fieldoff_s *)pa;
3962   const fieldoff_s *fob = (const fieldoff_s *)pb;
3963   unsigned HOST_WIDE_INT foasize, fobsize;
3964
3965   if (foa->offset < fob->offset)
3966     return -1;
3967   else if (foa->offset > fob->offset)
3968     return 1;
3969
3970   foasize = foa->size;
3971   fobsize = fob->size;
3972   if (foasize < fobsize)
3973     return -1;
3974   else if (foasize > fobsize)
3975     return 1;
3976   return 0;
3977 }
3978
3979 /* Sort a fieldstack according to the field offset and sizes.  */
3980 static void
3981 sort_fieldstack (VEC(fieldoff_s,heap) *fieldstack)
3982 {
3983   qsort (VEC_address (fieldoff_s, fieldstack),
3984          VEC_length (fieldoff_s, fieldstack),
3985          sizeof (fieldoff_s),
3986          fieldoff_compare);
3987 }
3988
3989 /* Return true if V is a tree that we can have subvars for.
3990    Normally, this is any aggregate type.  Also complex
3991    types which are not gimple registers can have subvars.  */
3992
3993 static inline bool
3994 var_can_have_subvars (const_tree v)
3995 {
3996   /* Volatile variables should never have subvars.  */
3997   if (TREE_THIS_VOLATILE (v))
3998     return false;
3999
4000   /* Non decls or memory tags can never have subvars.  */
4001   if (!DECL_P (v))
4002     return false;
4003
4004   /* Aggregates without overlapping fields can have subvars.  */
4005   if (TREE_CODE (TREE_TYPE (v)) == RECORD_TYPE)
4006     return true;
4007
4008   return false;
4009 }
4010
4011 /* Given a TYPE, and a vector of field offsets FIELDSTACK, push all
4012    the fields of TYPE onto fieldstack, recording their offsets along
4013    the way.
4014
4015    OFFSET is used to keep track of the offset in this entire
4016    structure, rather than just the immediately containing structure.
4017    Returns the number of fields pushed.  */
4018
4019 static int
4020 push_fields_onto_fieldstack (tree type, VEC(fieldoff_s,heap) **fieldstack,
4021                              HOST_WIDE_INT offset)
4022 {
4023   tree field;
4024   int count = 0;
4025
4026   if (TREE_CODE (type) != RECORD_TYPE)
4027     return 0;
4028
4029   /* If the vector of fields is growing too big, bail out early.
4030      Callers check for VEC_length <= MAX_FIELDS_FOR_FIELD_SENSITIVE, make
4031      sure this fails.  */
4032   if (VEC_length (fieldoff_s, *fieldstack) > MAX_FIELDS_FOR_FIELD_SENSITIVE)
4033     return 0;
4034
4035   for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
4036     if (TREE_CODE (field) == FIELD_DECL)
4037       {
4038         bool push = false;
4039         int pushed = 0;
4040         HOST_WIDE_INT foff = bitpos_of_field (field);
4041
4042         if (!var_can_have_subvars (field)
4043             || TREE_CODE (TREE_TYPE (field)) == QUAL_UNION_TYPE
4044             || TREE_CODE (TREE_TYPE (field)) == UNION_TYPE)
4045           push = true;
4046         else if (!(pushed = push_fields_onto_fieldstack
4047                    (TREE_TYPE (field), fieldstack, offset + foff))
4048                  && (DECL_SIZE (field)
4049                      && !integer_zerop (DECL_SIZE (field))))
4050           /* Empty structures may have actual size, like in C++.  So
4051              see if we didn't push any subfields and the size is
4052              nonzero, push the field onto the stack.  */
4053           push = true;
4054
4055         if (push)
4056           {
4057             fieldoff_s *pair = NULL;
4058             bool has_unknown_size = false;
4059
4060             if (!VEC_empty (fieldoff_s, *fieldstack))
4061               pair = VEC_last (fieldoff_s, *fieldstack);
4062
4063             if (!DECL_SIZE (field)
4064                 || !host_integerp (DECL_SIZE (field), 1))
4065               has_unknown_size = true;
4066
4067             /* If adjacent fields do not contain pointers merge them.  */
4068             if (pair
4069                 && !pair->may_have_pointers
4070                 && !could_have_pointers (field)
4071                 && !pair->has_unknown_size
4072                 && !has_unknown_size
4073                 && pair->offset + (HOST_WIDE_INT)pair->size == offset + foff)
4074               {
4075                 pair = VEC_last (fieldoff_s, *fieldstack);
4076                 pair->size += TREE_INT_CST_LOW (DECL_SIZE (field));
4077               }
4078             else
4079               {
4080                 pair = VEC_safe_push (fieldoff_s, heap, *fieldstack, NULL);
4081                 pair->offset = offset + foff;
4082                 pair->has_unknown_size = has_unknown_size;
4083                 if (!has_unknown_size)
4084                   pair->size = TREE_INT_CST_LOW (DECL_SIZE (field));
4085                 else
4086                   pair->size = -1;
4087                 pair->may_have_pointers = could_have_pointers (field);
4088                 count++;
4089               }
4090           }
4091         else
4092           count += pushed;
4093       }
4094
4095   return count;
4096 }
4097
4098 /* Create a constraint ID = &FROM.  */
4099
4100 static void
4101 make_constraint_from (varinfo_t vi, int from)
4102 {
4103   struct constraint_expr lhs, rhs;
4104
4105   lhs.var = vi->id;
4106   lhs.offset = 0;
4107   lhs.type = SCALAR;
4108
4109   rhs.var = from;
4110   rhs.offset = 0;
4111   rhs.type = ADDRESSOF;
4112   process_constraint (new_constraint (lhs, rhs));
4113 }
4114
4115 /* Create a constraint ID = FROM.  */
4116
4117 static void
4118 make_copy_constraint (varinfo_t vi, int from)
4119 {
4120   struct constraint_expr lhs, rhs;
4121
4122   lhs.var = vi->id;
4123   lhs.offset = 0;
4124   lhs.type = SCALAR;
4125
4126   rhs.var = from;
4127   rhs.offset = 0;
4128   rhs.type = SCALAR;
4129   process_constraint (new_constraint (lhs, rhs));
4130 }
4131
4132 /* Count the number of arguments DECL has, and set IS_VARARGS to true
4133    if it is a varargs function.  */
4134
4135 static unsigned int
4136 count_num_arguments (tree decl, bool *is_varargs)
4137 {
4138   unsigned int i = 0;
4139   tree t;
4140
4141   for (t = TYPE_ARG_TYPES (TREE_TYPE (decl));
4142        t;
4143        t = TREE_CHAIN (t))
4144     {
4145       if (TREE_VALUE (t) == void_type_node)
4146         break;
4147       i++;
4148     }
4149
4150   if (!t)
4151     *is_varargs = true;
4152   return i;
4153 }
4154
4155 /* Creation function node for DECL, using NAME, and return the index
4156    of the variable we've created for the function.  */
4157
4158 static unsigned int
4159 create_function_info_for (tree decl, const char *name)
4160 {
4161   unsigned int index = VEC_length (varinfo_t, varmap);
4162   varinfo_t vi;
4163   tree arg;
4164   unsigned int i;
4165   bool is_varargs = false;
4166
4167   /* Create the variable info.  */
4168
4169   vi = new_var_info (decl, index, name);
4170   vi->decl = decl;
4171   vi->offset = 0;
4172   vi->size = 1;
4173   vi->fullsize = count_num_arguments (decl, &is_varargs) + 1;
4174   insert_vi_for_tree (vi->decl, vi);
4175   VEC_safe_push (varinfo_t, heap, varmap, vi);
4176
4177   stats.total_vars++;
4178
4179   /* If it's varargs, we don't know how many arguments it has, so we
4180      can't do much.  */
4181   if (is_varargs)
4182     {
4183       vi->fullsize = ~0;
4184       vi->size = ~0;
4185       vi->is_unknown_size_var = true;
4186       return index;
4187     }
4188
4189
4190   arg = DECL_ARGUMENTS (decl);
4191
4192   /* Set up variables for each argument.  */
4193   for (i = 1; i < vi->fullsize; i++)
4194     {
4195       varinfo_t argvi;
4196       const char *newname;
4197       char *tempname;
4198       unsigned int newindex;
4199       tree argdecl = decl;
4200
4201       if (arg)
4202         argdecl = arg;
4203
4204       newindex = VEC_length (varinfo_t, varmap);
4205       asprintf (&tempname, "%s.arg%d", name, i-1);
4206       newname = ggc_strdup (tempname);
4207       free (tempname);
4208
4209       argvi = new_var_info (argdecl, newindex, newname);
4210       argvi->decl = argdecl;
4211       VEC_safe_push (varinfo_t, heap, varmap, argvi);
4212       argvi->offset = i;
4213       argvi->size = 1;
4214       argvi->is_full_var = true;
4215       argvi->fullsize = vi->fullsize;
4216       insert_into_field_list_sorted (vi, argvi);
4217       stats.total_vars ++;
4218       if (arg)
4219         {
4220           insert_vi_for_tree (arg, argvi);
4221           arg = TREE_CHAIN (arg);
4222         }
4223     }
4224
4225   /* Create a variable for the return var.  */
4226   if (DECL_RESULT (decl) != NULL
4227       || !VOID_TYPE_P (TREE_TYPE (TREE_TYPE (decl))))
4228     {
4229       varinfo_t resultvi;
4230       const char *newname;
4231       char *tempname;
4232       unsigned int newindex;
4233       tree resultdecl = decl;
4234
4235       vi->fullsize ++;
4236
4237       if (DECL_RESULT (decl))
4238         resultdecl = DECL_RESULT (decl);
4239
4240       newindex = VEC_length (varinfo_t, varmap);
4241       asprintf (&tempname, "%s.result", name);
4242       newname = ggc_strdup (tempname);
4243       free (tempname);
4244
4245       resultvi = new_var_info (resultdecl, newindex, newname);
4246       resultvi->decl = resultdecl;
4247       VEC_safe_push (varinfo_t, heap, varmap, resultvi);
4248       resultvi->offset = i;
4249       resultvi->size = 1;
4250       resultvi->fullsize = vi->fullsize;
4251       resultvi->is_full_var = true;
4252       insert_into_field_list_sorted (vi, resultvi);
4253       stats.total_vars ++;
4254       if (DECL_RESULT (decl))
4255         insert_vi_for_tree (DECL_RESULT (decl), resultvi);
4256     }
4257   return index;
4258 }
4259
4260
4261 /* Return true if FIELDSTACK contains fields that overlap.
4262    FIELDSTACK is assumed to be sorted by offset.  */
4263
4264 static bool
4265 check_for_overlaps (VEC (fieldoff_s,heap) *fieldstack)
4266 {
4267   fieldoff_s *fo = NULL;
4268   unsigned int i;
4269   HOST_WIDE_INT lastoffset = -1;
4270
4271   for (i = 0; VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
4272     {
4273       if (fo->offset == lastoffset)
4274         return true;
4275       lastoffset = fo->offset;
4276     }
4277   return false;
4278 }
4279
4280 /* Create a varinfo structure for NAME and DECL, and add it to VARMAP.
4281    This will also create any varinfo structures necessary for fields
4282    of DECL.  */
4283
4284 static unsigned int
4285 create_variable_info_for (tree decl, const char *name)
4286 {
4287   unsigned int index = VEC_length (varinfo_t, varmap);
4288   varinfo_t vi;
4289   tree decl_type = TREE_TYPE (decl);
4290   tree declsize = DECL_P (decl) ? DECL_SIZE (decl) : TYPE_SIZE (decl_type);
4291   bool is_global = DECL_P (decl) ? is_global_var (decl) : false;
4292   VEC (fieldoff_s,heap) *fieldstack = NULL;
4293
4294   if (TREE_CODE (decl) == FUNCTION_DECL && in_ipa_mode)
4295     return create_function_info_for (decl, name);
4296
4297   if (var_can_have_subvars (decl) && use_field_sensitive
4298       && (!var_ann (decl)
4299           || var_ann (decl)->noalias_state == 0)
4300       && (!var_ann (decl)
4301           || !var_ann (decl)->is_heapvar))
4302     push_fields_onto_fieldstack (decl_type, &fieldstack, 0);
4303
4304   /* If the variable doesn't have subvars, we may end up needing to
4305      sort the field list and create fake variables for all the
4306      fields.  */
4307   vi = new_var_info (decl, index, name);
4308   vi->decl = decl;
4309   vi->offset = 0;
4310   vi->may_have_pointers = could_have_pointers (decl);
4311   if (!declsize
4312       || !host_integerp (declsize, 1))
4313     {
4314       vi->is_unknown_size_var = true;
4315       vi->fullsize = ~0;
4316       vi->size = ~0;
4317     }
4318   else
4319     {
4320       vi->fullsize = TREE_INT_CST_LOW (declsize);
4321       vi->size = vi->fullsize;
4322     }
4323
4324   insert_vi_for_tree (vi->decl, vi);
4325   VEC_safe_push (varinfo_t, heap, varmap, vi);
4326   if (is_global && (!flag_whole_program || !in_ipa_mode)
4327       && vi->may_have_pointers)
4328     {
4329       if (var_ann (decl)
4330           && var_ann (decl)->noalias_state == NO_ALIAS_ANYTHING)
4331         make_constraint_from (vi, vi->id);
4332       else
4333         make_copy_constraint (vi, nonlocal_id);
4334     }
4335
4336   stats.total_vars++;
4337   if (use_field_sensitive
4338       && !vi->is_unknown_size_var
4339       && var_can_have_subvars (decl)
4340       && VEC_length (fieldoff_s, fieldstack) > 1
4341       && VEC_length (fieldoff_s, fieldstack) <= MAX_FIELDS_FOR_FIELD_SENSITIVE)
4342     {
4343       unsigned int newindex = VEC_length (varinfo_t, varmap);
4344       fieldoff_s *fo = NULL;
4345       bool notokay = false;
4346       unsigned int i;
4347
4348       for (i = 0; !notokay && VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
4349         {
4350           if (fo->has_unknown_size
4351               || fo->offset < 0)
4352             {
4353               notokay = true;
4354               break;
4355             }
4356         }
4357
4358       /* We can't sort them if we have a field with a variable sized type,
4359          which will make notokay = true.  In that case, we are going to return
4360          without creating varinfos for the fields anyway, so sorting them is a
4361          waste to boot.  */
4362       if (!notokay)
4363         {
4364           sort_fieldstack (fieldstack);
4365           /* Due to some C++ FE issues, like PR 22488, we might end up
4366              what appear to be overlapping fields even though they,
4367              in reality, do not overlap.  Until the C++ FE is fixed,
4368              we will simply disable field-sensitivity for these cases.  */
4369           notokay = check_for_overlaps (fieldstack);
4370         }
4371
4372
4373       if (VEC_length (fieldoff_s, fieldstack) != 0)
4374         fo = VEC_index (fieldoff_s, fieldstack, 0);
4375
4376       if (fo == NULL || notokay)
4377         {
4378           vi->is_unknown_size_var = 1;
4379           vi->fullsize = ~0;
4380           vi->size = ~0;
4381           vi->is_full_var = true;
4382           VEC_free (fieldoff_s, heap, fieldstack);
4383           return index;
4384         }
4385
4386       vi->size = fo->size;
4387       vi->offset = fo->offset;
4388       vi->may_have_pointers = fo->may_have_pointers;
4389       for (i = VEC_length (fieldoff_s, fieldstack) - 1;
4390            i >= 1 && VEC_iterate (fieldoff_s, fieldstack, i, fo);
4391            i--)
4392         {
4393           varinfo_t newvi;
4394           const char *newname = "NULL";
4395           char *tempname;
4396
4397           newindex = VEC_length (varinfo_t, varmap);
4398           if (dump_file)
4399             {
4400               asprintf (&tempname, "%s." HOST_WIDE_INT_PRINT_DEC
4401                         "+" HOST_WIDE_INT_PRINT_DEC,
4402                         vi->name, fo->offset, fo->size);
4403               newname = ggc_strdup (tempname);
4404               free (tempname);
4405             }
4406           newvi = new_var_info (decl, newindex, newname);
4407           newvi->offset = fo->offset;
4408           newvi->size = fo->size;
4409           newvi->fullsize = vi->fullsize;
4410           newvi->may_have_pointers = fo->may_have_pointers;
4411           insert_into_field_list (vi, newvi);
4412           VEC_safe_push (varinfo_t, heap, varmap, newvi);
4413           if (is_global && (!flag_whole_program || !in_ipa_mode)
4414               && newvi->may_have_pointers)
4415             make_copy_constraint (newvi, nonlocal_id);
4416
4417           stats.total_vars++;
4418         }
4419     }
4420   else
4421     vi->is_full_var = true;
4422
4423   VEC_free (fieldoff_s, heap, fieldstack);
4424
4425   return index;
4426 }
4427
4428 /* Print out the points-to solution for VAR to FILE.  */
4429
4430 static void
4431 dump_solution_for_var (FILE *file, unsigned int var)
4432 {
4433   varinfo_t vi = get_varinfo (var);
4434   unsigned int i;
4435   bitmap_iterator bi;
4436
4437   if (find (var) != var)
4438     {
4439       varinfo_t vipt = get_varinfo (find (var));
4440       fprintf (file, "%s = same as %s\n", vi->name, vipt->name);
4441     }
4442   else
4443     {
4444       fprintf (file, "%s = { ", vi->name);
4445       EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
4446         {
4447           fprintf (file, "%s ", get_varinfo (i)->name);
4448         }
4449       fprintf (file, "}\n");
4450     }
4451 }
4452
4453 /* Print the points-to solution for VAR to stdout.  */
4454
4455 void
4456 debug_solution_for_var (unsigned int var)
4457 {
4458   dump_solution_for_var (stdout, var);
4459 }
4460
4461 /* Create varinfo structures for all of the variables in the
4462    function for intraprocedural mode.  */
4463
4464 static void
4465 intra_create_variable_infos (void)
4466 {
4467   tree t;
4468   struct constraint_expr lhs, rhs;
4469
4470   /* For each incoming pointer argument arg, create the constraint ARG
4471      = NONLOCAL or a dummy variable if flag_argument_noalias is set.  */
4472   for (t = DECL_ARGUMENTS (current_function_decl); t; t = TREE_CHAIN (t))
4473     {
4474       varinfo_t p;
4475
4476       if (!could_have_pointers (t))
4477         continue;
4478
4479       /* If flag_argument_noalias is set, then function pointer
4480          arguments are guaranteed not to point to each other.  In that
4481          case, create an artificial variable PARM_NOALIAS and the
4482          constraint ARG = &PARM_NOALIAS.  */
4483       if (POINTER_TYPE_P (TREE_TYPE (t)) && flag_argument_noalias > 0)
4484         {
4485           varinfo_t vi;
4486           tree heapvar = heapvar_lookup (t);
4487
4488           lhs.offset = 0;
4489           lhs.type = SCALAR;
4490           lhs.var  = get_vi_for_tree (t)->id;
4491
4492           if (heapvar == NULL_TREE)
4493             {
4494               var_ann_t ann;
4495               heapvar = create_tmp_var_raw (ptr_type_node,
4496                                             "PARM_NOALIAS");
4497               DECL_EXTERNAL (heapvar) = 1;
4498               if (gimple_referenced_vars (cfun))
4499                 add_referenced_var (heapvar);
4500
4501               heapvar_insert (t, heapvar);
4502
4503               ann = get_var_ann (heapvar);
4504               ann->is_heapvar = 1;
4505               if (flag_argument_noalias == 1)
4506                 ann->noalias_state = NO_ALIAS;
4507               else if (flag_argument_noalias == 2)
4508                 ann->noalias_state = NO_ALIAS_GLOBAL;
4509               else if (flag_argument_noalias == 3)
4510                 ann->noalias_state = NO_ALIAS_ANYTHING;
4511               else
4512                 gcc_unreachable ();
4513             }
4514
4515           vi = get_vi_for_tree (heapvar);
4516           vi->is_artificial_var = 1;
4517           vi->is_heap_var = 1;
4518           vi->is_unknown_size_var = true;
4519           vi->fullsize = ~0;
4520           vi->size = ~0;
4521           rhs.var = vi->id;
4522           rhs.type = ADDRESSOF;
4523           rhs.offset = 0;
4524           for (p = get_varinfo (lhs.var); p; p = p->next)
4525             {
4526               struct constraint_expr temp = lhs;
4527               temp.var = p->id;
4528               process_constraint (new_constraint (temp, rhs));
4529             }
4530         }
4531       else
4532         {
4533           varinfo_t arg_vi = get_vi_for_tree (t);
4534
4535           for (p = arg_vi; p; p = p->next)
4536             make_constraint_from (p, nonlocal_id);
4537         }
4538     }
4539
4540   /* Add a constraint for a result decl that is passed by reference.  */
4541   if (DECL_RESULT (cfun->decl)
4542       && DECL_BY_REFERENCE (DECL_RESULT (cfun->decl)))
4543     {
4544       varinfo_t p, result_vi = get_vi_for_tree (DECL_RESULT (cfun->decl));
4545
4546       for (p = result_vi; p; p = p->next)
4547         make_constraint_from (p, nonlocal_id);
4548     }
4549
4550   /* Add a constraint for the incoming static chain parameter.  */
4551   if (cfun->static_chain_decl != NULL_TREE)
4552     {
4553       varinfo_t p, chain_vi = get_vi_for_tree (cfun->static_chain_decl);
4554
4555       for (p = chain_vi; p; p = p->next)
4556         make_constraint_from (p, nonlocal_id);
4557     }
4558 }
4559
4560 /* Structure used to put solution bitmaps in a hashtable so they can
4561    be shared among variables with the same points-to set.  */
4562
4563 typedef struct shared_bitmap_info
4564 {
4565   bitmap pt_vars;
4566   hashval_t hashcode;
4567 } *shared_bitmap_info_t;
4568 typedef const struct shared_bitmap_info *const_shared_bitmap_info_t;
4569
4570 static htab_t shared_bitmap_table;
4571
4572 /* Hash function for a shared_bitmap_info_t */
4573
4574 static hashval_t
4575 shared_bitmap_hash (const void *p)
4576 {
4577   const_shared_bitmap_info_t const bi = (const_shared_bitmap_info_t) p;
4578   return bi->hashcode;
4579 }
4580
4581 /* Equality function for two shared_bitmap_info_t's. */
4582
4583 static int
4584 shared_bitmap_eq (const void *p1, const void *p2)
4585 {
4586   const_shared_bitmap_info_t const sbi1 = (const_shared_bitmap_info_t) p1;
4587   const_shared_bitmap_info_t const sbi2 = (const_shared_bitmap_info_t) p2;
4588   return bitmap_equal_p (sbi1->pt_vars, sbi2->pt_vars);
4589 }
4590
4591 /* Lookup a bitmap in the shared bitmap hashtable, and return an already
4592    existing instance if there is one, NULL otherwise.  */
4593
4594 static bitmap
4595 shared_bitmap_lookup (bitmap pt_vars)
4596 {
4597   void **slot;
4598   struct shared_bitmap_info sbi;
4599
4600   sbi.pt_vars = pt_vars;
4601   sbi.hashcode = bitmap_hash (pt_vars);
4602
4603   slot = htab_find_slot_with_hash (shared_bitmap_table, &sbi,
4604                                    sbi.hashcode, NO_INSERT);
4605   if (!slot)
4606     return NULL;
4607   else
4608     return ((shared_bitmap_info_t) *slot)->pt_vars;
4609 }
4610
4611
4612 /* Add a bitmap to the shared bitmap hashtable.  */
4613
4614 static void
4615 shared_bitmap_add (bitmap pt_vars)
4616 {
4617   void **slot;
4618   shared_bitmap_info_t sbi = XNEW (struct shared_bitmap_info);
4619
4620   sbi->pt_vars = pt_vars;
4621   sbi->hashcode = bitmap_hash (pt_vars);
4622
4623   slot = htab_find_slot_with_hash (shared_bitmap_table, sbi,
4624                                    sbi->hashcode, INSERT);
4625   gcc_assert (!*slot);
4626   *slot = (void *) sbi;
4627 }
4628
4629
4630 /* Set bits in INTO corresponding to the variable uids in solution set FROM.  */
4631
4632 static void 
4633 set_uids_in_ptset (bitmap into, bitmap from, struct pt_solution *pt)
4634 {
4635   unsigned int i;
4636   bitmap_iterator bi;
4637
4638   EXECUTE_IF_SET_IN_BITMAP (from, 0, i, bi)
4639     {
4640       varinfo_t vi = get_varinfo (i);
4641
4642       /* The only artificial variables that are allowed in a may-alias
4643          set are heap variables.  */
4644       if (vi->is_artificial_var && !vi->is_heap_var)
4645         continue;
4646
4647       if (TREE_CODE (vi->decl) == VAR_DECL
4648           || TREE_CODE (vi->decl) == PARM_DECL
4649           || TREE_CODE (vi->decl) == RESULT_DECL)
4650         {
4651           /* Add the decl to the points-to set.  Note that the points-to
4652              set contains global variables.  */
4653           bitmap_set_bit (into, DECL_UID (vi->decl));
4654           if (is_global_var (vi->decl))
4655             pt->vars_contains_global = true;
4656         }
4657     }
4658 }
4659
4660
4661 static bool have_alias_info = false;
4662
4663 /* Compute the points-to solution *PT for the variable VI.  */
4664
4665 static void
4666 find_what_var_points_to (varinfo_t vi, struct pt_solution *pt)
4667 {
4668   unsigned int i;
4669   bitmap_iterator bi;
4670   bitmap finished_solution;
4671   bitmap result;
4672   tree ptr = vi->decl;
4673
4674   memset (pt, 0, sizeof (struct pt_solution));
4675
4676   /* This variable may have been collapsed, let's get the real
4677      variable.  */
4678   vi = get_varinfo (find (vi->id));
4679
4680   /* Translate artificial variables into SSA_NAME_PTR_INFO
4681      attributes.  */
4682   EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
4683     {
4684       varinfo_t vi = get_varinfo (i);
4685
4686       if (vi->is_artificial_var)
4687         {
4688           if (vi->id == nothing_id)
4689             pt->null = 1;
4690           else if (vi->id == escaped_id)
4691             pt->escaped = 1;
4692           else if (vi->id == callused_id)
4693             gcc_unreachable ();
4694           else if (vi->id == nonlocal_id)
4695             pt->nonlocal = 1;
4696           else if (vi->is_heap_var)
4697             /* We represent heapvars in the points-to set properly.  */
4698             ;
4699           else if (vi->id == anything_id
4700                    || vi->id == readonly_id
4701                    || vi->id == integer_id)
4702             pt->anything = 1;
4703         }
4704     }
4705
4706   /* Instead of doing extra work, simply do not create
4707      elaborate points-to information for pt_anything pointers.  */
4708   if (pt->anything)
4709     return;
4710
4711   /* Share the final set of variables when possible.  */
4712   finished_solution = BITMAP_GGC_ALLOC ();
4713   stats.points_to_sets_created++;
4714
4715   if (TREE_CODE (ptr) == SSA_NAME)
4716     ptr = SSA_NAME_VAR (ptr);
4717
4718   set_uids_in_ptset (finished_solution, vi->solution, pt);
4719   result = shared_bitmap_lookup (finished_solution);
4720   if (!result)
4721     {
4722       shared_bitmap_add (finished_solution);
4723       pt->vars = finished_solution;
4724     }
4725   else
4726     {
4727       pt->vars = result;
4728       bitmap_clear (finished_solution);
4729     }
4730 }
4731
4732 /* Given a pointer variable P, fill in its points-to set.  */
4733
4734 static void
4735 find_what_p_points_to (tree p)
4736 {
4737   struct ptr_info_def *pi;
4738   tree lookup_p = p;
4739   varinfo_t vi;
4740
4741   /* For parameters, get at the points-to set for the actual parm
4742      decl.  */
4743   if (TREE_CODE (p) == SSA_NAME
4744       && TREE_CODE (SSA_NAME_VAR (p)) == PARM_DECL
4745       && SSA_NAME_IS_DEFAULT_DEF (p))
4746     lookup_p = SSA_NAME_VAR (p);
4747
4748   vi = lookup_vi_for_tree (lookup_p);
4749   if (!vi)
4750     return;
4751
4752   pi = get_ptr_info (p);
4753   find_what_var_points_to (vi, &pi->pt);
4754 }
4755
4756
4757 /* Query statistics for points-to solutions.  */
4758
4759 static struct {
4760   unsigned HOST_WIDE_INT pt_solution_includes_may_alias;
4761   unsigned HOST_WIDE_INT pt_solution_includes_no_alias;
4762   unsigned HOST_WIDE_INT pt_solutions_intersect_may_alias;
4763   unsigned HOST_WIDE_INT pt_solutions_intersect_no_alias;
4764 } pta_stats;
4765
4766 void
4767 dump_pta_stats (FILE *s)
4768 {
4769   fprintf (s, "\nPTA query stats:\n");
4770   fprintf (s, "  pt_solution_includes: "
4771            HOST_WIDE_INT_PRINT_DEC" disambiguations, "
4772            HOST_WIDE_INT_PRINT_DEC" queries\n",
4773            pta_stats.pt_solution_includes_no_alias,
4774            pta_stats.pt_solution_includes_no_alias
4775            + pta_stats.pt_solution_includes_may_alias);
4776   fprintf (s, "  pt_solutions_intersect: "
4777            HOST_WIDE_INT_PRINT_DEC" disambiguations, "
4778            HOST_WIDE_INT_PRINT_DEC" queries\n",
4779            pta_stats.pt_solutions_intersect_no_alias,
4780            pta_stats.pt_solutions_intersect_no_alias
4781            + pta_stats.pt_solutions_intersect_may_alias);
4782 }
4783
4784
4785 /* Reset the points-to solution *PT to a conservative default
4786    (point to anything).  */
4787
4788 void
4789 pt_solution_reset (struct pt_solution *pt)
4790 {
4791   memset (pt, 0, sizeof (struct pt_solution));
4792   pt->anything = true;
4793 }
4794
4795 /* Return true if the points-to solution *PT is empty.  */
4796
4797 static bool
4798 pt_solution_empty_p (struct pt_solution *pt)
4799 {
4800   if (pt->anything
4801       || pt->nonlocal)
4802     return false;
4803
4804   if (pt->vars
4805       && !bitmap_empty_p (pt->vars))
4806     return false;
4807
4808   /* If the solution includes ESCAPED, check if that is empty.  */
4809   if (pt->escaped
4810       && !pt_solution_empty_p (&cfun->gimple_df->escaped))
4811     return false;
4812
4813   return true;
4814 }
4815
4816 /* Return true if the points-to solution *PT includes global memory.  */
4817
4818 bool
4819 pt_solution_includes_global (struct pt_solution *pt)
4820 {
4821   if (pt->anything
4822       || pt->nonlocal
4823       || pt->vars_contains_global)
4824     return true;
4825
4826   if (pt->escaped)
4827     return pt_solution_includes_global (&cfun->gimple_df->escaped);
4828
4829   return false;
4830 }
4831
4832 /* Return true if the points-to solution *PT includes the variable
4833    declaration DECL.  */
4834
4835 static bool
4836 pt_solution_includes_1 (struct pt_solution *pt, const_tree decl)
4837 {
4838   if (pt->anything)
4839     return true;
4840
4841   if (pt->nonlocal
4842       && is_global_var (decl))
4843     return true;
4844
4845   if (pt->vars
4846       && bitmap_bit_p (pt->vars, DECL_UID (decl)))
4847     return true;
4848
4849   /* If the solution includes ESCAPED, check it.  */
4850   if (pt->escaped
4851       && pt_solution_includes_1 (&cfun->gimple_df->escaped, decl))
4852     return true;
4853
4854   return false;
4855 }
4856
4857 bool
4858 pt_solution_includes (struct pt_solution *pt, const_tree decl)
4859 {
4860   bool res = pt_solution_includes_1 (pt, decl);
4861   if (res)
4862     ++pta_stats.pt_solution_includes_may_alias;
4863   else
4864     ++pta_stats.pt_solution_includes_no_alias;
4865   return res;
4866 }
4867
4868 /* Return true if both points-to solutions PT1 and PT2 have a non-empty
4869    intersection.  */
4870
4871 static bool
4872 pt_solutions_intersect_1 (struct pt_solution *pt1, struct pt_solution *pt2)
4873 {
4874   if (pt1->anything || pt2->anything)
4875     return true;
4876
4877   /* If either points to unknown global memory and the other points to
4878      any global memory they alias.  */
4879   if ((pt1->nonlocal
4880        && (pt2->nonlocal
4881            || pt2->vars_contains_global))
4882       || (pt2->nonlocal
4883           && pt1->vars_contains_global))
4884     return true;
4885
4886   /* Check the escaped solution if required.  */
4887   if ((pt1->escaped || pt2->escaped)
4888       && !pt_solution_empty_p (&cfun->gimple_df->escaped))
4889     {
4890       /* If both point to escaped memory and that solution
4891          is not empty they alias.  */
4892       if (pt1->escaped && pt2->escaped)
4893         return true;
4894
4895       /* If either points to escaped memory see if the escaped solution
4896          intersects with the other.  */
4897       if ((pt1->escaped
4898            && pt_solutions_intersect_1 (&cfun->gimple_df->escaped, pt2))
4899           || (pt2->escaped
4900               && pt_solutions_intersect_1 (&cfun->gimple_df->escaped, pt1)))
4901         return true;
4902     }
4903
4904   /* Now both pointers alias if their points-to solution intersects.  */
4905   return (pt1->vars
4906           && pt2->vars
4907           && bitmap_intersect_p (pt1->vars, pt2->vars));
4908 }
4909
4910 bool
4911 pt_solutions_intersect (struct pt_solution *pt1, struct pt_solution *pt2)
4912 {
4913   bool res = pt_solutions_intersect_1 (pt1, pt2);
4914   if (res)
4915     ++pta_stats.pt_solutions_intersect_may_alias;
4916   else
4917     ++pta_stats.pt_solutions_intersect_no_alias;
4918   return res;
4919 }
4920
4921
4922 /* Dump points-to information to OUTFILE.  */
4923
4924 static void
4925 dump_sa_points_to_info (FILE *outfile)
4926 {
4927   unsigned int i;
4928
4929   fprintf (outfile, "\nPoints-to sets\n\n");
4930
4931   if (dump_flags & TDF_STATS)
4932     {
4933       fprintf (outfile, "Stats:\n");
4934       fprintf (outfile, "Total vars:               %d\n", stats.total_vars);
4935       fprintf (outfile, "Non-pointer vars:          %d\n",
4936                stats.nonpointer_vars);
4937       fprintf (outfile, "Statically unified vars:  %d\n",
4938                stats.unified_vars_static);
4939       fprintf (outfile, "Dynamically unified vars: %d\n",
4940                stats.unified_vars_dynamic);
4941       fprintf (outfile, "Iterations:               %d\n", stats.iterations);
4942       fprintf (outfile, "Number of edges:          %d\n", stats.num_edges);
4943       fprintf (outfile, "Number of implicit edges: %d\n",
4944                stats.num_implicit_edges);
4945     }
4946
4947   for (i = 0; i < VEC_length (varinfo_t, varmap); i++)
4948     dump_solution_for_var (outfile, i);
4949 }
4950
4951
4952 /* Debug points-to information to stderr.  */
4953
4954 void
4955 debug_sa_points_to_info (void)
4956 {
4957   dump_sa_points_to_info (stderr);
4958 }
4959
4960
4961 /* Initialize the always-existing constraint variables for NULL
4962    ANYTHING, READONLY, and INTEGER */
4963
4964 static void
4965 init_base_vars (void)
4966 {
4967   struct constraint_expr lhs, rhs;
4968
4969   /* Create the NULL variable, used to represent that a variable points
4970      to NULL.  */
4971   nothing_tree = create_tmp_var_raw (void_type_node, "NULL");
4972   var_nothing = new_var_info (nothing_tree, nothing_id, "NULL");
4973   insert_vi_for_tree (nothing_tree, var_nothing);
4974   var_nothing->is_artificial_var = 1;
4975   var_nothing->offset = 0;
4976   var_nothing->size = ~0;
4977   var_nothing->fullsize = ~0;
4978   var_nothing->is_special_var = 1;
4979   VEC_safe_push (varinfo_t, heap, varmap, var_nothing);
4980
4981   /* Create the ANYTHING variable, used to represent that a variable
4982      points to some unknown piece of memory.  */
4983   anything_tree = create_tmp_var_raw (ptr_type_node, "ANYTHING");
4984   var_anything = new_var_info (anything_tree, anything_id, "ANYTHING");
4985   insert_vi_for_tree (anything_tree, var_anything);
4986   var_anything->is_artificial_var = 1;
4987   var_anything->size = ~0;
4988   var_anything->offset = 0;
4989   var_anything->next = NULL;
4990   var_anything->fullsize = ~0;
4991   var_anything->is_special_var = 1;
4992
4993   /* Anything points to anything.  This makes deref constraints just
4994      work in the presence of linked list and other p = *p type loops,
4995      by saying that *ANYTHING = ANYTHING. */
4996   VEC_safe_push (varinfo_t, heap, varmap, var_anything);
4997   lhs.type = SCALAR;
4998   lhs.var = anything_id;
4999   lhs.offset = 0;
5000   rhs.type = ADDRESSOF;
5001   rhs.var = anything_id;
5002   rhs.offset = 0;
5003
5004   /* This specifically does not use process_constraint because
5005      process_constraint ignores all anything = anything constraints, since all
5006      but this one are redundant.  */
5007   VEC_safe_push (constraint_t, heap, constraints, new_constraint (lhs, rhs));
5008
5009   /* Create the READONLY variable, used to represent that a variable
5010      points to readonly memory.  */
5011   readonly_tree = create_tmp_var_raw (ptr_type_node, "READONLY");
5012   var_readonly = new_var_info (readonly_tree, readonly_id, "READONLY");
5013   var_readonly->is_artificial_var = 1;
5014   var_readonly->offset = 0;
5015   var_readonly->size = ~0;
5016   var_readonly->fullsize = ~0;
5017   var_readonly->next = NULL;
5018   var_readonly->is_special_var = 1;
5019   insert_vi_for_tree (readonly_tree, var_readonly);
5020   VEC_safe_push (varinfo_t, heap, varmap, var_readonly);
5021
5022   /* readonly memory points to anything, in order to make deref
5023      easier.  In reality, it points to anything the particular
5024      readonly variable can point to, but we don't track this
5025      separately. */
5026   lhs.type = SCALAR;
5027   lhs.var = readonly_id;
5028   lhs.offset = 0;
5029   rhs.type = ADDRESSOF;
5030   rhs.var = readonly_id;  /* FIXME */
5031   rhs.offset = 0;
5032   process_constraint (new_constraint (lhs, rhs));
5033
5034   /* Create the ESCAPED variable, used to represent the set of escaped
5035      memory.  */
5036   escaped_tree = create_tmp_var_raw (ptr_type_node, "ESCAPED");
5037   var_escaped = new_var_info (escaped_tree, escaped_id, "ESCAPED");
5038   insert_vi_for_tree (escaped_tree, var_escaped);
5039   var_escaped->is_artificial_var = 1;
5040   var_escaped->offset = 0;
5041   var_escaped->size = ~0;
5042   var_escaped->fullsize = ~0;
5043   var_escaped->is_special_var = 0;
5044   VEC_safe_push (varinfo_t, heap, varmap, var_escaped);
5045   gcc_assert (VEC_index (varinfo_t, varmap, 3) == var_escaped);
5046
5047   /* Create the NONLOCAL variable, used to represent the set of nonlocal
5048      memory.  */
5049   nonlocal_tree = create_tmp_var_raw (ptr_type_node, "NONLOCAL");
5050   var_nonlocal = new_var_info (nonlocal_tree, nonlocal_id, "NONLOCAL");
5051   insert_vi_for_tree (nonlocal_tree, var_nonlocal);
5052   var_nonlocal->is_artificial_var = 1;
5053   var_nonlocal->offset = 0;
5054   var_nonlocal->size = ~0;
5055   var_nonlocal->fullsize = ~0;
5056   var_nonlocal->is_special_var = 1;
5057   VEC_safe_push (varinfo_t, heap, varmap, var_nonlocal);
5058
5059   /* ESCAPED = *ESCAPED, because escaped is may-deref'd at calls, etc.  */
5060   lhs.type = SCALAR;
5061   lhs.var = escaped_id;
5062   lhs.offset = 0;
5063   rhs.type = DEREF;
5064   rhs.var = escaped_id;
5065   rhs.offset = 0;
5066   process_constraint (new_constraint (lhs, rhs));
5067
5068   /* ESCAPED = ESCAPED + UNKNOWN_OFFSET, because if a sub-field escapes the
5069      whole variable escapes.  */
5070   lhs.type = SCALAR;
5071   lhs.var = escaped_id;
5072   lhs.offset = 0;
5073   rhs.type = SCALAR;
5074   rhs.var = escaped_id;
5075   rhs.offset = UNKNOWN_OFFSET;
5076   process_constraint (new_constraint (lhs, rhs));
5077
5078   /* *ESCAPED = NONLOCAL.  This is true because we have to assume
5079      everything pointed to by escaped points to what global memory can
5080      point to.  */
5081   lhs.type = DEREF;
5082   lhs.var = escaped_id;
5083   lhs.offset = 0;
5084   rhs.type = SCALAR;
5085   rhs.var = nonlocal_id;
5086   rhs.offset = 0;
5087   process_constraint (new_constraint (lhs, rhs));
5088
5089   /* NONLOCAL = &NONLOCAL, NONLOCAL = &ESCAPED.  This is true because
5090      global memory may point to global memory and escaped memory.  */
5091   lhs.type = SCALAR;
5092   lhs.var = nonlocal_id;
5093   lhs.offset = 0;
5094   rhs.type = ADDRESSOF;
5095   rhs.var = nonlocal_id;
5096   rhs.offset = 0;
5097   process_constraint (new_constraint (lhs, rhs));
5098   rhs.type = ADDRESSOF;
5099   rhs.var = escaped_id;
5100   rhs.offset = 0;
5101   process_constraint (new_constraint (lhs, rhs));
5102
5103   /* Create the CALLUSED variable, used to represent the set of call-used
5104      memory.  */
5105   callused_tree = create_tmp_var_raw (ptr_type_node, "CALLUSED");
5106   var_callused = new_var_info (callused_tree, callused_id, "CALLUSED");
5107   insert_vi_for_tree (callused_tree, var_callused);
5108   var_callused->is_artificial_var = 1;
5109   var_callused->offset = 0;
5110   var_callused->size = ~0;
5111   var_callused->fullsize = ~0;
5112   var_callused->is_special_var = 0;
5113   VEC_safe_push (varinfo_t, heap, varmap, var_callused);
5114
5115   /* CALLUSED = *CALLUSED, because call-used is may-deref'd at calls, etc.  */
5116   lhs.type = SCALAR;
5117   lhs.var = callused_id;
5118   lhs.offset = 0;
5119   rhs.type = DEREF;
5120   rhs.var = callused_id;
5121   rhs.offset = 0;
5122   process_constraint (new_constraint (lhs, rhs));
5123
5124   /* CALLUSED = CALLUSED + UNKNOWN, because if a sub-field is call-used the
5125      whole variable is call-used.  */
5126   lhs.type = SCALAR;
5127   lhs.var = callused_id;
5128   lhs.offset = 0;
5129   rhs.type = SCALAR;
5130   rhs.var = callused_id;
5131   rhs.offset = UNKNOWN_OFFSET;
5132   process_constraint (new_constraint (lhs, rhs));
5133
5134   /* Create the STOREDANYTHING variable, used to represent the set of
5135      variables stored to *ANYTHING.  */
5136   storedanything_tree = create_tmp_var_raw (ptr_type_node, "STOREDANYTHING");
5137   var_storedanything = new_var_info (storedanything_tree, storedanything_id,
5138                                      "STOREDANYTHING");
5139   insert_vi_for_tree (storedanything_tree, var_storedanything);
5140   var_storedanything->is_artificial_var = 1;
5141   var_storedanything->offset = 0;
5142   var_storedanything->size = ~0;
5143   var_storedanything->fullsize = ~0;
5144   var_storedanything->is_special_var = 0;
5145   VEC_safe_push (varinfo_t, heap, varmap, var_storedanything);
5146
5147   /* Create the INTEGER variable, used to represent that a variable points
5148      to what an INTEGER "points to".  */
5149   integer_tree = create_tmp_var_raw (ptr_type_node, "INTEGER");
5150   var_integer = new_var_info (integer_tree, integer_id, "INTEGER");
5151   insert_vi_for_tree (integer_tree, var_integer);
5152   var_integer->is_artificial_var = 1;
5153   var_integer->size = ~0;
5154   var_integer->fullsize = ~0;
5155   var_integer->offset = 0;
5156   var_integer->next = NULL;
5157   var_integer->is_special_var = 1;
5158   VEC_safe_push (varinfo_t, heap, varmap, var_integer);
5159
5160   /* INTEGER = ANYTHING, because we don't know where a dereference of
5161      a random integer will point to.  */
5162   lhs.type = SCALAR;
5163   lhs.var = integer_id;
5164   lhs.offset = 0;
5165   rhs.type = ADDRESSOF;
5166   rhs.var = anything_id;
5167   rhs.offset = 0;
5168   process_constraint (new_constraint (lhs, rhs));
5169 }
5170
5171 /* Initialize things necessary to perform PTA */
5172
5173 static void
5174 init_alias_vars (void)
5175 {
5176   use_field_sensitive = (MAX_FIELDS_FOR_FIELD_SENSITIVE > 1);
5177
5178   bitmap_obstack_initialize (&pta_obstack);
5179   bitmap_obstack_initialize (&oldpta_obstack);
5180   bitmap_obstack_initialize (&predbitmap_obstack);
5181
5182   constraint_pool = create_alloc_pool ("Constraint pool",
5183                                        sizeof (struct constraint), 30);
5184   variable_info_pool = create_alloc_pool ("Variable info pool",
5185                                           sizeof (struct variable_info), 30);
5186   constraints = VEC_alloc (constraint_t, heap, 8);
5187   varmap = VEC_alloc (varinfo_t, heap, 8);
5188   vi_for_tree = pointer_map_create ();
5189
5190   memset (&stats, 0, sizeof (stats));
5191   shared_bitmap_table = htab_create (511, shared_bitmap_hash,
5192                                      shared_bitmap_eq, free);
5193   init_base_vars ();
5194 }
5195
5196 /* Remove the REF and ADDRESS edges from GRAPH, as well as all the
5197    predecessor edges.  */
5198
5199 static void
5200 remove_preds_and_fake_succs (constraint_graph_t graph)
5201 {
5202   unsigned int i;
5203
5204   /* Clear the implicit ref and address nodes from the successor
5205      lists.  */
5206   for (i = 0; i < FIRST_REF_NODE; i++)
5207     {
5208       if (graph->succs[i])
5209         bitmap_clear_range (graph->succs[i], FIRST_REF_NODE,
5210                             FIRST_REF_NODE * 2);
5211     }
5212
5213   /* Free the successor list for the non-ref nodes.  */
5214   for (i = FIRST_REF_NODE; i < graph->size; i++)
5215     {
5216       if (graph->succs[i])
5217         BITMAP_FREE (graph->succs[i]);
5218     }
5219
5220   /* Now reallocate the size of the successor list as, and blow away
5221      the predecessor bitmaps.  */
5222   graph->size = VEC_length (varinfo_t, varmap);
5223   graph->succs = XRESIZEVEC (bitmap, graph->succs, graph->size);
5224
5225   free (graph->implicit_preds);
5226   graph->implicit_preds = NULL;
5227   free (graph->preds);
5228   graph->preds = NULL;
5229   bitmap_obstack_release (&predbitmap_obstack);
5230 }
5231
5232 /* Initialize the heapvar for statement mapping.  */
5233
5234 static void
5235 init_alias_heapvars (void)
5236 {
5237   if (!heapvar_for_stmt)
5238     heapvar_for_stmt = htab_create_ggc (11, tree_map_hash, tree_map_eq,
5239                                         NULL);
5240 }
5241
5242 /* Delete the heapvar for statement mapping.  */
5243
5244 void
5245 delete_alias_heapvars (void)
5246 {
5247   if (heapvar_for_stmt)
5248     htab_delete (heapvar_for_stmt);
5249   heapvar_for_stmt = NULL;
5250 }
5251
5252 /* Create points-to sets for the current function.  See the comments
5253    at the start of the file for an algorithmic overview.  */
5254
5255 static void
5256 compute_points_to_sets (void)
5257 {
5258   struct scc_info *si;
5259   basic_block bb;
5260   unsigned i;
5261
5262   timevar_push (TV_TREE_PTA);
5263
5264   init_alias_vars ();
5265   init_alias_heapvars ();
5266
5267   intra_create_variable_infos ();
5268
5269   /* Now walk all statements and derive aliases.  */
5270   FOR_EACH_BB (bb)
5271     {
5272       gimple_stmt_iterator gsi;
5273
5274       for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5275         {
5276           gimple phi = gsi_stmt (gsi);
5277
5278           if (is_gimple_reg (gimple_phi_result (phi)))
5279             find_func_aliases (phi);
5280         }
5281
5282       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5283         {
5284           gimple stmt = gsi_stmt (gsi);
5285
5286           find_func_aliases (stmt);
5287         }
5288     }
5289
5290   if (dump_file)
5291     {
5292       fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
5293       dump_constraints (dump_file);
5294     }
5295
5296   if (dump_file)
5297     fprintf (dump_file,
5298              "\nCollapsing static cycles and doing variable "
5299              "substitution\n");
5300
5301   init_graph (VEC_length (varinfo_t, varmap) * 2);
5302   
5303   if (dump_file)
5304     fprintf (dump_file, "Building predecessor graph\n");
5305   build_pred_graph ();
5306   
5307   if (dump_file)
5308     fprintf (dump_file, "Detecting pointer and location "
5309              "equivalences\n");
5310   si = perform_var_substitution (graph);
5311   
5312   if (dump_file)
5313     fprintf (dump_file, "Rewriting constraints and unifying "
5314              "variables\n");
5315   rewrite_constraints (graph, si);
5316
5317   build_succ_graph ();
5318   free_var_substitution_info (si);
5319
5320   if (dump_file && (dump_flags & TDF_GRAPH))
5321     dump_constraint_graph (dump_file);
5322
5323   move_complex_constraints (graph);
5324
5325   if (dump_file)
5326     fprintf (dump_file, "Uniting pointer but not location equivalent "
5327              "variables\n");
5328   unite_pointer_equivalences (graph);
5329
5330   if (dump_file)
5331     fprintf (dump_file, "Finding indirect cycles\n");
5332   find_indirect_cycles (graph);
5333
5334   /* Implicit nodes and predecessors are no longer necessary at this
5335      point. */
5336   remove_preds_and_fake_succs (graph);
5337
5338   if (dump_file)
5339     fprintf (dump_file, "Solving graph\n");
5340
5341   solve_graph (graph);
5342
5343   if (dump_file)
5344     dump_sa_points_to_info (dump_file);
5345
5346   /* Compute the points-to sets for ESCAPED and CALLUSED used for
5347      call-clobber analysis.  */
5348   find_what_var_points_to (var_escaped, &cfun->gimple_df->escaped);
5349   find_what_var_points_to (var_callused, &cfun->gimple_df->callused);
5350
5351   /* Make sure the ESCAPED solution (which is used as placeholder in
5352      other solutions) does not reference itself.  This simplifies
5353      points-to solution queries.  */
5354   cfun->gimple_df->escaped.escaped = 0;
5355
5356   /* Compute the points-to sets for pointer SSA_NAMEs.  */
5357   for (i = 0; i < num_ssa_names; ++i)
5358     {
5359       tree ptr = ssa_name (i);
5360       if (ptr
5361           && POINTER_TYPE_P (TREE_TYPE (ptr)))
5362         find_what_p_points_to (ptr);
5363     }
5364
5365   timevar_pop (TV_TREE_PTA);
5366
5367   have_alias_info = true;
5368 }
5369
5370
5371 /* Delete created points-to sets.  */
5372
5373 static void
5374 delete_points_to_sets (void)
5375 {
5376   unsigned int i;
5377
5378   htab_delete (shared_bitmap_table);
5379   if (dump_file && (dump_flags & TDF_STATS))
5380     fprintf (dump_file, "Points to sets created:%d\n",
5381              stats.points_to_sets_created);
5382
5383   pointer_map_destroy (vi_for_tree);
5384   bitmap_obstack_release (&pta_obstack);
5385   VEC_free (constraint_t, heap, constraints);
5386
5387   for (i = 0; i < graph->size; i++)
5388     VEC_free (constraint_t, heap, graph->complex[i]);
5389   free (graph->complex);
5390
5391   free (graph->rep);
5392   free (graph->succs);
5393   free (graph->pe);
5394   free (graph->pe_rep);
5395   free (graph->indirect_cycles);
5396   free (graph);
5397
5398   VEC_free (varinfo_t, heap, varmap);
5399   free_alloc_pool (variable_info_pool);
5400   free_alloc_pool (constraint_pool);
5401   have_alias_info = false;
5402 }
5403
5404
5405 /* Compute points-to information for every SSA_NAME pointer in the
5406    current function and compute the transitive closure of escaped
5407    variables to re-initialize the call-clobber states of local variables.  */
5408
5409 unsigned int
5410 compute_may_aliases (void)
5411 {
5412   /* For each pointer P_i, determine the sets of variables that P_i may
5413      point-to.  Compute the reachability set of escaped and call-used
5414      variables.  */
5415   compute_points_to_sets ();
5416
5417   /* Debugging dumps.  */
5418   if (dump_file)
5419     {
5420       dump_alias_info (dump_file);
5421
5422       if (dump_flags & TDF_DETAILS)
5423         dump_referenced_vars (dump_file);
5424     }
5425
5426   /* Deallocate memory used by aliasing data structures and the internal
5427      points-to solution.  */
5428   delete_points_to_sets ();
5429
5430   gcc_assert (!need_ssa_update_p (cfun));
5431
5432   return 0;
5433 }
5434
5435 static bool
5436 gate_tree_pta (void)
5437 {
5438   return flag_tree_pta;
5439 }
5440
5441 /* A dummy pass to cause points-to information to be computed via
5442    TODO_rebuild_alias.  */
5443
5444 struct gimple_opt_pass pass_build_alias =
5445 {
5446  {
5447   GIMPLE_PASS,
5448   "alias",                  /* name */
5449   gate_tree_pta,            /* gate */
5450   NULL,                     /* execute */
5451   NULL,                     /* sub */
5452   NULL,                     /* next */
5453   0,                        /* static_pass_number */
5454   TV_NONE,                  /* tv_id */
5455   PROP_cfg | PROP_ssa,      /* properties_required */
5456   0,                        /* properties_provided */
5457   0,                        /* properties_destroyed */
5458   0,                        /* todo_flags_start */
5459   TODO_rebuild_alias | TODO_dump_func  /* todo_flags_finish */
5460  }
5461 };
5462
5463 /* A dummy pass to cause points-to information to be computed via
5464    TODO_rebuild_alias.  */
5465
5466 struct gimple_opt_pass pass_build_ealias =
5467 {
5468  {
5469   GIMPLE_PASS,
5470   "ealias",                 /* name */
5471   gate_tree_pta,            /* gate */
5472   NULL,                     /* execute */
5473   NULL,                     /* sub */
5474   NULL,                     /* next */
5475   0,                        /* static_pass_number */
5476   TV_NONE,                  /* tv_id */
5477   PROP_cfg | PROP_ssa,      /* properties_required */
5478   0,                        /* properties_provided */
5479   0,                        /* properties_destroyed */
5480   0,                        /* todo_flags_start */
5481   TODO_rebuild_alias | TODO_dump_func  /* todo_flags_finish */
5482  }
5483 };
5484
5485
5486 /* Return true if we should execute IPA PTA.  */
5487 static bool
5488 gate_ipa_pta (void)
5489 {
5490   return (flag_ipa_pta
5491           /* Don't bother doing anything if the program has errors.  */
5492           && !(errorcount || sorrycount));
5493 }
5494
5495 /* Execute the driver for IPA PTA.  */
5496 static unsigned int
5497 ipa_pta_execute (void)
5498 {
5499   struct cgraph_node *node;
5500   struct scc_info *si;
5501
5502   in_ipa_mode = 1;
5503   init_alias_heapvars ();
5504   init_alias_vars ();
5505
5506   for (node = cgraph_nodes; node; node = node->next)
5507     {
5508       unsigned int varid;
5509
5510       varid = create_function_info_for (node->decl,
5511                                         cgraph_node_name (node));
5512       if (node->local.externally_visible)
5513         {
5514           varinfo_t fi = get_varinfo (varid);
5515           for (; fi; fi = fi->next)
5516             make_constraint_from (fi, anything_id);
5517         }
5518     }
5519   for (node = cgraph_nodes; node; node = node->next)
5520     {
5521       if (node->analyzed)
5522         {
5523           struct function *func = DECL_STRUCT_FUNCTION (node->decl);
5524           basic_block bb;
5525           tree old_func_decl = current_function_decl;
5526           if (dump_file)
5527             fprintf (dump_file,
5528                      "Generating constraints for %s\n",
5529                      cgraph_node_name (node));
5530           push_cfun (func);
5531           current_function_decl = node->decl;
5532
5533           FOR_EACH_BB_FN (bb, func)
5534             {
5535               gimple_stmt_iterator gsi;
5536
5537               for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
5538                    gsi_next (&gsi))
5539                 {
5540                   gimple phi = gsi_stmt (gsi);
5541
5542                   if (is_gimple_reg (gimple_phi_result (phi)))
5543                     find_func_aliases (phi);
5544                 }
5545
5546               for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5547                 find_func_aliases (gsi_stmt (gsi));
5548             }
5549           current_function_decl = old_func_decl;
5550           pop_cfun ();
5551         }
5552       else
5553         {
5554           /* Make point to anything.  */
5555         }
5556     }
5557
5558   if (dump_file)
5559     {
5560       fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
5561       dump_constraints (dump_file);
5562     }
5563
5564   if (dump_file)
5565     fprintf (dump_file,
5566              "\nCollapsing static cycles and doing variable "
5567              "substitution:\n");
5568
5569   init_graph (VEC_length (varinfo_t, varmap) * 2);
5570   build_pred_graph ();
5571   si = perform_var_substitution (graph);
5572   rewrite_constraints (graph, si);
5573
5574   build_succ_graph ();
5575   free_var_substitution_info (si);
5576   move_complex_constraints (graph);
5577   unite_pointer_equivalences (graph);
5578   find_indirect_cycles (graph);
5579
5580   /* Implicit nodes and predecessors are no longer necessary at this
5581      point. */
5582   remove_preds_and_fake_succs (graph);
5583
5584   if (dump_file)
5585     fprintf (dump_file, "\nSolving graph\n");
5586
5587   solve_graph (graph);
5588
5589   if (dump_file)
5590     dump_sa_points_to_info (dump_file);
5591
5592   in_ipa_mode = 0;
5593   delete_alias_heapvars ();
5594   delete_points_to_sets ();
5595   return 0;
5596 }
5597
5598 struct simple_ipa_opt_pass pass_ipa_pta =
5599 {
5600  {
5601   SIMPLE_IPA_PASS,
5602   "pta",                                /* name */
5603   gate_ipa_pta,                 /* gate */
5604   ipa_pta_execute,                      /* execute */
5605   NULL,                                 /* sub */
5606   NULL,                                 /* next */
5607   0,                                    /* static_pass_number */
5608   TV_IPA_PTA,                   /* tv_id */
5609   0,                                    /* properties_required */
5610   0,                                    /* properties_provided */
5611   0,                                    /* properties_destroyed */
5612   0,                                    /* todo_flags_start */
5613   TODO_update_ssa                       /* todo_flags_finish */
5614  }
5615 };
5616
5617
5618 #include "gt-tree-ssa-structalias.h"