OSDN Git Service

2005-06-08 Daniel Berlin <dberlin@dberlin.org>
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-structalias.c
1 /* Tree based points-to analysis
2    Copyright (C) 2005 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 2 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; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20 */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "ggc.h"
27 #include "obstack.h"
28 #include "bitmap.h"
29 #include "tree-ssa-structalias.h"
30 #include "flags.h"
31 #include "rtl.h"
32 #include "tm_p.h"
33 #include "hard-reg-set.h"
34 #include "basic-block.h"
35 #include "output.h"
36 #include "errors.h"
37 #include "expr.h"
38 #include "diagnostic.h"
39 #include "tree.h"
40 #include "c-common.h"
41 #include "tree-flow.h"
42 #include "tree-inline.h"
43 #include "varray.h"
44 #include "c-tree.h"
45 #include "tree-gimple.h"
46 #include "hashtab.h"
47 #include "function.h"
48 #include "cgraph.h"
49 #include "tree-pass.h"
50 #include "timevar.h"
51 #include "alloc-pool.h"
52 #include "splay-tree.h"
53
54 /* The idea behind this analyzer is to generate set constraints from the
55    program, then solve the resulting constraints in order to generate the
56    points-to sets. 
57
58    Set constraints are a way of modeling program analysis problems that
59    involve sets.  They consist of an inclusion constraint language,
60    describing the variables (each variable is a set) and operations that
61    are involved on the variables, and a set of rules that derive facts
62    from these operations.  To solve a system of set constraints, you derive
63    all possible facts under the rules, which gives you the correct sets
64    as a consequence.
65
66    See  "Efficient Field-sensitive pointer analysis for C" by "David
67    J. Pearce and Paul H. J. Kelly and Chris Hankin, at
68    http://citeseer.ist.psu.edu/pearce04efficient.html
69
70    Also see "Ultra-fast Aliasing Analysis using CLA: A Million Lines
71    of C Code in a Second" by ""Nevin Heintze and Olivier Tardieu" at
72    http://citeseer.ist.psu.edu/heintze01ultrafast.html 
73
74    There are three types of constraint expressions, DEREF, ADDRESSOF, and
75    SCALAR.  Each constraint expression consists of a constraint type,
76    a variable, and an offset.  
77    
78    SCALAR is a constraint expression type used to represent x, whether
79    it appears on the LHS or the RHS of a statement.
80    DEREF is a constraint expression type used to represent *x, whether
81    it appears on the LHS or the RHS of a statement. 
82    ADDRESSOF is a constraint expression used to represent &x, whether
83    it apepars on the LHS or the RHS of a statement.
84    
85    Each pointer variable in the program is assigned an integer id, and
86    each field of a structure variable is assigned an integer id as well.
87    
88    Structure variables are linked to their list of fields through a "next
89    field" in each variable that points to the next field in offset
90    order.  
91    Each variable for a structure field has 
92
93    1. "size", that tells the size in bits of that field.
94    2. "fullsize, that tells the size in bits of the entire structure.
95    3. "offset", that tells the offset in bits from the beginning of the
96    structure to this field.
97
98    Thus, 
99    struct f
100    {
101      int a;
102      int b;
103    } foo;
104    int *bar;
105
106    looks like
107
108    foo.a -> id 1, size 32, offset 0, fullsize 64, next foo.b
109    foo.b -> id 2, size 32, offset 32, fullsize 64, next NULL
110    bar -> id 3, size 32, offset 0, fullsize 32, next NULL
111
112    
113   In order to solve the system of set constraints, the following is
114   done:
115
116   1. Each constraint variable x has a solution set associated with it,
117   Sol(x).
118   
119   2. Constraints are separated into direct, copy, and complex.
120   Direct constraints are ADDRESSOF constraints that require no extra
121   processing, such as P = &Q
122   Copy constraints are those of the form P = Q.
123   Complex constraints are all the constraints involving dereferences.
124   
125   3. All direct constraints of the form P = &Q are processed, such
126   that Q is added to Sol(P) 
127
128   4. All complex constraints for a given constraint variable are stored in a
129   linked list attached to that variable's node.  
130
131   5. A directed graph is built out of the copy constraints. Each
132   constraint variable is a node in the graph, and an edge from 
133   Q to P is added for each copy constraint of the form P = Q
134   
135   6. The graph is then walked, and solution sets are
136   propagated along the copy edges, such that an edge from Q to P
137   causes Sol(P) <- Sol(P) union Sol(Q).
138   
139   7.  As we visit each node, all complex constraints associated with
140   that node are processed by adding approriate copy edges to the graph, or the
141   approriate variables to the solution set.  
142
143   8. The process of walking the graph is iterated until no solution
144   sets change.
145
146   Prior to walking the graph in steps 6 and 7, We perform static
147   cycle elimination on the constraint graph, as well 
148   as off-line variable substitution.
149   
150   TODO: Adding offsets to pointer-to-structures can be handled (IE not punted
151   on and turned into anything), but isn't.  You can just see what offset
152   inside the pointed-to struct it's going to access.
153   
154   TODO: Constant bounded arrays can be handled as if they were structs of the
155   same number of elements. 
156
157   TODO: Modeling heap and incoming pointers becomes much better if we
158   add fields to them as we discover them, which we could do.
159
160   TODO: We could handle unions, but to be honest, it's probably not
161   worth the pain or slowdown.  */
162
163 static bool use_field_sensitive = true;
164 static unsigned int create_variable_info_for (tree, const char *);
165 static struct constraint_expr get_constraint_for (tree);
166 static void build_constraint_graph (void);
167
168 static bitmap_obstack ptabitmap_obstack;
169 static bitmap_obstack iteration_obstack;
170 DEF_VEC_P(constraint_t);
171 DEF_VEC_ALLOC_P(constraint_t,gc);
172
173 static struct constraint_stats
174 {
175   unsigned int total_vars;
176   unsigned int collapsed_vars;
177   unsigned int unified_vars_static;
178   unsigned int unified_vars_dynamic;
179   unsigned int iterations;
180 } stats;
181
182 struct variable_info
183 {
184   /* ID of this variable  */
185   unsigned int id;
186
187   /* Name of this variable */
188   const char *name;
189
190   /* Tree that this variable is associated with.  */
191   tree decl;
192
193   /* Offset of this variable, in bits, from the base variable  */
194   unsigned HOST_WIDE_INT offset;  
195
196   /* Size of the variable, in bits.  */
197   unsigned HOST_WIDE_INT size;
198
199   /* Full size of the base variable, in bits.  */
200   unsigned HOST_WIDE_INT fullsize;
201
202   /* A link to the variable for the next field in this structure.  */
203   struct variable_info *next;
204
205   /* Node in the graph that represents the constraints and points-to
206      solution for the variable.  */
207   unsigned int node;
208
209   /* True if the address of this variable is taken.  Needed for
210      variable substitution.  */
211   unsigned int address_taken:1;
212
213   /* True if this variable is the target of a dereference.  Needed for
214      variable substitution.  */
215   unsigned int indirect_target:1;
216
217   /* True if this is a variable created by the constraint analysis, such as
218      heap variables and constraints we had to break up.  */
219   unsigned int is_artificial_var:1;
220
221   /* True for variables whose size is not known or variable.  */
222   unsigned int is_unknown_size_var:1;  
223
224   /* Points-to set for this variable.  */
225   bitmap solution;
226
227   /* Variable ids represented by this node.  */
228   bitmap variables;
229
230   /* Vector of complex constraints for this node.  Complex
231      constraints are those involving dereferences.  */
232   VEC(constraint_t,gc) *complex;
233 };
234 typedef struct variable_info *varinfo_t;
235
236 static varinfo_t first_vi_for_offset (varinfo_t, unsigned HOST_WIDE_INT);
237
238 /* Pool of variable info structures.  */
239 static alloc_pool variable_info_pool;
240
241 DEF_VEC_P(varinfo_t);
242
243 DEF_VEC_ALLOC_P(varinfo_t, gc);
244
245 /* Table of variable info structures for constraint variables.  Indexed direcly
246    by variable info id.  */
247 static VEC(varinfo_t,gc) *varmap;
248 #define get_varinfo(n) VEC_index(varinfo_t, varmap, n)
249
250 /* Variable that represents the unknown pointer.  */
251 static varinfo_t var_anything;
252 static tree anything_tree;
253 static unsigned int anything_id;
254
255 /* Variable that represents the NULL pointer.  */
256 static varinfo_t var_nothing;
257 static tree nothing_tree;
258 static unsigned int nothing_id;
259
260 /* Variable that represents read only memory.  */
261 static varinfo_t var_readonly;
262 static tree readonly_tree;
263 static unsigned int readonly_id;
264
265 /* Variable that represents integers.  This is used for when people do things
266    like &0->a.b.  */
267 static varinfo_t var_integer;
268 static tree integer_tree;
269 static unsigned int integer_id;
270
271
272 /* Return a new variable info structure consisting for a variable
273    named NAME, and using constraint graph node NODE.  */
274
275 static varinfo_t
276 new_var_info (tree t, unsigned int id, const char *name, unsigned int node)
277 {
278   varinfo_t ret = pool_alloc (variable_info_pool);
279
280   ret->id = id;
281   ret->name = name;
282   ret->decl = t;
283   ret->node = node;
284   ret->address_taken = false;
285   ret->indirect_target = false;
286   ret->is_artificial_var = false;
287   ret->is_unknown_size_var = false;
288   ret->solution = BITMAP_ALLOC (&ptabitmap_obstack);
289   bitmap_clear (ret->solution);
290   ret->variables = BITMAP_ALLOC (&ptabitmap_obstack);
291   bitmap_clear (ret->variables);
292   ret->complex = NULL;
293   ret->next = NULL;
294   return ret;
295 }
296
297 typedef enum {SCALAR, DEREF, ADDRESSOF} constraint_expr_type;
298
299 /* An expression that appears in a constraint.  */
300
301 struct constraint_expr 
302 {
303   /* Constraint type.  */
304   constraint_expr_type type;
305
306   /* Variable we are referring to in the constraint.  */
307   unsigned int var;
308
309   /* Offset, in bits, of this constraint from the beginning of
310      variables it ends up referring to.
311
312      IOW, in a deref constraint, we would deref, get the result set,
313      then add OFFSET to each member.   */
314   unsigned HOST_WIDE_INT offset;
315 };
316
317 static struct constraint_expr do_deref (struct constraint_expr);
318
319 /* Our set constraints are made up of two constraint expressions, one
320    LHS, and one RHS.  
321
322    As described in the introduction, our set constraints each represent an
323    operation between set valued variables.
324 */
325 struct constraint
326 {
327   struct constraint_expr lhs;
328   struct constraint_expr rhs;
329 };
330
331 /* List of constraints that we use to build the constraint graph from.  */
332
333 static VEC(constraint_t,gc) *constraints;
334 static alloc_pool constraint_pool;
335
336 /* An edge in the constraint graph.  We technically have no use for
337    the src, since it will always be the same node that we are indexing
338    into the pred/succ arrays with, but it's nice for checking
339    purposes.  The edges are weighted, with a bit set in weights for
340    each edge from src to dest with that weight.  */
341
342 struct constraint_edge
343 {
344   unsigned int src;
345   unsigned int dest;
346   bitmap weights;
347 };
348
349 typedef struct constraint_edge *constraint_edge_t;
350 static alloc_pool constraint_edge_pool;
351
352 /* Return a new constraint edge from SRC to DEST.  */
353
354 static constraint_edge_t
355 new_constraint_edge (unsigned int src, unsigned int dest)
356 {
357   constraint_edge_t ret = pool_alloc (constraint_edge_pool);
358   ret->src = src;
359   ret->dest = dest;
360   ret->weights = NULL;
361   return ret;
362 }
363
364 DEF_VEC_P(constraint_edge_t);
365 DEF_VEC_ALLOC_P(constraint_edge_t,gc);
366
367
368 /* The constraint graph is simply a set of adjacency vectors, one per
369    variable. succs[x] is the vector of successors for variable x, and preds[x]
370    is the vector of predecessors for variable x. 
371    IOW, all edges are "forward" edges, which is not like our CFG.  
372    So remember that
373    preds[x]->src == x, and
374    succs[x]->src == x*/
375
376 struct constraint_graph
377 {
378   VEC(constraint_edge_t,gc) **succs;
379   VEC(constraint_edge_t,gc) **preds;
380 };
381
382 typedef struct constraint_graph *constraint_graph_t;
383
384 static constraint_graph_t graph;
385
386 /* Create a new constraint consisting of LHS and RHS expressions.  */
387
388 static constraint_t 
389 new_constraint (const struct constraint_expr lhs,
390                 const struct constraint_expr rhs)
391 {
392   constraint_t ret = pool_alloc (constraint_pool);
393   ret->lhs = lhs;
394   ret->rhs = rhs;
395   return ret;
396 }
397
398 /* Print out constraint C to FILE.  */
399
400 void
401 dump_constraint (FILE *file, constraint_t c)
402 {
403   if (c->lhs.type == ADDRESSOF)
404     fprintf (file, "&");
405   else if (c->lhs.type == DEREF)
406     fprintf (file, "*");  
407   fprintf (file, "%s", get_varinfo (c->lhs.var)->name);
408   if (c->lhs.offset != 0)
409     fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->lhs.offset);
410   fprintf (file, " = ");
411   if (c->rhs.type == ADDRESSOF)
412     fprintf (file, "&");
413   else if (c->rhs.type == DEREF)
414     fprintf (file, "*");
415   fprintf (file, "%s", get_varinfo (c->rhs.var)->name);
416   if (c->rhs.offset != 0)
417     fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->rhs.offset);
418   fprintf (file, "\n");
419 }
420
421 /* Print out constraint C to stderr.  */
422
423 void
424 debug_constraint (constraint_t c)
425 {
426   dump_constraint (stderr, c);
427 }
428
429 /* Print out all constraints to FILE */
430
431 void
432 dump_constraints (FILE *file)
433 {
434   int i;
435   constraint_t c;
436   for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
437     dump_constraint (file, c);
438 }
439
440 /* Print out all constraints to stderr.  */
441
442 void
443 debug_constraints (void)
444 {
445   dump_constraints (stderr);
446 }
447
448 /* SOLVER FUNCTIONS 
449
450    The solver is a simple worklist solver, that works on the following
451    algorithm:
452    
453    sbitmap changed_nodes = all ones;
454    changed_count = number of nodes;
455    For each node that was already collapsed:
456        changed_count--;
457
458
459    while (changed_count > 0)
460    {
461      compute topological ordering for constraint graph
462   
463      find and collapse cycles in the constraint graph (updating
464      changed if necessary)
465      
466      for each node (n) in the graph in topological order:
467        changed_count--;
468
469        Process each complex constraint associated with the node,
470        updating changed if necessary.
471
472        For each outgoing edge from n, propagate the solution from n to
473        the destination of the edge, updating changed as necessary.
474
475    }  */
476
477 /* Return true if two constraint expressions A and B are equal.  */
478
479 static bool
480 constraint_expr_equal (struct constraint_expr a, struct constraint_expr b)
481 {
482   return a.type == b.type
483     && a.var == b.var
484     && a.offset == b.offset;
485 }
486
487 /* Return true if constraint expression A is less than constraint expression
488    B.  This is just arbitrary, but consistent, in order to give them an
489    ordering.  */
490
491 static bool
492 constraint_expr_less (struct constraint_expr a, struct constraint_expr b)
493 {
494   if (a.type == b.type)
495     {
496       if (a.var == b.var)
497         return a.offset < b.offset;
498       else
499         return a.var < b.var;
500     }
501   else
502     return a.type < b.type;
503 }
504
505 /* Return true if constraint A is less than constraint B.  This is just
506    arbitrary, but consistent, in order to give them an ordering.  */
507
508 static bool
509 constraint_less (const constraint_t a, const constraint_t b)
510 {
511   if (constraint_expr_less (a->lhs, b->lhs))
512     return true;
513   else if (constraint_expr_less (b->lhs, a->lhs))
514     return false;
515   else
516     return constraint_expr_less (a->rhs, b->rhs);
517 }
518
519 /* Return true if two constraints A and B are equal.  */
520   
521 static bool
522 constraint_equal (struct constraint a, struct constraint b)
523 {
524   return constraint_expr_equal (a.lhs, b.lhs) 
525     && constraint_expr_equal (a.rhs, b.rhs);
526 }
527
528
529 /* Find a constraint LOOKFOR in the sorted constraint vector VEC */
530
531 static constraint_t
532 constraint_vec_find (VEC(constraint_t,gc) *vec,
533                      struct constraint lookfor)
534 {
535   unsigned int place;  
536   constraint_t found;
537
538   if (vec == NULL)
539     return NULL;
540
541   place = VEC_lower_bound (constraint_t, vec, &lookfor, constraint_less);
542   if (place >= VEC_length (constraint_t, vec))
543     return NULL;
544   found = VEC_index (constraint_t, vec, place);
545   if (!constraint_equal (*found, lookfor))
546     return NULL;
547   return found;
548 }
549
550 /* Union two constraint vectors, TO and FROM.  Put the result in TO.  */
551
552 static void
553 constraint_set_union (VEC(constraint_t,gc) **to,
554                       VEC(constraint_t,gc) **from)
555 {
556   int i;
557   constraint_t c;
558
559   for (i = 0; VEC_iterate (constraint_t, *from, i, c); i++)
560     {
561       if (constraint_vec_find (*to, *c) == NULL)
562         {
563           unsigned int place = VEC_lower_bound (constraint_t, *to, c,
564                                                 constraint_less);
565           VEC_safe_insert (constraint_t, gc, *to, place, c);
566         }
567     }
568 }
569
570 /* Take a solution set SET, add OFFSET to each member of the set, and
571    overwrite SET with the result when done.  */
572
573 static void
574 solution_set_add (bitmap set, unsigned HOST_WIDE_INT offset)
575 {
576   bitmap result = BITMAP_ALLOC (&iteration_obstack);
577   unsigned int i;
578   bitmap_iterator bi;
579
580   EXECUTE_IF_SET_IN_BITMAP (set, 0, i, bi)
581     {
582       /* If this is a properly sized variable, only add offset if it's
583          less than end.  Otherwise, it is globbed to a single
584          variable.  */
585       
586       if ((get_varinfo (i)->offset + offset) < get_varinfo (i)->fullsize)
587         {
588           unsigned HOST_WIDE_INT fieldoffset = get_varinfo (i)->offset + offset;
589           varinfo_t v = first_vi_for_offset (get_varinfo (i), fieldoffset);
590           bitmap_set_bit (result, v->id);
591         }
592       else if (get_varinfo (i)->is_artificial_var 
593                || get_varinfo (i)->is_unknown_size_var)
594         {
595           bitmap_set_bit (result, i);
596         }
597     }
598   
599   bitmap_copy (set, result);  
600   BITMAP_FREE (result);
601 }
602
603 /* Union solution sets TO and FROM, and add INC to each member of FROM in the
604    process.  */
605
606 static bool
607 set_union_with_increment  (bitmap to, bitmap from, unsigned HOST_WIDE_INT inc)
608 {
609   if (inc == 0)
610     return bitmap_ior_into (to, from);
611   else
612     {
613       bitmap tmp;
614       bool res;
615
616       tmp = BITMAP_ALLOC (&iteration_obstack);
617       bitmap_copy (tmp, from);
618       solution_set_add (tmp, inc);
619       res = bitmap_ior_into (to, tmp);
620       BITMAP_FREE (tmp);
621       return res;
622     }
623 }
624
625 /* Insert constraint C into the list of complex constraints for VAR.  */
626
627 static void
628 insert_into_complex (unsigned int var, constraint_t c)
629 {
630   varinfo_t vi = get_varinfo (var);
631   unsigned int place = VEC_lower_bound (constraint_t, vi->complex, c,
632                                         constraint_less);
633   VEC_safe_insert (constraint_t, gc, vi->complex, place, c);
634 }
635
636
637 /* Compare two constraint edges A and B, return true if they are equal.  */
638
639 static bool
640 constraint_edge_equal (struct constraint_edge a, struct constraint_edge b)
641 {
642   return a.src == b.src && a.dest == b.dest;
643 }
644
645 /* Compare two constraint edges, return true if A is less than B */
646
647 static bool
648 constraint_edge_less (const constraint_edge_t a, const constraint_edge_t b)
649 {
650   if (a->dest < b->dest)
651     return true;
652   else if (a->dest == b->dest)
653     return a->src < b->src;
654   else
655     return false;
656 }
657
658 /* Find the constraint edge that matches LOOKFOR, in VEC.
659    Return the edge, if found, NULL otherwise.  */
660
661 static constraint_edge_t 
662 constraint_edge_vec_find (VEC(constraint_edge_t,gc) *vec, 
663                           struct constraint_edge lookfor)
664 {
665   unsigned int place;  
666   constraint_edge_t edge;
667
668   place = VEC_lower_bound (constraint_edge_t, vec, &lookfor, 
669                            constraint_edge_less);
670   edge = VEC_index (constraint_edge_t, vec, place);
671   if (!constraint_edge_equal (*edge, lookfor))
672     return NULL;
673   return edge;
674 }
675
676 /* Condense two variable nodes into a single variable node, by moving
677    all associated info from SRC to TO.  */
678
679 static void 
680 condense_varmap_nodes (unsigned int to, unsigned int src)
681 {
682   varinfo_t tovi = get_varinfo (to);
683   varinfo_t srcvi = get_varinfo (src);
684   unsigned int i;
685   constraint_t c;
686   bitmap_iterator bi;
687   
688   /* the src node, and all its variables, are now the to node.  */
689   srcvi->node = to;
690   EXECUTE_IF_SET_IN_BITMAP (srcvi->variables, 0, i, bi)
691     get_varinfo (i)->node = to;
692   
693   /* Merge the src node variables and the to node variables.  */
694   bitmap_set_bit (tovi->variables, src);
695   bitmap_ior_into (tovi->variables, srcvi->variables);
696   bitmap_clear (srcvi->variables);
697   
698   /* Move all complex constraints from src node into to node  */
699   for (i = 0; VEC_iterate (constraint_t, srcvi->complex, i, c); i++)
700     {
701       /* In complex constraints for node src, we may have either
702          a = *src, and *src = a.  */
703       
704       if (c->rhs.type == DEREF)
705         c->rhs.var = to;
706       else
707         c->lhs.var = to;
708     }
709   constraint_set_union (&tovi->complex, &srcvi->complex);
710   srcvi->complex = NULL;
711 }
712
713 /* Erase EDGE from GRAPH.  This routine only handles self-edges
714    (e.g. an edge from a to a).  */
715
716 static void
717 erase_graph_self_edge (constraint_graph_t graph, struct constraint_edge edge)
718 {
719   VEC(constraint_edge_t,gc) *predvec = graph->preds[edge.src];
720   VEC(constraint_edge_t,gc) *succvec = graph->succs[edge.dest];
721   unsigned int place;
722   gcc_assert (edge.src == edge.dest);
723
724   /* Remove from the successors.  */
725   place = VEC_lower_bound (constraint_edge_t, succvec, &edge, 
726                            constraint_edge_less);
727   
728   /* Make sure we found the edge.  */
729 #ifdef ENABLE_CHECKING
730   {
731     constraint_edge_t tmp = VEC_index (constraint_edge_t, succvec, place);
732     gcc_assert (constraint_edge_equal (*tmp, edge));
733   }
734 #endif
735   VEC_ordered_remove (constraint_edge_t, succvec, place);
736
737   /* Remove from the predecessors.  */
738   place = VEC_lower_bound (constraint_edge_t, predvec, &edge,
739                            constraint_edge_less);
740
741   /* Make sure we found the edge.  */
742 #ifdef ENABLE_CHECKING
743   {
744     constraint_edge_t tmp = VEC_index (constraint_edge_t, predvec, place);
745     gcc_assert (constraint_edge_equal (*tmp, edge));
746   }
747 #endif
748   VEC_ordered_remove (constraint_edge_t, predvec, place);
749 }
750
751 /* Remove edges involving NODE from GRAPH.  */
752
753 static void
754 clear_edges_for_node (constraint_graph_t graph, unsigned int node)
755 {
756   VEC(constraint_edge_t,gc) *succvec = graph->succs[node];
757   VEC(constraint_edge_t,gc) *predvec = graph->preds[node];
758   constraint_edge_t c;
759   int i;
760   
761   /* Walk the successors, erase the associated preds.  */
762   for (i = 0; VEC_iterate (constraint_edge_t, succvec, i, c); i++)
763     if (c->dest != node)
764       {
765         unsigned int place;
766         struct constraint_edge lookfor;
767         lookfor.src = c->dest;
768         lookfor.dest = node;
769         place = VEC_lower_bound (constraint_edge_t, graph->preds[c->dest], 
770                                  &lookfor, constraint_edge_less);
771         VEC_ordered_remove (constraint_edge_t, graph->preds[c->dest], place);
772       }
773   /* Walk the preds, erase the associated succs.  */
774   for (i =0; VEC_iterate (constraint_edge_t, predvec, i, c); i++)
775     if (c->dest != node)
776       {
777         unsigned int place;
778         struct constraint_edge lookfor;
779         lookfor.src = c->dest;
780         lookfor.dest = node;
781         place = VEC_lower_bound (constraint_edge_t, graph->succs[c->dest],
782                                  &lookfor, constraint_edge_less);
783         VEC_ordered_remove (constraint_edge_t, graph->succs[c->dest], place);
784       }    
785   
786   graph->preds[node] = NULL;
787   graph->succs[node] = NULL;
788 }
789
790 static bool edge_added = false;
791   
792 /* Add edge NEWE to the graph.  */
793
794 static bool
795 add_graph_edge (constraint_graph_t graph, struct constraint_edge newe)
796 {
797   unsigned int place;
798   unsigned int src = newe.src;
799   unsigned int dest = newe.dest;
800   VEC(constraint_edge_t,gc) *vec;
801
802   vec = graph->preds[src];
803   place = VEC_lower_bound (constraint_edge_t, vec, &newe, 
804                            constraint_edge_less);
805   if (place == VEC_length (constraint_edge_t, vec)
806       || VEC_index (constraint_edge_t, vec, place)->dest != dest)
807     {
808       constraint_edge_t edge = new_constraint_edge (src, dest);
809       bitmap weightbitmap;
810
811       weightbitmap = BITMAP_ALLOC (&ptabitmap_obstack);
812       edge->weights = weightbitmap;
813       VEC_safe_insert (constraint_edge_t, gc, graph->preds[edge->src], 
814                        place, edge);
815       edge = new_constraint_edge (dest, src);
816       edge->weights = weightbitmap;
817       place = VEC_lower_bound (constraint_edge_t, graph->succs[edge->src],
818                                edge, constraint_edge_less);
819       VEC_safe_insert (constraint_edge_t, gc, graph->succs[edge->src], 
820                        place, edge);
821       edge_added = true;
822       return true;
823     }
824   else
825     return false;
826 }
827
828
829 /* Return the bitmap representing the weights of edge LOOKFOR */
830
831 static bitmap
832 get_graph_weights (constraint_graph_t graph, struct constraint_edge lookfor)
833 {
834   constraint_edge_t edge;
835   unsigned int src = lookfor.src;
836   VEC(constraint_edge_t,gc) *vec;
837   vec = graph->preds[src];
838   edge = constraint_edge_vec_find (vec, lookfor);
839   gcc_assert (edge != NULL);
840   return edge->weights;
841 }
842
843
844 /* Merge GRAPH nodes FROM and TO into node TO.  */
845
846 static void
847 merge_graph_nodes (constraint_graph_t graph, unsigned int to, 
848                    unsigned int from)
849 {
850   VEC(constraint_edge_t,gc) *succvec = graph->succs[from];
851   VEC(constraint_edge_t,gc) *predvec = graph->preds[from];
852   int i;
853   constraint_edge_t c;
854   
855   /* Merge all the predecessor edges.  */
856
857   for (i = 0; VEC_iterate (constraint_edge_t, predvec, i, c); i++)
858     {
859       unsigned int d = c->dest;
860       struct constraint_edge olde;
861       struct constraint_edge newe;
862       bitmap temp;
863       bitmap weights;
864       if (c->dest == from)
865         d = to;
866       newe.src = to;
867       newe.dest = d;
868       add_graph_edge (graph, newe);
869       olde.src = from;
870       olde.dest = c->dest;
871       temp = get_graph_weights (graph, olde);
872       weights = get_graph_weights (graph, newe);
873       bitmap_ior_into (weights, temp);
874     }
875   
876   /* Merge all the successor edges.  */
877   for (i = 0; VEC_iterate (constraint_edge_t, succvec, i, c); i++)
878     {
879       unsigned int d = c->dest;
880       struct constraint_edge olde;
881       struct constraint_edge newe;
882       bitmap temp;
883       bitmap weights;
884       if (c->dest == from)
885         d = to;
886       newe.src = d;
887       newe.dest = to;
888       add_graph_edge (graph, newe);
889       olde.src = c->dest;
890       olde.dest = from;
891       temp = get_graph_weights (graph, olde);
892       weights = get_graph_weights (graph, newe);
893       bitmap_ior_into (weights, temp);
894     }
895   clear_edges_for_node (graph, from);
896 }
897
898 /* Add a graph edge to GRAPH, going from TO to FROM, with WEIGHT, if
899    it doesn't exist in the graph already.
900    Return false if the edge already existed, true otherwise.  */
901
902 static bool
903 int_add_graph_edge (constraint_graph_t graph, unsigned int to, 
904                     unsigned int from, unsigned HOST_WIDE_INT weight)
905 {
906   if (to == from && weight == 0)
907     {
908       return false;
909     }
910   else
911     {
912       bool r;
913       struct constraint_edge edge;
914       edge.src = to;
915       edge.dest = from;
916       r = add_graph_edge (graph, edge);
917       r |= !bitmap_bit_p (get_graph_weights (graph, edge), weight);
918       bitmap_set_bit (get_graph_weights (graph, edge), weight);
919       return r;
920     }
921 }
922
923
924 /* Return true if LOOKFOR is an existing graph edge.  */
925
926 static bool
927 valid_graph_edge (constraint_graph_t graph, struct constraint_edge lookfor)
928 {
929   return constraint_edge_vec_find (graph->preds[lookfor.src], lookfor) != NULL;
930 }
931
932
933 /* Build the constraint graph.  */
934
935 static void
936 build_constraint_graph (void)
937 {
938   int i = 0;
939   constraint_t c;
940
941   graph = ggc_alloc (sizeof (struct constraint_graph));
942   graph->succs = ggc_alloc_cleared (VEC_length (varinfo_t, varmap) * sizeof (*graph->succs));
943   graph->preds = ggc_alloc_cleared (VEC_length (varinfo_t, varmap) * sizeof (*graph->preds));
944   for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
945     {
946       struct constraint_expr lhs = c->lhs;
947       struct constraint_expr rhs = c->rhs;
948       if (lhs.type == DEREF)
949         {
950           /* *x = y or *x = &y (complex) */
951           if (rhs.type == ADDRESSOF || rhs.var > anything_id)
952             insert_into_complex (lhs.var, c);
953         }
954       else if (rhs.type == DEREF)
955         {
956           /* !ANYTHING = *y */
957           if (lhs.var > anything_id) 
958             insert_into_complex (rhs.var, c);
959         }
960       else if (rhs.type == ADDRESSOF)
961         {
962           /* x = &y */
963           bitmap_set_bit (get_varinfo (lhs.var)->solution, rhs.var);
964         }
965       else if (rhs.var > anything_id && lhs.var > anything_id)
966         {
967           /* Ignore 0 weighted self edges, as they can't possibly contribute
968              anything */
969           if (lhs.var != rhs.var || rhs.offset != 0 || lhs.offset != 0)
970             {
971               
972               struct constraint_edge edge;
973               edge.src = lhs.var;
974               edge.dest = rhs.var;
975               /* x = y (simple) */
976               add_graph_edge (graph, edge);
977               bitmap_set_bit (get_graph_weights (graph, edge),
978                               rhs.offset);
979             }
980           
981         }
982     }
983 }
984 /* Changed variables on the last iteration.  */
985 static unsigned int changed_count;
986 static sbitmap changed;
987
988 DEF_VEC_I(uint);
989 DEF_VEC_ALLOC_I(uint,heap);
990
991
992 /* Strongly Connected Component visitation info.  */
993
994 struct scc_info
995 {
996   sbitmap visited;
997   sbitmap in_component;
998   int current_index;
999   unsigned int *visited_index;
1000   VEC(uint,heap) *scc_stack;
1001   VEC(uint,heap) *unification_queue;
1002 };
1003
1004
1005 /* Recursive routine to find strongly connected components in GRAPH.
1006    SI is the SCC info to store the information in, and N is the id of current
1007    graph node we are processing.
1008    
1009    This is Tarjan's strongly connected component finding algorithm, as
1010    modified by Nuutila to keep only non-root nodes on the stack.  
1011    The algorithm can be found in "On finding the strongly connected
1012    connected components in a directed graph" by Esko Nuutila and Eljas
1013    Soisalon-Soininen, in Information Processing Letters volume 49,
1014    number 1, pages 9-14.  */
1015
1016 static void
1017 scc_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1018 {
1019   constraint_edge_t c;
1020   int i;
1021
1022   gcc_assert (get_varinfo (n)->node == n);
1023   SET_BIT (si->visited, n);
1024   RESET_BIT (si->in_component, n);
1025   si->visited_index[n] = si->current_index ++;
1026   
1027   /* Visit all the successors.  */
1028   for (i = 0; VEC_iterate (constraint_edge_t, graph->succs[n], i, c); i++)
1029     {
1030       /* We only want to find and collapse the zero weight edges. */
1031       if (bitmap_bit_p (c->weights, 0))
1032         {
1033           unsigned int w = c->dest;
1034           if (!TEST_BIT (si->visited, w))
1035             scc_visit (graph, si, w);
1036           if (!TEST_BIT (si->in_component, w))
1037             {
1038               unsigned int t = get_varinfo (w)->node;
1039               unsigned int nnode = get_varinfo (n)->node;
1040               if (si->visited_index[t] < si->visited_index[nnode])
1041                 get_varinfo (n)->node = t;
1042             }
1043         }
1044     }
1045   
1046   /* See if any components have been identified.  */
1047   if (get_varinfo (n)->node == n)
1048     {
1049       unsigned int t = si->visited_index[n];
1050       SET_BIT (si->in_component, n);
1051       while (VEC_length (uint, si->scc_stack) != 0 
1052              && t < si->visited_index[VEC_last (uint, si->scc_stack)])
1053         {
1054           unsigned int w = VEC_pop (uint, si->scc_stack);
1055           get_varinfo (w)->node = n;
1056           SET_BIT (si->in_component, w);
1057           /* Mark this node for collapsing.  */
1058           VEC_safe_push (uint, heap, si->unification_queue, w);
1059         } 
1060     }
1061   else
1062     VEC_safe_push (uint, heap, si->scc_stack, n);
1063 }
1064
1065
1066 /* Collapse two variables into one variable.  */
1067
1068 static void
1069 collapse_nodes (constraint_graph_t graph, unsigned int to, unsigned int from)
1070 {
1071   bitmap tosol, fromsol;
1072   struct constraint_edge edge;
1073
1074
1075   condense_varmap_nodes (to, from);
1076   tosol = get_varinfo (to)->solution;
1077   fromsol = get_varinfo (from)->solution;
1078   bitmap_ior_into (tosol, fromsol);
1079   merge_graph_nodes (graph, to, from);
1080   edge.src = to;
1081   edge.dest = to;
1082   if (valid_graph_edge (graph, edge))
1083     {
1084       bitmap weights = get_graph_weights (graph, edge);
1085       bitmap_clear_bit (weights, 0);
1086       if (bitmap_empty_p (weights))
1087         erase_graph_self_edge (graph, edge);
1088     }
1089   bitmap_clear (fromsol);
1090   get_varinfo (to)->address_taken |= get_varinfo (from)->address_taken;
1091   get_varinfo (to)->indirect_target |= get_varinfo (from)->indirect_target;
1092 }
1093
1094
1095 /* Unify nodes in GRAPH that we have found to be part of a cycle.
1096    SI is the Strongly Connected Components information structure that tells us
1097    what components to unify.
1098    UPDATE_CHANGED should be set to true if the changed sbitmap and changed
1099    count should be updated to reflect the unification.  */
1100
1101 static void
1102 process_unification_queue (constraint_graph_t graph, struct scc_info *si,
1103                            bool update_changed)
1104 {
1105   size_t i = 0;
1106   bitmap tmp = BITMAP_ALLOC (update_changed ? &iteration_obstack : NULL);
1107   bitmap_clear (tmp);
1108
1109   /* We proceed as follows:
1110
1111      For each component in the queue (components are delineated by
1112      when current_queue_element->node != next_queue_element->node):
1113
1114         rep = representative node for component
1115
1116         For each node (tounify) to be unified in the component,
1117            merge the solution for tounify into tmp bitmap
1118
1119            clear solution for tounify
1120
1121            merge edges from tounify into rep
1122
1123            merge complex constraints from tounify into rep
1124
1125            update changed count to note that tounify will never change
1126            again
1127
1128         Merge tmp into solution for rep, marking rep changed if this
1129         changed rep's solution.
1130         
1131         Delete any 0 weighted self-edges we now have for rep.  */
1132   while (i != VEC_length (uint, si->unification_queue))
1133     {
1134       unsigned int tounify = VEC_index (uint, si->unification_queue, i);
1135       unsigned int n = get_varinfo (tounify)->node;
1136
1137       if (dump_file && (dump_flags & TDF_DETAILS))
1138         fprintf (dump_file, "Unifying %s to %s\n", 
1139                  get_varinfo (tounify)->name,
1140                  get_varinfo (n)->name);
1141       if (update_changed)
1142         stats.unified_vars_dynamic++;
1143       else
1144         stats.unified_vars_static++;
1145       bitmap_ior_into (tmp, get_varinfo (tounify)->solution);
1146       merge_graph_nodes (graph, n, tounify);
1147       condense_varmap_nodes (n, tounify);
1148       
1149       if (update_changed && TEST_BIT (changed, tounify))
1150         {
1151           RESET_BIT (changed, tounify);
1152           if (!TEST_BIT (changed, n))
1153             SET_BIT (changed, n);
1154           else
1155             {
1156               gcc_assert (changed_count > 0);
1157               changed_count--;
1158             }
1159         }
1160
1161       bitmap_clear (get_varinfo (tounify)->solution);
1162       ++i;
1163
1164       /* If we've either finished processing the entire queue, or
1165          finished processing all nodes for component n, update the solution for
1166          n.  */
1167       if (i == VEC_length (uint, si->unification_queue)
1168           || get_varinfo (VEC_index (uint, si->unification_queue, i))->node != n)
1169         {
1170           struct constraint_edge edge;
1171
1172           /* If the solution changes because of the merging, we need to mark
1173              the variable as changed.  */
1174           if (bitmap_ior_into (get_varinfo (n)->solution, tmp))
1175             {
1176               if (update_changed && !TEST_BIT (changed, n))
1177                 {
1178                   SET_BIT (changed, n);
1179                   changed_count++;
1180                 }
1181             }
1182           bitmap_clear (tmp);
1183           edge.src = n;
1184           edge.dest = n;
1185           if (valid_graph_edge (graph, edge))
1186             {
1187               bitmap weights = get_graph_weights (graph, edge);
1188               bitmap_clear_bit (weights, 0);
1189               if (bitmap_empty_p (weights))
1190                 erase_graph_self_edge (graph, edge);
1191             }
1192         }
1193     }
1194   BITMAP_FREE (tmp);
1195 }
1196
1197
1198 /* Information needed to compute the topological ordering of a graph.  */
1199
1200 struct topo_info
1201 {
1202   /* sbitmap of visited nodes.  */
1203   sbitmap visited;
1204   /* Array that stores the topological order of the graph, *in
1205      reverse*.  */
1206   VEC(uint,heap) *topo_order;
1207 };
1208
1209
1210 /* Initialize and return a topological info structure.  */
1211
1212 static struct topo_info *
1213 init_topo_info (void)
1214 {
1215   size_t size = VEC_length (varinfo_t, varmap);
1216   struct topo_info *ti = xmalloc (sizeof (struct topo_info));
1217   ti->visited = sbitmap_alloc (size);
1218   sbitmap_zero (ti->visited);
1219   ti->topo_order = VEC_alloc (uint, heap, 1);
1220   return ti;
1221 }
1222
1223
1224 /* Free the topological sort info pointed to by TI.  */
1225
1226 static void
1227 free_topo_info (struct topo_info *ti)
1228 {
1229   sbitmap_free (ti->visited);
1230   VEC_free (uint, heap, ti->topo_order);
1231   free (ti);
1232 }
1233
1234 /* Visit the graph in topological order, and store the order in the
1235    topo_info structure.  */
1236
1237 static void
1238 topo_visit (constraint_graph_t graph, struct topo_info *ti,
1239             unsigned int n)
1240 {
1241   VEC(constraint_edge_t,gc) *succs = graph->succs[n];
1242   constraint_edge_t c;
1243   int i;
1244   SET_BIT (ti->visited, n);
1245   for (i = 0; VEC_iterate (constraint_edge_t, succs, i, c); i++)
1246     {
1247       if (!TEST_BIT (ti->visited, c->dest))
1248         topo_visit (graph, ti, c->dest);
1249     }
1250   VEC_safe_push (uint, heap, ti->topo_order, n);
1251 }
1252
1253 /* Return true if variable N + OFFSET is a legal field of N.  */
1254
1255 static bool 
1256 type_safe (unsigned int n, unsigned HOST_WIDE_INT *offset)
1257 {
1258   varinfo_t ninfo = get_varinfo (n);
1259
1260   /* For things we've globbed to single variables, any offset into the
1261      variable acts like the entire variable, so that it becomes offset
1262      0.  */
1263   if (n == anything_id
1264       || ninfo->is_artificial_var
1265       || ninfo->is_unknown_size_var)
1266     {
1267       *offset = 0;
1268       return true;
1269     }
1270   return n > anything_id 
1271     && (get_varinfo (n)->offset + *offset) < get_varinfo (n)->fullsize;
1272 }
1273
1274 /* Process a constraint C that represents *x = &y.  */
1275
1276 static void
1277 do_da_constraint (constraint_graph_t graph ATTRIBUTE_UNUSED,
1278                   constraint_t c, bitmap delta)
1279 {
1280   unsigned int rhs = c->rhs.var;
1281   unsigned HOST_WIDE_INT offset = c->lhs.offset;
1282   unsigned int j;
1283   bitmap_iterator bi;
1284
1285   /* For each member j of Delta (Sol(x)), add x to Sol(j)  */
1286   EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1287     {
1288       if (type_safe (j, &offset))
1289         {
1290         /* *x != NULL && *x != ANYTHING*/
1291           varinfo_t v;
1292           unsigned int t;
1293           bitmap sol;
1294           unsigned HOST_WIDE_INT fieldoffset = get_varinfo (j)->offset + offset;
1295           v = first_vi_for_offset (get_varinfo (j), fieldoffset);
1296           t = v->node;
1297           sol = get_varinfo (t)->solution;
1298           if (!bitmap_bit_p (sol, rhs))
1299             {             
1300               bitmap_set_bit (sol, rhs);
1301               if (!TEST_BIT (changed, t))
1302                 {
1303                   SET_BIT (changed, t);
1304                   changed_count++;
1305                 }
1306             }
1307         }
1308       else if (dump_file)
1309         fprintf (dump_file, "Untypesafe usage in do_da_constraint.\n");
1310       
1311     }
1312 }
1313
1314 /* Process a constraint C that represents x = *y, using DELTA as the
1315    starting solution.  */
1316
1317 static void
1318 do_sd_constraint (constraint_graph_t graph, constraint_t c,
1319                   bitmap delta)
1320 {
1321   unsigned int lhs = get_varinfo (c->lhs.var)->node;
1322   unsigned HOST_WIDE_INT roffset = c->rhs.offset;
1323   bool flag = false;
1324   bitmap sol = get_varinfo (lhs)->solution;
1325   unsigned int j;
1326   bitmap_iterator bi;
1327   
1328   /* For each variable j in delta (Sol(y)), add    
1329      an edge in the graph from j to x, and union Sol(j) into Sol(x).  */
1330   EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1331     {
1332       if (type_safe (j, &roffset))
1333         {
1334           varinfo_t v;
1335           unsigned HOST_WIDE_INT fieldoffset = get_varinfo (j)->offset + roffset;
1336           unsigned int t;
1337
1338           v = first_vi_for_offset (get_varinfo (j), fieldoffset);         
1339           t = v->node;
1340           if (int_add_graph_edge (graph, lhs, t, 0))
1341             flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);     
1342         }
1343       else if (dump_file)
1344         fprintf (dump_file, "Untypesafe usage in do_sd_constraint\n");
1345       
1346     }
1347
1348   /* If the LHS solution changed, mark the var as changed.  */
1349   if (flag)
1350     {
1351       get_varinfo (lhs)->solution = sol;
1352       if (!TEST_BIT (changed, lhs))
1353         {
1354           SET_BIT (changed, lhs);
1355           changed_count++;
1356         }
1357     }    
1358 }
1359
1360 /* Process a constraint C that represents *x = y.  */
1361
1362 static void
1363 do_ds_constraint (constraint_graph_t graph, constraint_t c, bitmap delta)
1364 {
1365   unsigned int rhs = get_varinfo (c->rhs.var)->node;
1366   unsigned HOST_WIDE_INT loff = c->lhs.offset;
1367   unsigned HOST_WIDE_INT roff = c->rhs.offset;
1368   bitmap sol = get_varinfo (rhs)->solution;
1369   unsigned int j;
1370   bitmap_iterator bi;
1371
1372   /* For each member j of delta (Sol(x)), add an edge from y to j and
1373      union Sol(y) into Sol(j) */
1374   EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1375     {
1376       if (type_safe (j, &loff))
1377         {
1378           varinfo_t v;
1379           unsigned int t;
1380           unsigned HOST_WIDE_INT fieldoffset = get_varinfo (j)->offset + loff;
1381
1382           v = first_vi_for_offset (get_varinfo (j), fieldoffset);
1383           t = v->node;
1384           if (int_add_graph_edge (graph, t, rhs, roff))
1385             {
1386               bitmap tmp = get_varinfo (t)->solution;
1387               if (set_union_with_increment (tmp, sol, roff))
1388                 {
1389                   get_varinfo (t)->solution = tmp;
1390                   if (t == rhs)
1391                     {
1392                       sol = get_varinfo (rhs)->solution;
1393                     }
1394                   if (!TEST_BIT (changed, t))
1395                     {
1396                       SET_BIT (changed, t);
1397                       changed_count++;
1398                     }
1399                 }
1400             }
1401         }    
1402       else if (dump_file)
1403         fprintf (dump_file, "Untypesafe usage in do_ds_constraint\n");
1404     }
1405 }
1406
1407 /* Handle a non-simple (simple meaning requires no iteration), non-copy
1408    constraint (IE *x = &y, x = *y, and *x = y).  */
1409    
1410 static void
1411 do_complex_constraint (constraint_graph_t graph, constraint_t c, bitmap delta)
1412 {
1413   if (c->lhs.type == DEREF)
1414     {
1415       if (c->rhs.type == ADDRESSOF)
1416         {
1417           /* *x = &y */
1418           do_da_constraint (graph, c, delta);
1419         }
1420       else
1421         {
1422           /* *x = y */
1423           do_ds_constraint (graph, c, delta);
1424         }
1425     }
1426   else
1427     {
1428       /* x = *y */
1429       do_sd_constraint (graph, c, delta);
1430     }
1431 }
1432
1433 /* Initialize and return a new SCC info structure.  */
1434
1435 static struct scc_info *
1436 init_scc_info (void)
1437 {
1438   struct scc_info *si = xmalloc (sizeof (struct scc_info));
1439   size_t size = VEC_length (varinfo_t, varmap);
1440
1441   si->current_index = 0;
1442   si->visited = sbitmap_alloc (size);
1443   sbitmap_zero (si->visited);
1444   si->in_component = sbitmap_alloc (size);
1445   sbitmap_ones (si->in_component);
1446   si->visited_index = xcalloc (sizeof (unsigned int), size + 1);
1447   si->scc_stack = VEC_alloc (uint, heap, 1);
1448   si->unification_queue = VEC_alloc (uint, heap, 1);
1449   return si;
1450 }
1451
1452 /* Free an SCC info structure pointed to by SI */
1453
1454 static void
1455 free_scc_info (struct scc_info *si)
1456 {  
1457   sbitmap_free (si->visited);
1458   sbitmap_free (si->in_component);
1459   free (si->visited_index);
1460   VEC_free (uint, heap, si->scc_stack);
1461   VEC_free (uint, heap, si->unification_queue);
1462   free(si); 
1463 }
1464
1465
1466 /* Find cycles in GRAPH that occur, using strongly connected components, and
1467    collapse the cycles into a single representative node.  if UPDATE_CHANGED
1468    is true, then update the changed sbitmap to note those nodes whose
1469    solutions have changed as a result of collapsing.  */
1470
1471 static void
1472 find_and_collapse_graph_cycles (constraint_graph_t graph, bool update_changed)
1473 {
1474   unsigned int i;
1475   unsigned int size = VEC_length (varinfo_t, varmap);
1476   struct scc_info *si = init_scc_info ();
1477
1478   for (i = 0; i != size; ++i)
1479     if (!TEST_BIT (si->visited, i) && get_varinfo (i)->node == i)
1480       scc_visit (graph, si, i);
1481   process_unification_queue (graph, si, update_changed);
1482   free_scc_info (si);
1483 }
1484
1485 /* Compute a topological ordering for GRAPH, and store the result in the
1486    topo_info structure TI.  */
1487
1488 static void 
1489 compute_topo_order (constraint_graph_t graph,
1490                     struct topo_info *ti)
1491 {
1492   unsigned int i;
1493   unsigned int size = VEC_length (varinfo_t, varmap);
1494   
1495   for (i = 0; i != size; ++i)
1496     if (!TEST_BIT (ti->visited, i) && get_varinfo (i)->node == i)
1497       topo_visit (graph, ti, i);
1498 }
1499
1500 /* Return true if bitmap B is empty, or a bitmap other than bit 0 is set. */
1501
1502 static bool
1503 bitmap_other_than_zero_bit_set (bitmap b)
1504 {
1505   unsigned int i;
1506   bitmap_iterator bi;
1507
1508   if (bitmap_empty_p (b))
1509     return false;
1510   EXECUTE_IF_SET_IN_BITMAP (b, 1, i, bi)
1511     return true;
1512   return false;
1513 }
1514
1515 /* Perform offline variable substitution.
1516    
1517    This is a linear time way of identifying variables that must have
1518    equivalent points-to sets, including those caused by static cycles,
1519    and single entry subgraphs, in the constraint graph.
1520
1521    The technique is described in "Off-line variable substitution for
1522    scaling points-to analysis" by Atanas Rountev and Satish Chandra,
1523    in "ACM SIGPLAN Notices" volume 35, number 5, pages 47-56.  */
1524
1525 static void
1526 perform_var_substitution (constraint_graph_t graph)
1527 {
1528   struct topo_info *ti = init_topo_info ();
1529  
1530   /* Compute the topological ordering of the graph, then visit each
1531      node in topological order.  */
1532   compute_topo_order (graph, ti);
1533  
1534   while (VEC_length (uint, ti->topo_order) != 0)
1535     {
1536       unsigned int i = VEC_pop (uint, ti->topo_order);
1537       unsigned int pred;
1538       varinfo_t vi = get_varinfo (i);
1539       bool okay_to_elim = false;
1540       unsigned int root = VEC_length (varinfo_t, varmap);
1541       VEC(constraint_edge_t,gc) *predvec = graph->preds[i];
1542       constraint_edge_t ce;
1543       bitmap tmp;
1544
1545       /* We can't eliminate things whose address is taken, or which is
1546          the target of a dereference.  */
1547       if (vi->address_taken || vi->indirect_target)
1548         continue;
1549
1550       /* See if all predecessors of I are ripe for elimination */
1551       for (pred = 0; VEC_iterate (constraint_edge_t, predvec, pred, ce); pred++)
1552         {
1553           bitmap weight;
1554           unsigned int w;
1555           weight = get_graph_weights (graph, *ce);
1556         
1557           /* We can't eliminate variables that have non-zero weighted
1558              edges between them.  */
1559           if (bitmap_other_than_zero_bit_set (weight))
1560             {
1561               okay_to_elim = false;
1562               break;
1563             }
1564           w = get_varinfo (ce->dest)->node;
1565
1566           /* We can't eliminate the node if one of the predecessors is
1567              part of a different strongly connected component.  */
1568           if (!okay_to_elim)
1569             {
1570               root = w;
1571               okay_to_elim = true;
1572             }
1573           else if (w != root)
1574             {
1575               okay_to_elim = false;
1576               break;
1577             }
1578
1579           /* Theorem 4 in Rountev and Chandra: If i is a direct node,
1580              then Solution(i) is a subset of Solution (w), where w is a
1581              predecessor in the graph.  
1582              Corrolary: If all predecessors of i have the same
1583              points-to set, then i has that same points-to set as
1584              those predecessors.  */
1585           tmp = BITMAP_ALLOC (NULL);
1586           bitmap_and_compl (tmp, get_varinfo (i)->solution,
1587                             get_varinfo (w)->solution);
1588           if (!bitmap_empty_p (tmp))
1589             {
1590               okay_to_elim = false;
1591               BITMAP_FREE (tmp);
1592               break;
1593             }
1594           BITMAP_FREE (tmp);
1595         }
1596
1597       /* See if the root is different than the original node. 
1598          If so, we've found an equivalence.  */
1599       if (root != get_varinfo (i)->node && okay_to_elim)
1600         {
1601           /* Found an equivalence */
1602           get_varinfo (i)->node = root;
1603           collapse_nodes (graph, root, i);
1604           if (dump_file && (dump_flags & TDF_DETAILS))
1605             fprintf (dump_file, "Collapsing %s into %s\n",
1606                      get_varinfo (i)->name,
1607                      get_varinfo (root)->name);
1608           stats.collapsed_vars++;
1609         }
1610     }
1611
1612   free_topo_info (ti);
1613 }
1614
1615
1616 /* Solve the constraint graph GRAPH using our worklist solver.
1617    This is based on the PW* family of solvers from the "Efficient Field
1618    Sensitive Pointer Analysis for C" paper.
1619    It works by iterating over all the graph nodes, processing the complex
1620    constraints and propagating the copy constraints, until everything stops
1621    changed.  This corresponds to steps 6-8 in the solving list given above.  */
1622
1623 static void
1624 solve_graph (constraint_graph_t graph)
1625 {
1626   unsigned int size = VEC_length (varinfo_t, varmap);
1627   unsigned int i;
1628
1629   changed_count = size;
1630   changed = sbitmap_alloc (size);
1631   sbitmap_ones (changed);
1632   
1633   /* The already collapsed/unreachable nodes will never change, so we
1634      need to  account for them in changed_count.  */
1635   for (i = 0; i < size; i++)
1636     if (get_varinfo (i)->node != i)
1637       changed_count--;
1638   
1639   while (changed_count > 0)
1640     {
1641       unsigned int i;
1642       struct topo_info *ti = init_topo_info ();
1643       stats.iterations++;
1644       
1645       bitmap_obstack_initialize (&iteration_obstack);
1646       
1647       if (edge_added)
1648         {
1649           /* We already did cycle elimination once, when we did
1650              variable substitution, so we don't need it again for the
1651              first iteration.  */
1652           if (stats.iterations > 1)
1653             find_and_collapse_graph_cycles (graph, true);
1654           
1655           edge_added = false;
1656         }
1657
1658       compute_topo_order (graph, ti);
1659
1660       while (VEC_length (uint, ti->topo_order) != 0)
1661         {
1662           i = VEC_pop (uint, ti->topo_order);
1663           gcc_assert (get_varinfo (i)->node == i);
1664
1665           /* If the node has changed, we need to process the
1666              complex constraints and outgoing edges again.  */
1667           if (TEST_BIT (changed, i))
1668             {
1669               unsigned int j;
1670               constraint_t c;
1671               constraint_edge_t e;
1672               bitmap solution;
1673               VEC(constraint_t,gc) *complex = get_varinfo (i)->complex;
1674               VEC(constraint_edge_t,gc) *succs;
1675
1676               RESET_BIT (changed, i);
1677               changed_count--;
1678
1679               /* Process the complex constraints */
1680               solution = get_varinfo (i)->solution;
1681               for (j = 0; VEC_iterate (constraint_t, complex, j, c); j++)
1682                 do_complex_constraint (graph, c, solution);
1683
1684               /* Propagate solution to all successors.  */
1685               succs = graph->succs[i];
1686               for (j = 0; VEC_iterate (constraint_edge_t, succs, j, e); j++)
1687                 {
1688                   bitmap tmp = get_varinfo (e->dest)->solution;
1689                   bool flag = false;
1690                   unsigned int k;
1691                   bitmap weights = e->weights;
1692                   bitmap_iterator bi;
1693
1694                   gcc_assert (!bitmap_empty_p (weights));
1695                   EXECUTE_IF_SET_IN_BITMAP (weights, 0, k, bi)
1696                     flag |= set_union_with_increment (tmp, solution, k);
1697
1698                   if (flag)
1699                     {
1700                       get_varinfo (e->dest)->solution = tmp;                
1701                       if (!TEST_BIT (changed, e->dest))
1702                         {
1703                           SET_BIT (changed, e->dest);
1704                           changed_count++;
1705                         }
1706                     }
1707                 }
1708             }
1709         }
1710       free_topo_info (ti);
1711       bitmap_obstack_release (&iteration_obstack);
1712     }
1713
1714   sbitmap_free (changed);
1715 }
1716
1717
1718 /* CONSTRAINT AND VARIABLE GENERATION FUNCTIONS */
1719
1720 /* Map from trees to variable ids.  */    
1721 static htab_t id_for_tree;
1722
1723 typedef struct tree_id
1724 {
1725   tree t;
1726   unsigned int id;
1727 } *tree_id_t;
1728
1729 /* Hash a tree id structure.  */
1730
1731 static hashval_t 
1732 tree_id_hash (const void *p)
1733 {
1734   const tree_id_t ta = (tree_id_t) p;
1735   return htab_hash_pointer (ta->t);
1736 }
1737
1738 /* Return true if the tree in P1 and the tree in P2 are the same.  */
1739
1740 static int
1741 tree_id_eq (const void *p1, const void *p2)
1742 {
1743   const tree_id_t ta1 = (tree_id_t) p1;
1744   const tree_id_t ta2 = (tree_id_t) p2;
1745   return ta1->t == ta2->t;
1746 }
1747
1748 /* Insert ID as the variable id for tree T in the hashtable.  */
1749
1750 static void 
1751 insert_id_for_tree (tree t, int id)
1752 {
1753   void **slot;
1754   struct tree_id finder;
1755   tree_id_t new_pair;
1756   
1757   finder.t = t;
1758   slot = htab_find_slot (id_for_tree, &finder, INSERT);
1759   gcc_assert (*slot == NULL);
1760   new_pair = xmalloc (sizeof (struct tree_id));
1761   new_pair->t = t;
1762   new_pair->id = id;
1763   *slot = (void *)new_pair;
1764 }
1765
1766 /* Find the variable id for tree T in ID_FOR_TREE.  If T does not
1767    exist in the hash table, return false, otherwise, return true and
1768    set *ID to the id we found.  */
1769
1770 static bool
1771 lookup_id_for_tree (tree t, unsigned int *id)
1772 {
1773   tree_id_t pair;
1774   struct tree_id finder;
1775
1776   finder.t = t;
1777   pair = htab_find (id_for_tree,  &finder);
1778   if (pair == NULL)
1779     return false;
1780   *id = pair->id;
1781   return true;
1782 }
1783
1784 /* Return a printable name for DECL  */
1785
1786 static const char *
1787 alias_get_name (tree decl)
1788 {
1789   const char *res = get_name (decl);
1790   char *temp;
1791   int num_printed = 0;
1792
1793   if (res != NULL)
1794     return res;
1795
1796   res = "NULL";
1797   if (TREE_CODE (decl) == SSA_NAME)
1798     {
1799       num_printed = asprintf (&temp, "%s_%u", 
1800                               alias_get_name (SSA_NAME_VAR (decl)),
1801                               SSA_NAME_VERSION (decl));
1802     }
1803   else if (DECL_P (decl))
1804     {
1805       num_printed = asprintf (&temp, "D.%u", DECL_UID (decl));
1806     }
1807   if (num_printed > 0)
1808     {
1809       res = ggc_strdup (temp);
1810       free (temp);
1811     }
1812   return res;
1813 }
1814
1815 /* Find the variable id for tree T in the hashtable.
1816    If T doesn't exist in the hash table, create an entry for it.  */
1817
1818 static unsigned int
1819 get_id_for_tree (tree t)
1820 {
1821   tree_id_t pair;
1822   struct tree_id finder;
1823
1824   finder.t = t;
1825   pair = htab_find (id_for_tree,  &finder);
1826   if (pair == NULL)
1827     return create_variable_info_for (t, alias_get_name (t));
1828   
1829   return pair->id;
1830 }
1831
1832 /* Get a constraint expression from an SSA_VAR_P node.  */
1833
1834 static struct constraint_expr
1835 get_constraint_exp_from_ssa_var (tree t)
1836 {
1837   struct constraint_expr cexpr;
1838
1839   gcc_assert (SSA_VAR_P (t) || DECL_P (t));
1840
1841   /* For parameters, get at the points-to set for the actual parm
1842      decl.  */
1843   if (TREE_CODE (t) == SSA_NAME 
1844       && TREE_CODE (SSA_NAME_VAR (t)) == PARM_DECL 
1845       && default_def (SSA_NAME_VAR (t)) == t)
1846     return get_constraint_exp_from_ssa_var (SSA_NAME_VAR (t));
1847
1848   cexpr.type = SCALAR;
1849   
1850   if (TREE_READONLY (t))
1851     {
1852       cexpr.type = ADDRESSOF;
1853       cexpr.var = readonly_id;
1854     }
1855   else
1856     cexpr.var = get_id_for_tree (t);    
1857     
1858   cexpr.offset = 0;
1859   return cexpr;
1860 }
1861
1862 /* Process a completed constraint T, and add it to the constraint
1863    list.  */
1864
1865 static void
1866 process_constraint (constraint_t t)
1867 {
1868   struct constraint_expr rhs = t->rhs;
1869   struct constraint_expr lhs = t->lhs;
1870   
1871   gcc_assert (rhs.var < VEC_length (varinfo_t, varmap));
1872   gcc_assert (lhs.var < VEC_length (varinfo_t, varmap));
1873
1874   /* ANYTHING == ANYTHING is pointless.  */
1875   if (lhs.var == anything_id && rhs.var == anything_id)
1876     return;
1877
1878   /* If we have &ANYTHING = something, convert to SOMETHING = &ANYTHING) */
1879   else if (lhs.var == anything_id && lhs.type == ADDRESSOF)
1880     {
1881       rhs = t->lhs;
1882       t->lhs = t->rhs;
1883       t->rhs = rhs;
1884       process_constraint (t);
1885     }   
1886   /* This can happen in our IR with things like n->a = *p */
1887   else if (rhs.type == DEREF && lhs.type == DEREF && rhs.var != anything_id)
1888     {
1889       /* Split into tmp = *rhs, *lhs = tmp */
1890       tree rhsdecl = get_varinfo (rhs.var)->decl;
1891       tree pointertype = TREE_TYPE (rhsdecl);
1892       tree pointedtotype = TREE_TYPE (pointertype);
1893       tree tmpvar = create_tmp_var_raw (pointedtotype, "doubledereftmp");
1894       struct constraint_expr tmplhs = get_constraint_exp_from_ssa_var (tmpvar);
1895       
1896       /* If this is an aggregate of known size, we should have passed
1897          this off to do_structure_copy, and it should have broken it
1898          up.  */
1899       gcc_assert (!AGGREGATE_TYPE_P (pointedtotype) 
1900                   || get_varinfo (rhs.var)->is_unknown_size_var);
1901       
1902       process_constraint (new_constraint (tmplhs, rhs));
1903       process_constraint (new_constraint (lhs, tmplhs));
1904     }
1905   else if (rhs.type == ADDRESSOF)
1906     {
1907       varinfo_t vi;
1908       gcc_assert (rhs.offset == 0);
1909       
1910       for (vi = get_varinfo (rhs.var); vi != NULL; vi = vi->next)
1911         vi->address_taken = true;
1912
1913       VEC_safe_push (constraint_t, gc, constraints, t);
1914     }
1915   else
1916     {
1917       if (lhs.type != DEREF && rhs.type == DEREF)
1918         get_varinfo (lhs.var)->indirect_target = true;
1919       VEC_safe_push (constraint_t, gc, constraints, t);
1920     }
1921 }
1922
1923
1924 /* Return the position, in bits, of FIELD_DECL from the beginning of its
1925    structure.  */
1926
1927 static unsigned HOST_WIDE_INT
1928 bitpos_of_field (const tree fdecl)
1929 {
1930
1931   if (TREE_CODE (DECL_FIELD_OFFSET (fdecl)) != INTEGER_CST
1932       || TREE_CODE (DECL_FIELD_BIT_OFFSET (fdecl)) != INTEGER_CST)
1933     return -1;
1934   
1935   return (tree_low_cst (DECL_FIELD_OFFSET (fdecl), 1) * 8) 
1936          + tree_low_cst (DECL_FIELD_BIT_OFFSET (fdecl), 1);
1937 }
1938
1939
1940 /* Given a COMPONENT_REF T, return the constraint_expr for it.  */
1941
1942 static struct constraint_expr
1943 get_constraint_for_component_ref (tree t)
1944 {
1945   struct constraint_expr result;
1946   HOST_WIDE_INT bitsize;
1947   HOST_WIDE_INT bitpos;
1948   tree offset;
1949   enum machine_mode mode;
1950   int unsignedp;
1951   int volatilep;
1952   tree forzero;
1953   
1954   result.offset = 0;
1955   result.type = SCALAR;
1956   result.var = 0;
1957
1958   /* Some people like to do cute things like take the address of
1959      &0->a.b */
1960   forzero = t;
1961   while (!SSA_VAR_P (forzero) && !CONSTANT_CLASS_P (forzero))
1962       forzero = TREE_OPERAND (forzero, 0);
1963
1964   if (CONSTANT_CLASS_P (forzero) && integer_zerop (forzero)) 
1965     {
1966       result.offset = 0;
1967       result.var = integer_id;
1968       result.type = SCALAR;
1969       return result;
1970     }
1971  
1972   t = get_inner_reference (t, &bitsize, &bitpos, &offset, &mode,
1973                            &unsignedp, &volatilep, false);
1974   result = get_constraint_for (t);
1975
1976   /* This can also happen due to weird offsetof type macros.  */
1977   if (TREE_CODE (t) != ADDR_EXPR && result.type == ADDRESSOF)
1978     result.type = SCALAR;
1979   
1980   /* If we know where this goes, then yay. Otherwise, booo. */
1981
1982   if (offset == NULL && bitsize != -1)
1983     {
1984       result.offset = bitpos;
1985     }   
1986   else
1987     {
1988       result.var = anything_id;
1989       result.offset = 0;      
1990     }
1991
1992   if (result.type == SCALAR)
1993     {
1994       /* In languages like C, you can access one past the end of an
1995          array.  You aren't allowed to dereference it, so we can
1996          ignore this constraint. When we handle pointer subtraction,
1997          we may have to do something cute here.  */
1998       
1999       if (result.offset < get_varinfo (result.var)->fullsize)   
2000         result.var = first_vi_for_offset (get_varinfo (result.var), 
2001                                           result.offset)->id;
2002       else
2003         if (dump_file && (dump_flags & TDF_DETAILS))
2004           fprintf (dump_file, "Access to past the end of variable, ignoring\n");
2005
2006       result.offset = 0;
2007     }
2008   
2009   return result;
2010 }
2011
2012
2013 /* Dereference the constraint expression CONS, and return the result.
2014    DEREF (ADDRESSOF) = SCALAR
2015    DEREF (SCALAR) = DEREF
2016    DEREF (DEREF) = (temp = DEREF1; result = DEREF(temp))
2017    This is needed so that we can handle dereferencing DEREF constraints.  */
2018
2019 static struct constraint_expr
2020 do_deref (struct constraint_expr cons)
2021 {
2022   if (cons.type == SCALAR)
2023     {
2024       cons.type = DEREF;
2025       return cons;
2026     }
2027   else if (cons.type == ADDRESSOF)
2028     {
2029       cons.type = SCALAR;
2030       return cons;
2031     }
2032   else if (cons.type == DEREF)
2033     {
2034       tree tmpvar = create_tmp_var_raw (ptr_type_node, "derefmp");
2035       struct constraint_expr tmplhs = get_constraint_exp_from_ssa_var (tmpvar);
2036       process_constraint (new_constraint (tmplhs, cons));
2037       cons.var = tmplhs.var;
2038       return cons;
2039     }
2040   gcc_unreachable ();
2041 }
2042
2043
2044 /* Given a tree T, return the constraint expression for it.  */
2045
2046 static struct constraint_expr
2047 get_constraint_for (tree t)
2048 {
2049   struct constraint_expr temp;
2050
2051   /* x = integer is all glommed to a single variable, which doesn't
2052      point to anything by itself.  That is, of course, unless it is an
2053      integer constant being treated as a pointer, in which case, we
2054      will return that this is really the addressof anything.  This
2055      happens below, since it will fall into the default case. The only
2056      case we know something about an integer treated like a pointer is
2057      when it is the NULL pointer, and then we just say it points to
2058      NULL.  */
2059   if (TREE_CODE (t) == INTEGER_CST
2060       && !POINTER_TYPE_P (TREE_TYPE (t)))
2061     {
2062       temp.var = integer_id;
2063       temp.type = SCALAR;
2064       temp.offset = 0;
2065       return temp;
2066     }
2067   else if (TREE_CODE (t) == INTEGER_CST
2068            && integer_zerop (t))
2069     {
2070       temp.var = nothing_id;
2071       temp.type = ADDRESSOF;
2072       temp.offset = 0;
2073       return temp;
2074     }
2075
2076   switch (TREE_CODE_CLASS (TREE_CODE (t)))
2077     {
2078     case tcc_expression:
2079       {
2080         switch (TREE_CODE (t))
2081           {
2082           case ADDR_EXPR:
2083             {
2084               temp = get_constraint_for (TREE_OPERAND (t, 0));
2085                if (temp.type == DEREF)
2086                  temp.type = SCALAR;
2087                else
2088                  temp.type = ADDRESSOF;
2089               return temp;
2090             }
2091             break;
2092           case CALL_EXPR:
2093             
2094             /* XXX: In interprocedural mode, if we didn't have the
2095                body, we would need to do *each pointer argument =
2096                &ANYTHING added.  */
2097             if (call_expr_flags (t) & (ECF_MALLOC | ECF_MAY_BE_ALLOCA))
2098               {
2099                 tree heapvar = create_tmp_var_raw (ptr_type_node, "HEAP");
2100                 temp.var = create_variable_info_for (heapvar,
2101                                                      alias_get_name (heapvar));
2102                 
2103                 get_varinfo (temp.var)->is_artificial_var = 1;
2104                 temp.type = ADDRESSOF;
2105                 temp.offset = 0;
2106                 return temp;
2107               }
2108             /* FALLTHRU */
2109           default:
2110             {
2111               temp.type = ADDRESSOF;
2112               temp.var = anything_id;
2113               temp.offset = 0;
2114               return temp;
2115             }
2116           }
2117       }
2118     case tcc_reference:
2119       {
2120         switch (TREE_CODE (t))
2121           {
2122           case INDIRECT_REF:
2123             {
2124               temp = get_constraint_for (TREE_OPERAND (t, 0));
2125               temp = do_deref (temp);
2126               return temp;
2127             }
2128           case ARRAY_REF:
2129           case COMPONENT_REF:
2130             temp = get_constraint_for_component_ref (t);
2131             return temp;
2132           default:
2133             {
2134               temp.type = ADDRESSOF;
2135               temp.var = anything_id;
2136               temp.offset = 0;
2137               return temp;
2138             }
2139           }
2140       }
2141     case tcc_unary:
2142       {
2143         switch (TREE_CODE (t))
2144           {
2145           case NOP_EXPR:
2146           case CONVERT_EXPR:
2147           case NON_LVALUE_EXPR:
2148             {
2149               tree op = TREE_OPERAND (t, 0);
2150               
2151               /* Cast from non-pointer to pointers are bad news for us.
2152                  Anything else, we see through */
2153               if (!(POINTER_TYPE_P (TREE_TYPE (t))  &&
2154                     ! POINTER_TYPE_P (TREE_TYPE (op))))
2155                 return get_constraint_for (op);
2156             }
2157           default:
2158             {
2159               temp.type = ADDRESSOF;
2160               temp.var = anything_id;
2161               temp.offset = 0;
2162               return temp;
2163             }
2164           }
2165       }
2166     case tcc_exceptional:
2167       {
2168         switch (TREE_CODE (t))
2169           {
2170           case PHI_NODE:           
2171             return get_constraint_for (PHI_RESULT (t));
2172           case SSA_NAME:
2173             return get_constraint_exp_from_ssa_var (t);
2174           default:
2175             {
2176               temp.type = ADDRESSOF;
2177               temp.var = anything_id;
2178               temp.offset = 0;
2179               return temp;
2180             }
2181           }
2182       }
2183     case tcc_declaration:
2184       return get_constraint_exp_from_ssa_var (t);
2185     default:
2186       {
2187         temp.type = ADDRESSOF;
2188         temp.var = anything_id;
2189         temp.offset = 0;
2190         return temp;
2191       }
2192     }
2193 }
2194
2195
2196 /* Handle the structure copy case where we have a simple structure copy
2197    between LHS and RHS that is of SIZE (in bits) 
2198   
2199    For each field of the lhs variable (lhsfield)
2200      For each field of the rhs variable at lhsfield.offset (rhsfield)
2201        add the constraint lhsfield = rhsfield
2202 */
2203
2204 static void
2205 do_simple_structure_copy (const struct constraint_expr lhs,
2206                           const struct constraint_expr rhs,
2207                           const unsigned HOST_WIDE_INT size)
2208 {
2209   varinfo_t p = get_varinfo (lhs.var);
2210   unsigned HOST_WIDE_INT pstart,last;
2211
2212   pstart = p->offset;
2213   last = p->offset + size;
2214   for (; p && p->offset < last; p = p->next)
2215     {
2216       varinfo_t q;
2217       struct constraint_expr templhs = lhs;
2218       struct constraint_expr temprhs = rhs;
2219       unsigned HOST_WIDE_INT fieldoffset;
2220
2221       templhs.var = p->id;            
2222       q = get_varinfo (temprhs.var);
2223       fieldoffset = p->offset - pstart;
2224       q = first_vi_for_offset (q, q->offset + fieldoffset);
2225       temprhs.var = q->id;
2226       process_constraint (new_constraint (templhs, temprhs));
2227     }
2228 }
2229
2230
2231 /* Handle the structure copy case where we have a  structure copy between a
2232    aggregate on the LHS and a dereference of a pointer on the RHS
2233    that is of SIZE (in bits) 
2234   
2235    For each field of the lhs variable (lhsfield)
2236        rhs.offset = lhsfield->offset
2237        add the constraint lhsfield = rhs
2238 */
2239
2240 static void
2241 do_rhs_deref_structure_copy (const struct constraint_expr lhs,
2242                              const struct constraint_expr rhs,
2243                              const unsigned HOST_WIDE_INT size)
2244 {
2245   varinfo_t p = get_varinfo (lhs.var);
2246   unsigned HOST_WIDE_INT pstart,last;
2247   pstart = p->offset;
2248   last = p->offset + size;
2249
2250   for (; p && p->offset < last; p = p->next)
2251     {
2252       varinfo_t q;
2253       struct constraint_expr templhs = lhs;
2254       struct constraint_expr temprhs = rhs;
2255       unsigned HOST_WIDE_INT fieldoffset;
2256
2257
2258       if (templhs.type == SCALAR)
2259         templhs.var = p->id;      
2260       else
2261         templhs.offset = p->offset;
2262       
2263       q = get_varinfo (temprhs.var);
2264       fieldoffset = p->offset - pstart;      
2265       temprhs.offset += fieldoffset;
2266       process_constraint (new_constraint (templhs, temprhs));
2267     }
2268 }
2269
2270 /* Handle the structure copy case where we have a structure copy
2271    between a aggregate on the RHS and a dereference of a pointer on
2272    the LHS that is of SIZE (in bits) 
2273
2274    For each field of the rhs variable (rhsfield)
2275        lhs.offset = rhsfield->offset
2276        add the constraint lhs = rhsfield
2277 */
2278
2279 static void
2280 do_lhs_deref_structure_copy (const struct constraint_expr lhs,
2281                              const struct constraint_expr rhs,
2282                              const unsigned HOST_WIDE_INT size)
2283 {
2284   varinfo_t p = get_varinfo (rhs.var);
2285   unsigned HOST_WIDE_INT pstart,last;
2286   pstart = p->offset;
2287   last = p->offset + size;
2288
2289   for (; p && p->offset < last; p = p->next)
2290     {
2291       varinfo_t q;
2292       struct constraint_expr templhs = lhs;
2293       struct constraint_expr temprhs = rhs;
2294       unsigned HOST_WIDE_INT fieldoffset;
2295
2296
2297       if (temprhs.type == SCALAR)
2298         temprhs.var = p->id;      
2299       else
2300         temprhs.offset = p->offset;
2301       
2302       q = get_varinfo (templhs.var);
2303       fieldoffset = p->offset - pstart;      
2304       templhs.offset += fieldoffset;
2305       process_constraint (new_constraint (templhs, temprhs));
2306     }
2307 }
2308
2309
2310 /* Handle aggregate copies by expanding into copies of the respective
2311    fields of the structures.  */
2312
2313 static void
2314 do_structure_copy (tree lhsop, tree rhsop)
2315 {
2316   struct constraint_expr lhs, rhs, tmp;
2317   varinfo_t p;
2318   unsigned HOST_WIDE_INT lhssize;
2319   unsigned HOST_WIDE_INT rhssize;
2320
2321   lhssize = TREE_INT_CST_LOW (TYPE_SIZE (TREE_TYPE (lhsop)));
2322   rhssize = TREE_INT_CST_LOW (TYPE_SIZE (TREE_TYPE (rhsop)));
2323   lhs = get_constraint_for (lhsop);  
2324   rhs = get_constraint_for (rhsop);
2325   
2326   /* If we have special var = x, swap it around.  */
2327   if (lhs.var <= integer_id && rhs.var > integer_id)
2328     {
2329       tmp = lhs;
2330       lhs = rhs;
2331       rhs = tmp;
2332     }
2333   
2334   /* If the RHS is a special var, set all the LHS fields to that
2335      special var.  */
2336   if (rhs.var <= integer_id)
2337     {
2338       for (p = get_varinfo (lhs.var); p; p = p->next)
2339         {
2340           struct constraint_expr templhs = lhs;
2341           struct constraint_expr temprhs = rhs;
2342           if (templhs.type == SCALAR )
2343             templhs.var = p->id;
2344           else
2345             templhs.offset += p->offset;
2346           process_constraint (new_constraint (templhs, temprhs));
2347         }
2348     }
2349   else
2350     {
2351       if (rhs.type == SCALAR && lhs.type == SCALAR)  
2352         do_simple_structure_copy (lhs, rhs, MIN (lhssize, rhssize));
2353       else if (lhs.type != DEREF && rhs.type == DEREF)
2354         do_rhs_deref_structure_copy (lhs, rhs, MIN (lhssize, rhssize));
2355       else if (lhs.type == DEREF && rhs.type != DEREF)
2356         do_lhs_deref_structure_copy (lhs, rhs, MIN (lhssize, rhssize));
2357       else
2358         {
2359           tree rhsdecl = get_varinfo (rhs.var)->decl;
2360           tree pointertype = TREE_TYPE (rhsdecl);
2361           tree pointedtotype = TREE_TYPE (pointertype);
2362           tree tmpvar;
2363           gcc_assert (rhs.type == DEREF && lhs.type == DEREF);
2364           tmpvar = create_tmp_var_raw (pointedtotype, "structcopydereftmp");
2365           lhs = get_constraint_for (tmpvar);
2366           do_rhs_deref_structure_copy (lhs, rhs, MIN (lhssize, rhssize));
2367           rhs = lhs;
2368           lhs = get_constraint_for (lhsop);
2369           do_lhs_deref_structure_copy (lhs, rhs, MIN (lhssize, rhssize));
2370         }
2371     }
2372 }
2373
2374
2375 /* Return true if REF, a COMPONENT_REF, has an INDIRECT_REF somewhere
2376    in it.  */
2377
2378 static inline bool
2379 ref_contains_indirect_ref (tree ref)
2380 {
2381   while (handled_component_p (ref))
2382     {
2383       if (TREE_CODE (ref) == INDIRECT_REF)
2384         return true;
2385       ref = TREE_OPERAND (ref, 0);
2386     }
2387   return false;
2388 }
2389
2390
2391 /*  Tree walker that is the heart of the aliasing infrastructure.
2392     TP is a pointer to the current tree.
2393     WALK_SUBTREES specifies whether to continue traversing subtrees or
2394     not.
2395     Returns NULL_TREE when we should stop.
2396     
2397     This function is the main part of the constraint builder. It
2398     walks the trees, calling the appropriate building functions
2399     to process various statements.  */
2400
2401 static void
2402 find_func_aliases (tree t)
2403 {
2404   struct constraint_expr lhs, rhs;
2405   switch (TREE_CODE (t))
2406     {      
2407     case PHI_NODE:
2408       {
2409         int i;
2410
2411         /* Only care about pointers and structures containing
2412            pointers.  */
2413         if (POINTER_TYPE_P (TREE_TYPE (PHI_RESULT (t)))
2414             || AGGREGATE_TYPE_P (TREE_TYPE (PHI_RESULT (t))))
2415           {
2416             lhs = get_constraint_for (PHI_RESULT (t));
2417             for (i = 0; i < PHI_NUM_ARGS (t); i++)
2418               {
2419                 rhs = get_constraint_for (PHI_ARG_DEF (t, i));
2420                 process_constraint (new_constraint (lhs, rhs));
2421               }
2422           }
2423       }
2424       break;
2425
2426     case MODIFY_EXPR:
2427       {
2428         tree lhsop = TREE_OPERAND (t, 0);
2429         tree rhsop = TREE_OPERAND (t, 1);
2430         int i;  
2431
2432         if (AGGREGATE_TYPE_P (TREE_TYPE (lhsop)) 
2433             && AGGREGATE_TYPE_P (TREE_TYPE (rhsop)))
2434           {
2435             do_structure_copy (lhsop, rhsop);
2436           }
2437         else
2438           {
2439             /* Only care about operations with pointers, structures
2440                containing pointers, dereferences, and call
2441                expressions.  */
2442             if (POINTER_TYPE_P (TREE_TYPE (lhsop))
2443                 || AGGREGATE_TYPE_P (TREE_TYPE (lhsop))
2444                 || ref_contains_indirect_ref (lhsop)
2445                 || TREE_CODE (rhsop) == CALL_EXPR)
2446               {
2447                 lhs = get_constraint_for (lhsop);
2448                 switch (TREE_CODE_CLASS (TREE_CODE (rhsop)))
2449                   {
2450                     /* RHS that consist of unary operations,
2451                        exceptional types, or bare decls/constants, get
2452                        handled directly by get_constraint_for.  */ 
2453                   case tcc_reference:
2454                   case tcc_declaration:
2455                   case tcc_constant:
2456                   case tcc_exceptional:
2457                   case tcc_expression:
2458                   case tcc_unary:
2459                     {
2460                       rhs = get_constraint_for (rhsop);
2461                       process_constraint (new_constraint (lhs, rhs));
2462                     }
2463                     break;
2464
2465                     /* Otherwise, walk each operand.  */
2466                   default:
2467                     for (i = 0; i < TREE_CODE_LENGTH (TREE_CODE (rhsop)); i++)
2468                       {
2469                         tree op = TREE_OPERAND (rhsop, i);
2470                         rhs = get_constraint_for (op);
2471                         process_constraint (new_constraint (lhs, rhs));
2472                       }
2473                   }      
2474               }
2475           }
2476       }
2477       break;
2478
2479     default:
2480       break;
2481     }
2482 }
2483
2484
2485 /* Find the first varinfo in the same variable as START that overlaps with
2486    OFFSET.
2487    Effectively, walk the chain of fields for the variable START to find the
2488    first field that overlaps with OFFSET.
2489    Abort if we can't find one.  */
2490
2491 static varinfo_t 
2492 first_vi_for_offset (varinfo_t start, unsigned HOST_WIDE_INT offset)
2493 {
2494   varinfo_t curr = start;
2495   while (curr)
2496     {
2497       /* We may not find a variable in the field list with the actual
2498          offset when when we have glommed a structure to a variable.
2499          In that case, however, offset should still be within the size
2500          of the variable. */
2501       if (offset >= curr->offset && offset < (curr->offset +  curr->size))
2502         return curr;
2503       curr = curr->next;
2504     }
2505
2506   gcc_unreachable ();
2507 }
2508
2509
2510 /* Insert the varinfo FIELD into the field list for BASE, ordered by
2511    offset.  */
2512
2513 static void
2514 insert_into_field_list (varinfo_t base, varinfo_t field)
2515 {
2516   varinfo_t prev = base;
2517   varinfo_t curr = base->next;
2518   
2519   if (curr == NULL)
2520     {
2521       prev->next = field;
2522       field->next = NULL;
2523     }
2524   else
2525     {
2526       while (curr)
2527         {
2528           if (field->offset <= curr->offset)
2529             break;
2530           prev = curr;
2531           curr = curr->next;
2532         }
2533       field->next = prev->next;
2534       prev->next = field;
2535     }
2536 }
2537
2538 /* qsort comparison function for two fieldoff's PA and PB */
2539
2540 static int 
2541 fieldoff_compare (const void *pa, const void *pb)
2542 {
2543   const fieldoff_s *foa = (const fieldoff_s *)pa;
2544   const fieldoff_s *fob = (const fieldoff_s *)pb;
2545   HOST_WIDE_INT foasize, fobsize;
2546   
2547   if (foa->offset != fob->offset)
2548     return foa->offset - fob->offset;
2549
2550   foasize = TREE_INT_CST_LOW (DECL_SIZE (foa->field));
2551   fobsize = TREE_INT_CST_LOW (DECL_SIZE (fob->field));
2552   return foasize - fobsize;
2553 }
2554
2555 /* Sort a fieldstack according to the field offset and sizes.  */
2556 void sort_fieldstack (VEC(fieldoff_s,heap) *fieldstack)
2557 {
2558   qsort (VEC_address (fieldoff_s, fieldstack), 
2559          VEC_length (fieldoff_s, fieldstack), 
2560          sizeof (fieldoff_s),
2561          fieldoff_compare);
2562 }
2563
2564 /* Given a TYPE, and a vector of field offsets FIELDSTACK, push all the fields
2565    of TYPE onto fieldstack, recording their offsets along the way.
2566    OFFSET is used to keep track of the offset in this entire structure, rather
2567    than just the immediately containing structure.  Returns the number
2568    of fields pushed.
2569    HAS_UNION is set to true if we find a union type as a field of
2570    TYPE.  */
2571
2572 int
2573 push_fields_onto_fieldstack (tree type, VEC(fieldoff_s,heap) **fieldstack, 
2574                              HOST_WIDE_INT offset, bool *has_union)
2575 {
2576   tree field;
2577   int count = 0;
2578
2579   for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
2580     if (TREE_CODE (field) == FIELD_DECL)
2581       {
2582         bool push = false;
2583         
2584         if (has_union 
2585             && (TREE_CODE (TREE_TYPE (field)) == QUAL_UNION_TYPE
2586                 || TREE_CODE (TREE_TYPE (field)) == UNION_TYPE))
2587           *has_union = true;
2588         
2589         if (!var_can_have_subvars (field))
2590           push = true;
2591         else if (!(push_fields_onto_fieldstack
2592                    (TREE_TYPE (field), fieldstack,
2593                     offset + bitpos_of_field (field), has_union))
2594                  && DECL_SIZE (field)
2595                  && !integer_zerop (DECL_SIZE (field)))
2596           /* Empty structures may have actual size, like in C++. So
2597              see if we didn't push any subfields and the size is
2598              nonzero, push the field onto the stack */
2599           push = true;
2600         
2601         if (push)
2602           {
2603             fieldoff_s *pair;
2604
2605             pair = VEC_safe_push (fieldoff_s, heap, *fieldstack, NULL);
2606             pair->field = field;
2607             pair->offset = offset + bitpos_of_field (field);
2608             count++;
2609           }
2610       }
2611
2612   return count;
2613 }
2614
2615 static void
2616 make_constraint_to_anything (varinfo_t vi)
2617 {
2618   struct constraint_expr lhs, rhs;
2619   
2620   lhs.var = vi->id;
2621   lhs.offset = 0;
2622   lhs.type = SCALAR;
2623   
2624   rhs.var = anything_id;
2625   rhs.offset =0 ;
2626   rhs.type = ADDRESSOF;
2627   process_constraint (new_constraint (lhs, rhs));
2628 }
2629
2630 /* Create a varinfo structure for NAME and DECL, and add it to VARMAP.
2631    This will also create any varinfo structures necessary for fields
2632    of DECL.  */
2633
2634 static unsigned int
2635 create_variable_info_for (tree decl, const char *name)
2636 {
2637   unsigned int index = VEC_length (varinfo_t, varmap);
2638   varinfo_t vi;
2639   tree decltype = TREE_TYPE (decl);
2640   bool notokay = false;
2641   subvar_t svars;
2642   bool is_global = DECL_P (decl) ? is_global_var (decl) : false;
2643
2644   VEC (fieldoff_s,heap) *fieldstack = NULL;
2645   
2646   if (var_can_have_subvars (decl) && use_field_sensitive)
2647     {
2648       push_fields_onto_fieldstack (decltype, &fieldstack, 0, &notokay);
2649       if (notokay)
2650         VEC_free (fieldoff_s, heap, fieldstack);
2651     }
2652
2653   /* If this variable already has subvars, just create the variables for the
2654      subvars and we are done.
2655      NOTE: This assumes things haven't generated uses of previously
2656      unused structure fields.  */
2657   if (use_field_sensitive 
2658       && !notokay 
2659       && var_can_have_subvars (decl) 
2660       && var_ann (decl)      
2661       && (svars = get_subvars_for_var (decl)))
2662     {
2663       subvar_t sv;
2664       varinfo_t base = NULL;
2665       unsigned int firstindex = index;
2666
2667       for (sv = svars; sv; sv = sv->next)
2668         {
2669           /* For debugging purposes, this will print the names of the
2670              fields as "<var>.<offset>.<size>"
2671              This is only for debugging purposes.  */
2672 #define PRINT_LONG_NAMES
2673 #ifdef PRINT_LONG_NAMES
2674           char *tempname;
2675           const char *newname;
2676
2677           asprintf (&tempname,
2678                     "%s." HOST_WIDE_INT_PRINT_DEC "." HOST_WIDE_INT_PRINT_DEC,
2679                     alias_get_name (decl), sv->offset, sv->size);
2680           newname = ggc_strdup (tempname);
2681           free (tempname);
2682           vi = new_var_info (sv->var, index, newname, index);
2683 #else
2684           vi = new_var_info (sv->var, index, alias_get_name (sv->var), index);
2685 #endif
2686           vi->decl = sv->var;
2687           vi->fullsize = TREE_INT_CST_LOW (TYPE_SIZE (decltype));
2688           vi->size = sv->size;
2689           vi->offset = sv->offset;
2690           if (!base)
2691             {
2692               base = vi;
2693               insert_id_for_tree (decl, index);
2694             }
2695           else
2696             {
2697               insert_into_field_list (base, vi);
2698             }
2699           insert_id_for_tree (sv->var, index);  
2700           VEC_safe_push (varinfo_t, gc, varmap, vi);
2701           if (is_global)
2702             make_constraint_to_anything (vi);
2703           index++;
2704           
2705         }
2706       return firstindex;
2707     }
2708   
2709
2710   /* If the variable doesn't have subvars, we may end up needing to
2711      sort the field list and create fake variables for all the
2712      fields.  */
2713   vi = new_var_info (decl, index, name, index);
2714   vi->decl = decl;
2715   vi->offset = 0;
2716   if (!TYPE_SIZE (decltype) 
2717       || TREE_CODE (TYPE_SIZE  (decltype)) != INTEGER_CST
2718       || TREE_CODE (decltype) == ARRAY_TYPE
2719       || TREE_CODE (decltype) == UNION_TYPE
2720       || TREE_CODE (decltype) == QUAL_UNION_TYPE)
2721     {
2722       vi->is_unknown_size_var = true;
2723       vi->fullsize = ~0;
2724       vi->size = ~0;
2725     }
2726   else
2727     {
2728       vi->fullsize = TREE_INT_CST_LOW (TYPE_SIZE (decltype));
2729       vi->size = vi->fullsize;
2730     }
2731   
2732   insert_id_for_tree (vi->decl, index);  
2733   VEC_safe_push (varinfo_t, gc, varmap, vi);
2734   if (is_global)
2735     make_constraint_to_anything (vi);
2736
2737   stats.total_vars++;
2738   if (use_field_sensitive 
2739       && !notokay 
2740       && !vi->is_unknown_size_var 
2741       && var_can_have_subvars (decl))
2742     {
2743       unsigned int newindex = VEC_length (varinfo_t, varmap);
2744       fieldoff_s *fo = NULL;
2745       unsigned int i;
2746       tree field;
2747
2748       for (i = 0; !notokay && VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
2749         {
2750           if (!DECL_SIZE (fo->field) 
2751               || TREE_CODE (DECL_SIZE (fo->field)) != INTEGER_CST
2752               || TREE_CODE (TREE_TYPE (fo->field)) == ARRAY_TYPE
2753               || fo->offset < 0)
2754             {
2755               notokay = true;
2756               break;
2757             }
2758         }
2759       sort_fieldstack (fieldstack);
2760       
2761       if (VEC_length (fieldoff_s, fieldstack) != 0)
2762         fo = VEC_index (fieldoff_s, fieldstack, 0);
2763
2764       if (fo == NULL || notokay)
2765         {
2766           vi->is_unknown_size_var = 1;
2767           vi->fullsize = ~0;
2768           vi->size = ~0;
2769           VEC_free (fieldoff_s, heap, fieldstack);
2770           return index;
2771         }
2772       
2773       field = fo->field;
2774       gcc_assert (bitpos_of_field (field) == 0);
2775       vi->size = TREE_INT_CST_LOW (DECL_SIZE (field));
2776       for (i = 1; VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
2777         {
2778           varinfo_t newvi;
2779           const char *newname;
2780           char *tempname;
2781
2782           field = fo->field;
2783           newindex = VEC_length (varinfo_t, varmap);
2784           asprintf (&tempname, "%s.%s", vi->name, alias_get_name (field));
2785           newname = ggc_strdup (tempname);
2786           free (tempname);
2787           newvi = new_var_info (decl, newindex, newname, newindex);
2788           newvi->offset = fo->offset;
2789           newvi->size = TREE_INT_CST_LOW (DECL_SIZE (field));
2790           newvi->fullsize = vi->fullsize;
2791           insert_into_field_list (vi, newvi);
2792           VEC_safe_push (varinfo_t, gc, varmap, newvi);
2793           if (is_global)
2794             make_constraint_to_anything (newvi);
2795
2796           stats.total_vars++;     
2797         }
2798       VEC_free (fieldoff_s, heap, fieldstack);
2799     }
2800   return index;
2801 }
2802
2803 /* Print out the points-to solution for VAR to FILE.  */
2804
2805 void
2806 dump_solution_for_var (FILE *file, unsigned int var)
2807 {
2808   varinfo_t vi = get_varinfo (var);
2809   unsigned int i;
2810   bitmap_iterator bi; 
2811   
2812   fprintf (file, "%s = {", vi->name);
2813   EXECUTE_IF_SET_IN_BITMAP (get_varinfo (vi->node)->solution, 0, i, bi)
2814     {
2815       fprintf (file, "%s,", get_varinfo (i)->name);
2816     }
2817   fprintf (file, "}\n");
2818 }
2819
2820 /* Print the points-to solution for VAR to stdout.  */
2821
2822 void
2823 debug_solution_for_var (unsigned int var)
2824 {
2825   dump_solution_for_var (stdout, var);
2826 }
2827
2828
2829 /* Create varinfo structures for all of the variables in the
2830    function for intraprocedural mode.  */
2831
2832 static void
2833 intra_create_variable_infos (void)
2834 {
2835   tree t;
2836
2837   /* For each incoming argument arg, ARG = &ANYTHING */
2838   for (t = DECL_ARGUMENTS (current_function_decl); t; t = TREE_CHAIN (t))
2839     {
2840       struct constraint_expr lhs;
2841       struct constraint_expr rhs;
2842       varinfo_t p;
2843       
2844       lhs.offset = 0;
2845       lhs.type = SCALAR;
2846       lhs.var  = create_variable_info_for (t, alias_get_name (t));
2847       
2848       get_varinfo (lhs.var)->is_artificial_var = true;
2849       rhs.var = anything_id;
2850       rhs.type = ADDRESSOF;
2851       rhs.offset = 0;
2852
2853       for (p = get_varinfo (lhs.var); p; p = p->next)
2854         {
2855           struct constraint_expr temp = lhs;
2856           temp.var = p->id;
2857           process_constraint (new_constraint (temp, rhs));
2858         }
2859     }   
2860
2861 }
2862
2863 /* Set bits in INTO corresponding to the variable uids in solution set
2864    FROM  */
2865
2866 static void
2867 set_uids_in_ptset (bitmap into, bitmap from)
2868 {
2869   unsigned int i;
2870   bitmap_iterator bi;
2871
2872   EXECUTE_IF_SET_IN_BITMAP (from, 0, i, bi)
2873     {
2874       varinfo_t vi = get_varinfo (i);
2875
2876       /* We may end up with labels in the points-to set because people
2877          take their address, and they are _DECL's.  */
2878       if (TREE_CODE (vi->decl) == VAR_DECL 
2879           || TREE_CODE (vi->decl) == PARM_DECL)
2880         bitmap_set_bit (into, var_ann (vi->decl)->uid);
2881     }
2882 }
2883 static int have_alias_info = false;
2884
2885 /* Given a pointer variable P, fill in its points-to set, or return
2886    false if we can't.  */
2887
2888 bool
2889 find_what_p_points_to (tree p)
2890 {
2891   unsigned int id = 0;
2892   if (!have_alias_info)
2893     return false;
2894   if (lookup_id_for_tree (p, &id))
2895     {
2896       varinfo_t vi = get_varinfo (id);
2897       
2898       if (vi->is_artificial_var)
2899         return false;
2900
2901       /* See if this is a field or a structure */
2902       if (vi->size != vi->fullsize)
2903         {
2904           if (!var_can_have_subvars (vi->decl)
2905               || get_subvars_for_var (vi->decl) == NULL)
2906             return false;
2907         } 
2908       else
2909         {
2910           struct ptr_info_def *pi = get_ptr_info (p);
2911           unsigned int i;
2912           bitmap_iterator bi;
2913
2914           /* This variable may have been collapsed, let's get the real
2915              variable.  */
2916           vi = get_varinfo (vi->node);
2917           
2918           /* Make sure there aren't any artificial vars in the points
2919              to set.  XXX: Note that we need to translate our heap
2920              variables to something.  */ 
2921           EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
2922             {
2923               if (get_varinfo (i)->is_artificial_var)
2924                 return false;
2925             }
2926           pi->pt_anything = false;
2927           if (!pi->pt_vars)
2928             pi->pt_vars = BITMAP_GGC_ALLOC ();
2929           set_uids_in_ptset (pi->pt_vars, vi->solution);
2930           return true;
2931         }
2932     }
2933   return false;
2934 }
2935
2936 /* Initialize things necessary to perform PTA */
2937
2938 static void
2939 init_alias_vars (void)
2940 {
2941   bitmap_obstack_initialize (&ptabitmap_obstack);
2942 }
2943
2944 /* Dump the points-to information to OUTFILE.  */
2945
2946 static void
2947 dump_sa_points_to_info (FILE *outfile)
2948 {
2949   
2950   unsigned int i;
2951   if (dump_flags & TDF_STATS)
2952     {
2953       fprintf (outfile, "Stats:\n");
2954       fprintf (outfile, "Total vars:%d\n", stats.total_vars);
2955       fprintf (outfile, "Statically unified vars:%d\n", stats.unified_vars_static);
2956       fprintf (outfile, "Collapsed vars:%d\n", stats.collapsed_vars);
2957       fprintf (outfile, "Dynamically unified vars:%d\n", stats.unified_vars_dynamic);
2958       fprintf (outfile, "Iterations:%d\n", stats.iterations);
2959     }
2960   for (i = 0; i < VEC_length (varinfo_t, varmap); i++)
2961     dump_solution_for_var (outfile, i);
2962 }
2963
2964
2965 /* Initialize the always-existing constraint variables for NULL
2966    ANYTHING, READONLY, and INTEGER */
2967
2968 static void
2969 init_base_vars (void)
2970 {
2971   struct constraint_expr lhs, rhs;
2972
2973   /* Create the NULL variable, used to represent that a variable points
2974      to NULL.  */
2975   nothing_tree = create_tmp_var_raw (void_type_node, "NULL");
2976   var_nothing = new_var_info (nothing_tree, 0, "NULL", 0);
2977   insert_id_for_tree (nothing_tree, 0);
2978   var_nothing->is_artificial_var = 1;
2979   var_nothing->offset = 0;
2980   var_nothing->size = ~0;
2981   var_nothing->fullsize = ~0;
2982   nothing_id = 0;
2983   VEC_safe_push (varinfo_t, gc, varmap, var_nothing);
2984
2985   /* Create the ANYTHING variable, used to represent that a variable
2986      points to some unknown piece of memory.  */
2987   anything_tree = create_tmp_var_raw (void_type_node, "ANYTHING");
2988   var_anything = new_var_info (anything_tree, 1, "ANYTHING", 1); 
2989   insert_id_for_tree (anything_tree, 1);
2990   var_anything->is_artificial_var = 1;
2991   var_anything->size = ~0;
2992   var_anything->offset = 0;
2993   var_anything->next = NULL;
2994   var_anything->fullsize = ~0;
2995   anything_id = 1;
2996
2997   /* Anything points to anything.  This makes deref constraints just
2998      work in the presence of linked list and other p = *p type loops, 
2999      by saying that *ANYTHING = ANYTHING. */
3000   VEC_safe_push (varinfo_t, gc, varmap, var_anything);
3001   lhs.type = SCALAR;
3002   lhs.var = anything_id;
3003   lhs.offset = 0;
3004   rhs.type = ADDRESSOF;
3005   rhs.var = anything_id;
3006   rhs.offset = 0;
3007   var_anything->address_taken = true;
3008   process_constraint (new_constraint (lhs, rhs));
3009
3010   
3011   /* Create the READONLY variable, used to represent that a variable
3012      points to readonly memory.  */
3013   readonly_tree = create_tmp_var_raw (void_type_node, "READONLY");
3014   var_readonly = new_var_info (readonly_tree, 2, "READONLY", 2);
3015   var_readonly->is_artificial_var = 1;
3016   var_readonly->offset = 0;
3017   var_readonly->size = ~0;
3018   var_readonly->fullsize = ~0;
3019   var_readonly->next = NULL;
3020   insert_id_for_tree (readonly_tree, 2);
3021   readonly_id = 2;
3022   VEC_safe_push (varinfo_t, gc, varmap, var_readonly);
3023
3024   /* readonly memory points to anything, in order to make deref
3025      easier.  In reality, it points to anything the particular
3026      readonly variable can point to, but we don't track this
3027      seperately. */
3028   lhs.type = SCALAR;
3029   lhs.var = readonly_id;
3030   lhs.offset = 0;
3031   rhs.type = ADDRESSOF;
3032   rhs.var = anything_id;
3033   rhs.offset = 0;
3034   var_readonly->address_taken = true;
3035   
3036   process_constraint (new_constraint (lhs, rhs));
3037   
3038   /* Create the INTEGER variable, used to represent that a variable points
3039      to an INTEGER.  */
3040   integer_tree = create_tmp_var_raw (void_type_node, "INTEGER");
3041   var_integer = new_var_info (integer_tree, 3, "INTEGER", 3);
3042   insert_id_for_tree (integer_tree, 3);
3043   var_integer->is_artificial_var = 1;
3044   var_integer->size = ~0;
3045   var_integer->fullsize = ~0;
3046   var_integer->offset = 0;
3047   var_integer->next = NULL;
3048   integer_id = 3;
3049   VEC_safe_push (varinfo_t, gc, varmap, var_integer);
3050 }  
3051
3052
3053 /* Create points-to sets for the current function.  See the comments
3054    at the start of the file for an algorithmic overview.  */
3055
3056 static void
3057 create_alias_vars (void)
3058 {
3059   basic_block bb;
3060
3061   
3062   init_alias_vars ();
3063
3064   constraint_pool = create_alloc_pool ("Constraint pool", 
3065                                        sizeof (struct constraint), 30);
3066   variable_info_pool = create_alloc_pool ("Variable info pool",
3067                                           sizeof (struct variable_info), 30);
3068   constraint_edge_pool = create_alloc_pool ("Constraint edges",
3069                                             sizeof (struct constraint_edge), 30);
3070   
3071   constraints = VEC_alloc (constraint_t, gc, 8);
3072   varmap = VEC_alloc (varinfo_t, gc, 8);
3073   id_for_tree = htab_create (10, tree_id_hash, tree_id_eq, free);
3074   memset (&stats, 0, sizeof (stats));
3075   
3076   init_base_vars ();
3077
3078   intra_create_variable_infos ();
3079
3080   /* Now walk all statements and derive aliases.  */
3081   FOR_EACH_BB (bb)
3082     {
3083       block_stmt_iterator bsi; 
3084       tree phi;
3085
3086       for (phi = phi_nodes (bb); phi; phi = TREE_CHAIN (phi))
3087         if (is_gimple_reg (PHI_RESULT (phi)))
3088           find_func_aliases (phi);
3089
3090       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
3091         find_func_aliases (bsi_stmt (bsi));
3092     }
3093
3094   build_constraint_graph ();
3095
3096   if (dump_file)
3097     {
3098       fprintf (dump_file, "Constraints:\n");
3099       dump_constraints (dump_file);
3100     }
3101
3102   if (dump_file)
3103     fprintf (dump_file, "Collapsing static cycles and doing variable substitution:\n");
3104
3105   find_and_collapse_graph_cycles (graph, false);
3106   perform_var_substitution (graph);
3107
3108   if (dump_file)
3109     fprintf (dump_file, "Solving graph:\n");
3110
3111   solve_graph (graph);
3112
3113   if (dump_file)
3114     dump_sa_points_to_info (dump_file);
3115   
3116   have_alias_info = true;
3117 }
3118
3119 struct tree_opt_pass pass_build_pta = 
3120 {
3121   "pta",                                /* name */
3122   NULL,                                 /* gate */
3123   create_alias_vars,                    /* execute */
3124   NULL,                                 /* sub */
3125   NULL,                                 /* next */
3126   0,                                    /* static_pass_number */
3127   TV_TREE_PTA,                          /* tv_id */
3128   PROP_cfg,                             /* properties_required */
3129   PROP_pta,                             /* properties_provided */
3130   0,                                    /* properties_destroyed */
3131   0,                                    /* todo_flags_start */
3132   0,                                    /* todo_flags_finish */
3133   0                                     /* letter */
3134 };
3135  
3136
3137 /* Delete created points-to sets.  */
3138
3139 static void
3140 delete_alias_vars (void)
3141 {
3142   htab_delete (id_for_tree);
3143   free_alloc_pool (variable_info_pool);
3144   free_alloc_pool (constraint_pool); 
3145   free_alloc_pool (constraint_edge_pool);
3146   bitmap_obstack_release (&ptabitmap_obstack);
3147   have_alias_info = false;
3148 }
3149
3150 struct tree_opt_pass pass_del_pta = 
3151 {
3152   NULL,                                 /* name */
3153   NULL,                                 /* gate */
3154   delete_alias_vars,                    /* execute */
3155   NULL,                                 /* sub */
3156   NULL,                                 /* next */
3157   0,                                    /* static_pass_number */
3158   TV_TREE_PTA,                          /* tv_id */
3159   PROP_pta,                             /* properties_required */
3160   0,                                    /* properties_provided */
3161   PROP_pta,                             /* properties_destroyed */
3162   0,                                    /* todo_flags_start */
3163   0,                                    /* todo_flags_finish */
3164   0                                     /* letter */
3165 };