OSDN Git Service

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