OSDN Git Service

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