OSDN Git Service

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