OSDN Git Service

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