OSDN Git Service

- fix whitespace in laste gcc/ChangeLog entry
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-structalias.c
1 /* Tree based points-to analysis
2    Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010
3    Free Software Foundation, Inc.
4    Contributed by Daniel Berlin <dberlin@dberlin.org>
5
6    This file is part of GCC.
7
8    GCC is free software; you can redistribute it and/or modify
9    under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    GCC is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with GCC; see the file COPYING3.  If not see
20    <http://www.gnu.org/licenses/>.  */
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 "flags.h"
30 #include "basic-block.h"
31 #include "output.h"
32 #include "tree.h"
33 #include "tree-flow.h"
34 #include "tree-inline.h"
35 #include "diagnostic-core.h"
36 #include "gimple.h"
37 #include "hashtab.h"
38 #include "function.h"
39 #include "cgraph.h"
40 #include "tree-pass.h"
41 #include "timevar.h"
42 #include "alloc-pool.h"
43 #include "splay-tree.h"
44 #include "params.h"
45 #include "cgraph.h"
46 #include "alias.h"
47 #include "pointer-set.h"
48
49 /* The idea behind this analyzer is to generate set constraints from the
50    program, then solve the resulting constraints in order to generate the
51    points-to sets.
52
53    Set constraints are a way of modeling program analysis problems that
54    involve sets.  They consist of an inclusion constraint language,
55    describing the variables (each variable is a set) and operations that
56    are involved on the variables, and a set of rules that derive facts
57    from these operations.  To solve a system of set constraints, you derive
58    all possible facts under the rules, which gives you the correct sets
59    as a consequence.
60
61    See  "Efficient Field-sensitive pointer analysis for C" by "David
62    J. Pearce and Paul H. J. Kelly and Chris Hankin, at
63    http://citeseer.ist.psu.edu/pearce04efficient.html
64
65    Also see "Ultra-fast Aliasing Analysis using CLA: A Million Lines
66    of C Code in a Second" by ""Nevin Heintze and Olivier Tardieu" at
67    http://citeseer.ist.psu.edu/heintze01ultrafast.html
68
69    There are three types of real constraint expressions, DEREF,
70    ADDRESSOF, and SCALAR.  Each constraint expression consists
71    of a constraint type, a variable, and an offset.
72
73    SCALAR is a constraint expression type used to represent x, whether
74    it appears on the LHS or the RHS of a statement.
75    DEREF is a constraint expression type used to represent *x, whether
76    it appears on the LHS or the RHS of a statement.
77    ADDRESSOF is a constraint expression used to represent &x, whether
78    it appears on the LHS or the RHS of a statement.
79
80    Each pointer variable in the program is assigned an integer id, and
81    each field of a structure variable is assigned an integer id as well.
82
83    Structure variables are linked to their list of fields through a "next
84    field" in each variable that points to the next field in offset
85    order.
86    Each variable for a structure field has
87
88    1. "size", that tells the size in bits of that field.
89    2. "fullsize, that tells the size in bits of the entire structure.
90    3. "offset", that tells the offset in bits from the beginning of the
91    structure to this field.
92
93    Thus,
94    struct f
95    {
96      int a;
97      int b;
98    } foo;
99    int *bar;
100
101    looks like
102
103    foo.a -> id 1, size 32, offset 0, fullsize 64, next foo.b
104    foo.b -> id 2, size 32, offset 32, fullsize 64, next NULL
105    bar -> id 3, size 32, offset 0, fullsize 32, next NULL
106
107
108   In order to solve the system of set constraints, the following is
109   done:
110
111   1. Each constraint variable x has a solution set associated with it,
112   Sol(x).
113
114   2. Constraints are separated into direct, copy, and complex.
115   Direct constraints are ADDRESSOF constraints that require no extra
116   processing, such as P = &Q
117   Copy constraints are those of the form P = Q.
118   Complex constraints are all the constraints involving dereferences
119   and offsets (including offsetted copies).
120
121   3. All direct constraints of the form P = &Q are processed, such
122   that Q is added to Sol(P)
123
124   4. All complex constraints for a given constraint variable are stored in a
125   linked list attached to that variable's node.
126
127   5. A directed graph is built out of the copy constraints. Each
128   constraint variable is a node in the graph, and an edge from
129   Q to P is added for each copy constraint of the form P = Q
130
131   6. The graph is then walked, and solution sets are
132   propagated along the copy edges, such that an edge from Q to P
133   causes Sol(P) <- Sol(P) union Sol(Q).
134
135   7.  As we visit each node, all complex constraints associated with
136   that node are processed by adding appropriate copy edges to the graph, or the
137   appropriate variables to the solution set.
138
139   8. The process of walking the graph is iterated until no solution
140   sets change.
141
142   Prior to walking the graph in steps 6 and 7, We perform static
143   cycle elimination on the constraint graph, as well
144   as off-line variable substitution.
145
146   TODO: Adding offsets to pointer-to-structures can be handled (IE not punted
147   on and turned into anything), but isn't.  You can just see what offset
148   inside the pointed-to struct it's going to access.
149
150   TODO: Constant bounded arrays can be handled as if they were structs of the
151   same number of elements.
152
153   TODO: Modeling heap and incoming pointers becomes much better if we
154   add fields to them as we discover them, which we could do.
155
156   TODO: We could handle unions, but to be honest, it's probably not
157   worth the pain or slowdown.  */
158
159 /* IPA-PTA optimizations possible.
160
161    When the indirect function called is ANYTHING we can add disambiguation
162    based on the function signatures (or simply the parameter count which
163    is the varinfo size).  We also do not need to consider functions that
164    do not have their address taken.
165
166    The is_global_var bit which marks escape points is overly conservative
167    in IPA mode.  Split it to is_escape_point and is_global_var - only
168    externally visible globals are escape points in IPA mode.  This is
169    also needed to fix the pt_solution_includes_global predicate
170    (and thus ptr_deref_may_alias_global_p).
171
172    The way we introduce DECL_PT_UID to avoid fixing up all points-to
173    sets in the translation unit when we copy a DECL during inlining
174    pessimizes precision.  The advantage is that the DECL_PT_UID keeps
175    compile-time and memory usage overhead low - the points-to sets
176    do not grow or get unshared as they would during a fixup phase.
177    An alternative solution is to delay IPA PTA until after all
178    inlining transformations have been applied.
179
180    The way we propagate clobber/use information isn't optimized.
181    It should use a new complex constraint that properly filters
182    out local variables of the callee (though that would make
183    the sets invalid after inlining).  OTOH we might as well
184    admit defeat to WHOPR and simply do all the clobber/use analysis
185    and propagation after PTA finished but before we threw away
186    points-to information for memory variables.  WHOPR and PTA
187    do not play along well anyway - the whole constraint solving
188    would need to be done in WPA phase and it will be very interesting
189    to apply the results to local SSA names during LTRANS phase.
190
191    We probably should compute a per-function unit-ESCAPE solution
192    propagating it simply like the clobber / uses solutions.  The
193    solution can go alongside the non-IPA espaced solution and be
194    used to query which vars escape the unit through a function.
195
196    We never put function decls in points-to sets so we do not
197    keep the set of called functions for indirect calls.
198
199    And probably more.  */
200 static GTY ((if_marked ("tree_map_marked_p"), param_is (struct heapvar_map)))
201 htab_t heapvar_for_stmt;
202
203 static bool use_field_sensitive = true;
204 static int in_ipa_mode = 0;
205
206 /* Used for predecessor bitmaps. */
207 static bitmap_obstack predbitmap_obstack;
208
209 /* Used for points-to sets.  */
210 static bitmap_obstack pta_obstack;
211
212 /* Used for oldsolution members of variables. */
213 static bitmap_obstack oldpta_obstack;
214
215 /* Used for per-solver-iteration bitmaps.  */
216 static bitmap_obstack iteration_obstack;
217
218 static unsigned int create_variable_info_for (tree, const char *);
219 typedef struct constraint_graph *constraint_graph_t;
220 static void unify_nodes (constraint_graph_t, unsigned int, unsigned int, bool);
221
222 struct constraint;
223 typedef struct constraint *constraint_t;
224
225 DEF_VEC_P(constraint_t);
226 DEF_VEC_ALLOC_P(constraint_t,heap);
227
228 #define EXECUTE_IF_IN_NONNULL_BITMAP(a, b, c, d)        \
229   if (a)                                                \
230     EXECUTE_IF_SET_IN_BITMAP (a, b, c, d)
231
232 static struct constraint_stats
233 {
234   unsigned int total_vars;
235   unsigned int nonpointer_vars;
236   unsigned int unified_vars_static;
237   unsigned int unified_vars_dynamic;
238   unsigned int iterations;
239   unsigned int num_edges;
240   unsigned int num_implicit_edges;
241   unsigned int points_to_sets_created;
242 } stats;
243
244 struct variable_info
245 {
246   /* ID of this variable  */
247   unsigned int id;
248
249   /* True if this is a variable created by the constraint analysis, such as
250      heap variables and constraints we had to break up.  */
251   unsigned int is_artificial_var : 1;
252
253   /* True if this is a special variable whose solution set should not be
254      changed.  */
255   unsigned int is_special_var : 1;
256
257   /* True for variables whose size is not known or variable.  */
258   unsigned int is_unknown_size_var : 1;
259
260   /* True for (sub-)fields that represent a whole variable.  */
261   unsigned int is_full_var : 1;
262
263   /* True if this is a heap variable.  */
264   unsigned int is_heap_var : 1;
265
266   /* True if this is a variable tracking a restrict pointer source.  */
267   unsigned int is_restrict_var : 1;
268
269   /* True if this field may contain pointers.  */
270   unsigned int may_have_pointers : 1;
271
272   /* True if this field has only restrict qualified pointers.  */
273   unsigned int only_restrict_pointers : 1;
274
275   /* True if this represents a global variable.  */
276   unsigned int is_global_var : 1;
277
278   /* True if this represents a IPA function info.  */
279   unsigned int is_fn_info : 1;
280
281   /* A link to the variable for the next field in this structure.  */
282   struct variable_info *next;
283
284   /* Offset of this variable, in bits, from the base variable  */
285   unsigned HOST_WIDE_INT offset;
286
287   /* Size of the variable, in bits.  */
288   unsigned HOST_WIDE_INT size;
289
290   /* Full size of the base variable, in bits.  */
291   unsigned HOST_WIDE_INT fullsize;
292
293   /* Name of this variable */
294   const char *name;
295
296   /* Tree that this variable is associated with.  */
297   tree decl;
298
299   /* Points-to set for this variable.  */
300   bitmap solution;
301
302   /* Old points-to set for this variable.  */
303   bitmap oldsolution;
304 };
305 typedef struct variable_info *varinfo_t;
306
307 static varinfo_t first_vi_for_offset (varinfo_t, unsigned HOST_WIDE_INT);
308 static varinfo_t first_or_preceding_vi_for_offset (varinfo_t,
309                                                    unsigned HOST_WIDE_INT);
310 static varinfo_t lookup_vi_for_tree (tree);
311 static inline bool type_can_have_subvars (const_tree);
312
313 /* Pool of variable info structures.  */
314 static alloc_pool variable_info_pool;
315
316 DEF_VEC_P(varinfo_t);
317
318 DEF_VEC_ALLOC_P(varinfo_t, heap);
319
320 /* Table of variable info structures for constraint variables.
321    Indexed directly by variable info id.  */
322 static VEC(varinfo_t,heap) *varmap;
323
324 /* Return the varmap element N */
325
326 static inline varinfo_t
327 get_varinfo (unsigned int n)
328 {
329   return VEC_index (varinfo_t, varmap, n);
330 }
331
332 /* Static IDs for the special variables.  */
333 enum { nothing_id = 0, anything_id = 1, readonly_id = 2,
334        escaped_id = 3, nonlocal_id = 4,
335        storedanything_id = 5, integer_id = 6 };
336
337 struct GTY(()) heapvar_map {
338   struct tree_map map;
339   unsigned HOST_WIDE_INT offset;
340 };
341
342 static int
343 heapvar_map_eq (const void *p1, const void *p2)
344 {
345   const struct heapvar_map *h1 = (const struct heapvar_map *)p1;
346   const struct heapvar_map *h2 = (const struct heapvar_map *)p2;
347   return (h1->map.base.from == h2->map.base.from
348           && h1->offset == h2->offset);
349 }
350
351 static unsigned int
352 heapvar_map_hash (struct heapvar_map *h)
353 {
354   return iterative_hash_host_wide_int (h->offset,
355                                        htab_hash_pointer (h->map.base.from));
356 }
357
358 /* Lookup a heap var for FROM, and return it if we find one.  */
359
360 static tree
361 heapvar_lookup (tree from, unsigned HOST_WIDE_INT offset)
362 {
363   struct heapvar_map *h, in;
364   in.map.base.from = from;
365   in.offset = offset;
366   h = (struct heapvar_map *) htab_find_with_hash (heapvar_for_stmt, &in,
367                                                   heapvar_map_hash (&in));
368   if (h)
369     return h->map.to;
370   return NULL_TREE;
371 }
372
373 /* Insert a mapping FROM->TO in the heap var for statement
374    hashtable.  */
375
376 static void
377 heapvar_insert (tree from, unsigned HOST_WIDE_INT offset, tree to)
378 {
379   struct heapvar_map *h;
380   void **loc;
381
382   h = ggc_alloc_heapvar_map ();
383   h->map.base.from = from;
384   h->offset = offset;
385   h->map.hash = heapvar_map_hash (h);
386   h->map.to = to;
387   loc = htab_find_slot_with_hash (heapvar_for_stmt, h, h->map.hash, INSERT);
388   gcc_assert (*loc == NULL);
389   *(struct heapvar_map **) loc = h;
390 }
391
392 /* Return a new variable info structure consisting for a variable
393    named NAME, and using constraint graph node NODE.  Append it
394    to the vector of variable info structures.  */
395
396 static varinfo_t
397 new_var_info (tree t, const char *name)
398 {
399   unsigned index = VEC_length (varinfo_t, varmap);
400   varinfo_t ret = (varinfo_t) pool_alloc (variable_info_pool);
401
402   ret->id = index;
403   ret->name = name;
404   ret->decl = t;
405   /* Vars without decl are artificial and do not have sub-variables.  */
406   ret->is_artificial_var = (t == NULL_TREE);
407   ret->is_special_var = false;
408   ret->is_unknown_size_var = false;
409   ret->is_full_var = (t == NULL_TREE);
410   ret->is_heap_var = false;
411   ret->is_restrict_var = false;
412   ret->may_have_pointers = true;
413   ret->only_restrict_pointers = false;
414   ret->is_global_var = (t == NULL_TREE);
415   ret->is_fn_info = false;
416   if (t && DECL_P (t))
417     ret->is_global_var = (is_global_var (t)
418                           /* We have to treat even local register variables
419                              as escape points.  */
420                           || (TREE_CODE (t) == VAR_DECL
421                               && DECL_HARD_REGISTER (t)));
422   ret->solution = BITMAP_ALLOC (&pta_obstack);
423   ret->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
424   ret->next = NULL;
425
426   stats.total_vars++;
427
428   VEC_safe_push (varinfo_t, heap, varmap, ret);
429
430   return ret;
431 }
432
433
434 /* A map mapping call statements to per-stmt variables for uses
435    and clobbers specific to the call.  */
436 struct pointer_map_t *call_stmt_vars;
437
438 /* Lookup or create the variable for the call statement CALL.  */
439
440 static varinfo_t
441 get_call_vi (gimple call)
442 {
443   void **slot_p;
444   varinfo_t vi, vi2;
445
446   slot_p = pointer_map_insert (call_stmt_vars, call);
447   if (*slot_p)
448     return (varinfo_t) *slot_p;
449
450   vi = new_var_info (NULL_TREE, "CALLUSED");
451   vi->offset = 0;
452   vi->size = 1;
453   vi->fullsize = 2;
454   vi->is_full_var = true;
455
456   vi->next = vi2 = new_var_info (NULL_TREE, "CALLCLOBBERED");
457   vi2->offset = 1;
458   vi2->size = 1;
459   vi2->fullsize = 2;
460   vi2->is_full_var = true;
461
462   *slot_p = (void *) vi;
463   return vi;
464 }
465
466 /* Lookup the variable for the call statement CALL representing
467    the uses.  Returns NULL if there is nothing special about this call.  */
468
469 static varinfo_t
470 lookup_call_use_vi (gimple call)
471 {
472   void **slot_p;
473
474   slot_p = pointer_map_contains (call_stmt_vars, call);
475   if (slot_p)
476     return (varinfo_t) *slot_p;
477
478   return NULL;
479 }
480
481 /* Lookup the variable for the call statement CALL representing
482    the clobbers.  Returns NULL if there is nothing special about this call.  */
483
484 static varinfo_t
485 lookup_call_clobber_vi (gimple call)
486 {
487   varinfo_t uses = lookup_call_use_vi (call);
488   if (!uses)
489     return NULL;
490
491   return uses->next;
492 }
493
494 /* Lookup or create the variable for the call statement CALL representing
495    the uses.  */
496
497 static varinfo_t
498 get_call_use_vi (gimple call)
499 {
500   return get_call_vi (call);
501 }
502
503 /* Lookup or create the variable for the call statement CALL representing
504    the clobbers.  */
505
506 static varinfo_t ATTRIBUTE_UNUSED
507 get_call_clobber_vi (gimple call)
508 {
509   return get_call_vi (call)->next;
510 }
511
512
513 typedef enum {SCALAR, DEREF, ADDRESSOF} constraint_expr_type;
514
515 /* An expression that appears in a constraint.  */
516
517 struct constraint_expr
518 {
519   /* Constraint type.  */
520   constraint_expr_type type;
521
522   /* Variable we are referring to in the constraint.  */
523   unsigned int var;
524
525   /* Offset, in bits, of this constraint from the beginning of
526      variables it ends up referring to.
527
528      IOW, in a deref constraint, we would deref, get the result set,
529      then add OFFSET to each member.   */
530   HOST_WIDE_INT offset;
531 };
532
533 /* Use 0x8000... as special unknown offset.  */
534 #define UNKNOWN_OFFSET ((HOST_WIDE_INT)-1 << (HOST_BITS_PER_WIDE_INT-1))
535
536 typedef struct constraint_expr ce_s;
537 DEF_VEC_O(ce_s);
538 DEF_VEC_ALLOC_O(ce_s, heap);
539 static void get_constraint_for_1 (tree, VEC(ce_s, heap) **, bool, bool);
540 static void get_constraint_for (tree, VEC(ce_s, heap) **);
541 static void get_constraint_for_rhs (tree, VEC(ce_s, heap) **);
542 static void do_deref (VEC (ce_s, heap) **);
543
544 /* Our set constraints are made up of two constraint expressions, one
545    LHS, and one RHS.
546
547    As described in the introduction, our set constraints each represent an
548    operation between set valued variables.
549 */
550 struct constraint
551 {
552   struct constraint_expr lhs;
553   struct constraint_expr rhs;
554 };
555
556 /* List of constraints that we use to build the constraint graph from.  */
557
558 static VEC(constraint_t,heap) *constraints;
559 static alloc_pool constraint_pool;
560
561 /* The constraint graph is represented as an array of bitmaps
562    containing successor nodes.  */
563
564 struct constraint_graph
565 {
566   /* Size of this graph, which may be different than the number of
567      nodes in the variable map.  */
568   unsigned int size;
569
570   /* Explicit successors of each node. */
571   bitmap *succs;
572
573   /* Implicit predecessors of each node (Used for variable
574      substitution). */
575   bitmap *implicit_preds;
576
577   /* Explicit predecessors of each node (Used for variable substitution).  */
578   bitmap *preds;
579
580   /* Indirect cycle representatives, or -1 if the node has no indirect
581      cycles.  */
582   int *indirect_cycles;
583
584   /* Representative node for a node.  rep[a] == a unless the node has
585      been unified. */
586   unsigned int *rep;
587
588   /* Equivalence class representative for a label.  This is used for
589      variable substitution.  */
590   int *eq_rep;
591
592   /* Pointer equivalence label for a node.  All nodes with the same
593      pointer equivalence label can be unified together at some point
594      (either during constraint optimization or after the constraint
595      graph is built).  */
596   unsigned int *pe;
597
598   /* Pointer equivalence representative for a label.  This is used to
599      handle nodes that are pointer equivalent but not location
600      equivalent.  We can unite these once the addressof constraints
601      are transformed into initial points-to sets.  */
602   int *pe_rep;
603
604   /* Pointer equivalence label for each node, used during variable
605      substitution.  */
606   unsigned int *pointer_label;
607
608   /* Location equivalence label for each node, used during location
609      equivalence finding.  */
610   unsigned int *loc_label;
611
612   /* Pointed-by set for each node, used during location equivalence
613      finding.  This is pointed-by rather than pointed-to, because it
614      is constructed using the predecessor graph.  */
615   bitmap *pointed_by;
616
617   /* Points to sets for pointer equivalence.  This is *not* the actual
618      points-to sets for nodes.  */
619   bitmap *points_to;
620
621   /* Bitmap of nodes where the bit is set if the node is a direct
622      node.  Used for variable substitution.  */
623   sbitmap direct_nodes;
624
625   /* Bitmap of nodes where the bit is set if the node is address
626      taken.  Used for variable substitution.  */
627   bitmap address_taken;
628
629   /* Vector of complex constraints for each graph node.  Complex
630      constraints are those involving dereferences or offsets that are
631      not 0.  */
632   VEC(constraint_t,heap) **complex;
633 };
634
635 static constraint_graph_t graph;
636
637 /* During variable substitution and the offline version of indirect
638    cycle finding, we create nodes to represent dereferences and
639    address taken constraints.  These represent where these start and
640    end.  */
641 #define FIRST_REF_NODE (VEC_length (varinfo_t, varmap))
642 #define LAST_REF_NODE (FIRST_REF_NODE + (FIRST_REF_NODE - 1))
643
644 /* Return the representative node for NODE, if NODE has been unioned
645    with another NODE.
646    This function performs path compression along the way to finding
647    the representative.  */
648
649 static unsigned int
650 find (unsigned int node)
651 {
652   gcc_assert (node < graph->size);
653   if (graph->rep[node] != node)
654     return graph->rep[node] = find (graph->rep[node]);
655   return node;
656 }
657
658 /* Union the TO and FROM nodes to the TO nodes.
659    Note that at some point in the future, we may want to do
660    union-by-rank, in which case we are going to have to return the
661    node we unified to.  */
662
663 static bool
664 unite (unsigned int to, unsigned int from)
665 {
666   gcc_assert (to < graph->size && from < graph->size);
667   if (to != from && graph->rep[from] != to)
668     {
669       graph->rep[from] = to;
670       return true;
671     }
672   return false;
673 }
674
675 /* Create a new constraint consisting of LHS and RHS expressions.  */
676
677 static constraint_t
678 new_constraint (const struct constraint_expr lhs,
679                 const struct constraint_expr rhs)
680 {
681   constraint_t ret = (constraint_t) pool_alloc (constraint_pool);
682   ret->lhs = lhs;
683   ret->rhs = rhs;
684   return ret;
685 }
686
687 /* Print out constraint C to FILE.  */
688
689 static void
690 dump_constraint (FILE *file, constraint_t c)
691 {
692   if (c->lhs.type == ADDRESSOF)
693     fprintf (file, "&");
694   else if (c->lhs.type == DEREF)
695     fprintf (file, "*");
696   fprintf (file, "%s", get_varinfo (c->lhs.var)->name);
697   if (c->lhs.offset == UNKNOWN_OFFSET)
698     fprintf (file, " + UNKNOWN");
699   else if (c->lhs.offset != 0)
700     fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->lhs.offset);
701   fprintf (file, " = ");
702   if (c->rhs.type == ADDRESSOF)
703     fprintf (file, "&");
704   else if (c->rhs.type == DEREF)
705     fprintf (file, "*");
706   fprintf (file, "%s", get_varinfo (c->rhs.var)->name);
707   if (c->rhs.offset == UNKNOWN_OFFSET)
708     fprintf (file, " + UNKNOWN");
709   else if (c->rhs.offset != 0)
710     fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->rhs.offset);
711   fprintf (file, "\n");
712 }
713
714
715 void debug_constraint (constraint_t);
716 void debug_constraints (void);
717 void debug_constraint_graph (void);
718 void debug_solution_for_var (unsigned int);
719 void debug_sa_points_to_info (void);
720
721 /* Print out constraint C to stderr.  */
722
723 DEBUG_FUNCTION void
724 debug_constraint (constraint_t c)
725 {
726   dump_constraint (stderr, c);
727 }
728
729 /* Print out all constraints to FILE */
730
731 static void
732 dump_constraints (FILE *file, int from)
733 {
734   int i;
735   constraint_t c;
736   for (i = from; VEC_iterate (constraint_t, constraints, i, c); i++)
737     dump_constraint (file, c);
738 }
739
740 /* Print out all constraints to stderr.  */
741
742 DEBUG_FUNCTION void
743 debug_constraints (void)
744 {
745   dump_constraints (stderr, 0);
746 }
747
748 /* Print out to FILE the edge in the constraint graph that is created by
749    constraint c. The edge may have a label, depending on the type of
750    constraint that it represents. If complex1, e.g: a = *b, then the label
751    is "=*", if complex2, e.g: *a = b, then the label is "*=", if
752    complex with an offset, e.g: a = b + 8, then the label is "+".
753    Otherwise the edge has no label.  */
754
755 static void
756 dump_constraint_edge (FILE *file, constraint_t c)
757 {
758   if (c->rhs.type != ADDRESSOF)
759     {
760       const char *src = get_varinfo (c->rhs.var)->name;
761       const char *dst = get_varinfo (c->lhs.var)->name;
762       fprintf (file, "  \"%s\" -> \"%s\" ", src, dst);
763       /* Due to preprocessing of constraints, instructions like *a = *b are
764          illegal; thus, we do not have to handle such cases.  */
765       if (c->lhs.type == DEREF)
766         fprintf (file, " [ label=\"*=\" ] ;\n");
767       else if (c->rhs.type == DEREF)
768         fprintf (file, " [ label=\"=*\" ] ;\n");
769       else
770         {
771           /* We must check the case where the constraint is an offset.
772              In this case, it is treated as a complex constraint.  */
773           if (c->rhs.offset != c->lhs.offset)
774             fprintf (file, " [ label=\"+\" ] ;\n");
775           else
776             fprintf (file, " ;\n");
777         }
778     }
779 }
780
781 /* Print the constraint graph in dot format.  */
782
783 static void
784 dump_constraint_graph (FILE *file)
785 {
786   unsigned int i=0, size;
787   constraint_t c;
788
789   /* Only print the graph if it has already been initialized:  */
790   if (!graph)
791     return;
792
793   /* Print the constraints used to produce the constraint graph. The
794      constraints will be printed as comments in the dot file:  */
795   fprintf (file, "\n\n/* Constraints used in the constraint graph:\n");
796   dump_constraints (file, 0);
797   fprintf (file, "*/\n");
798
799   /* Prints the header of the dot file:  */
800   fprintf (file, "\n\n// The constraint graph in dot format:\n");
801   fprintf (file, "strict digraph {\n");
802   fprintf (file, "  node [\n    shape = box\n  ]\n");
803   fprintf (file, "  edge [\n    fontsize = \"12\"\n  ]\n");
804   fprintf (file, "\n  // List of nodes in the constraint graph:\n");
805
806   /* The next lines print the nodes in the graph. In order to get the
807      number of nodes in the graph, we must choose the minimum between the
808      vector VEC (varinfo_t, varmap) and graph->size. If the graph has not
809      yet been initialized, then graph->size == 0, otherwise we must only
810      read nodes that have an entry in VEC (varinfo_t, varmap).  */
811   size = VEC_length (varinfo_t, varmap);
812   size = size < graph->size ? size : graph->size;
813   for (i = 0; i < size; i++)
814     {
815       const char *name = get_varinfo (graph->rep[i])->name;
816       fprintf (file, "  \"%s\" ;\n", name);
817     }
818
819   /* Go over the list of constraints printing the edges in the constraint
820      graph.  */
821   fprintf (file, "\n  // The constraint edges:\n");
822   FOR_EACH_VEC_ELT (constraint_t, constraints, i, c)
823     if (c)
824       dump_constraint_edge (file, c);
825
826   /* Prints the tail of the dot file. By now, only the closing bracket.  */
827   fprintf (file, "}\n\n\n");
828 }
829
830 /* Print out the constraint graph to stderr.  */
831
832 DEBUG_FUNCTION void
833 debug_constraint_graph (void)
834 {
835   dump_constraint_graph (stderr);
836 }
837
838 /* SOLVER FUNCTIONS
839
840    The solver is a simple worklist solver, that works on the following
841    algorithm:
842
843    sbitmap changed_nodes = all zeroes;
844    changed_count = 0;
845    For each node that is not already collapsed:
846        changed_count++;
847        set bit in changed nodes
848
849    while (changed_count > 0)
850    {
851      compute topological ordering for constraint graph
852
853      find and collapse cycles in the constraint graph (updating
854      changed if necessary)
855
856      for each node (n) in the graph in topological order:
857        changed_count--;
858
859        Process each complex constraint associated with the node,
860        updating changed if necessary.
861
862        For each outgoing edge from n, propagate the solution from n to
863        the destination of the edge, updating changed as necessary.
864
865    }  */
866
867 /* Return true if two constraint expressions A and B are equal.  */
868
869 static bool
870 constraint_expr_equal (struct constraint_expr a, struct constraint_expr b)
871 {
872   return a.type == b.type && a.var == b.var && a.offset == b.offset;
873 }
874
875 /* Return true if constraint expression A is less than constraint expression
876    B.  This is just arbitrary, but consistent, in order to give them an
877    ordering.  */
878
879 static bool
880 constraint_expr_less (struct constraint_expr a, struct constraint_expr b)
881 {
882   if (a.type == b.type)
883     {
884       if (a.var == b.var)
885         return a.offset < b.offset;
886       else
887         return a.var < b.var;
888     }
889   else
890     return a.type < b.type;
891 }
892
893 /* Return true if constraint A is less than constraint B.  This is just
894    arbitrary, but consistent, in order to give them an ordering.  */
895
896 static bool
897 constraint_less (const constraint_t a, const constraint_t b)
898 {
899   if (constraint_expr_less (a->lhs, b->lhs))
900     return true;
901   else if (constraint_expr_less (b->lhs, a->lhs))
902     return false;
903   else
904     return constraint_expr_less (a->rhs, b->rhs);
905 }
906
907 /* Return true if two constraints A and B are equal.  */
908
909 static bool
910 constraint_equal (struct constraint a, struct constraint b)
911 {
912   return constraint_expr_equal (a.lhs, b.lhs)
913     && constraint_expr_equal (a.rhs, b.rhs);
914 }
915
916
917 /* Find a constraint LOOKFOR in the sorted constraint vector VEC */
918
919 static constraint_t
920 constraint_vec_find (VEC(constraint_t,heap) *vec,
921                      struct constraint lookfor)
922 {
923   unsigned int place;
924   constraint_t found;
925
926   if (vec == NULL)
927     return NULL;
928
929   place = VEC_lower_bound (constraint_t, vec, &lookfor, constraint_less);
930   if (place >= VEC_length (constraint_t, vec))
931     return NULL;
932   found = VEC_index (constraint_t, vec, place);
933   if (!constraint_equal (*found, lookfor))
934     return NULL;
935   return found;
936 }
937
938 /* Union two constraint vectors, TO and FROM.  Put the result in TO.  */
939
940 static void
941 constraint_set_union (VEC(constraint_t,heap) **to,
942                       VEC(constraint_t,heap) **from)
943 {
944   int i;
945   constraint_t c;
946
947   FOR_EACH_VEC_ELT (constraint_t, *from, i, c)
948     {
949       if (constraint_vec_find (*to, *c) == NULL)
950         {
951           unsigned int place = VEC_lower_bound (constraint_t, *to, c,
952                                                 constraint_less);
953           VEC_safe_insert (constraint_t, heap, *to, place, c);
954         }
955     }
956 }
957
958 /* Expands the solution in SET to all sub-fields of variables included.
959    Union the expanded result into RESULT.  */
960
961 static void
962 solution_set_expand (bitmap result, bitmap set)
963 {
964   bitmap_iterator bi;
965   bitmap vars = NULL;
966   unsigned j;
967
968   /* In a first pass record all variables we need to add all
969      sub-fields off.  This avoids quadratic behavior.  */
970   EXECUTE_IF_SET_IN_BITMAP (set, 0, j, bi)
971     {
972       varinfo_t v = get_varinfo (j);
973       if (v->is_artificial_var
974           || v->is_full_var)
975         continue;
976       v = lookup_vi_for_tree (v->decl);
977       if (vars == NULL)
978         vars = BITMAP_ALLOC (NULL);
979       bitmap_set_bit (vars, v->id);
980     }
981
982   /* In the second pass now do the addition to the solution and
983      to speed up solving add it to the delta as well.  */
984   if (vars != NULL)
985     {
986       EXECUTE_IF_SET_IN_BITMAP (vars, 0, j, bi)
987         {
988           varinfo_t v = get_varinfo (j);
989           for (; v != NULL; v = v->next)
990             bitmap_set_bit (result, v->id);
991         }
992       BITMAP_FREE (vars);
993     }
994 }
995
996 /* Take a solution set SET, add OFFSET to each member of the set, and
997    overwrite SET with the result when done.  */
998
999 static void
1000 solution_set_add (bitmap set, HOST_WIDE_INT offset)
1001 {
1002   bitmap result = BITMAP_ALLOC (&iteration_obstack);
1003   unsigned int i;
1004   bitmap_iterator bi;
1005
1006   /* If the offset is unknown we have to expand the solution to
1007      all subfields.  */
1008   if (offset == UNKNOWN_OFFSET)
1009     {
1010       solution_set_expand (set, set);
1011       return;
1012     }
1013
1014   EXECUTE_IF_SET_IN_BITMAP (set, 0, i, bi)
1015     {
1016       varinfo_t vi = get_varinfo (i);
1017
1018       /* If this is a variable with just one field just set its bit
1019          in the result.  */
1020       if (vi->is_artificial_var
1021           || vi->is_unknown_size_var
1022           || vi->is_full_var)
1023         bitmap_set_bit (result, i);
1024       else
1025         {
1026           unsigned HOST_WIDE_INT fieldoffset = vi->offset + offset;
1027
1028           /* If the offset makes the pointer point to before the
1029              variable use offset zero for the field lookup.  */
1030           if (offset < 0
1031               && fieldoffset > vi->offset)
1032             fieldoffset = 0;
1033
1034           if (offset != 0)
1035             vi = first_or_preceding_vi_for_offset (vi, fieldoffset);
1036
1037           bitmap_set_bit (result, vi->id);
1038           /* If the result is not exactly at fieldoffset include the next
1039              field as well.  See get_constraint_for_ptr_offset for more
1040              rationale.  */
1041           if (vi->offset != fieldoffset
1042               && vi->next != NULL)
1043             bitmap_set_bit (result, vi->next->id);
1044         }
1045     }
1046
1047   bitmap_copy (set, result);
1048   BITMAP_FREE (result);
1049 }
1050
1051 /* Union solution sets TO and FROM, and add INC to each member of FROM in the
1052    process.  */
1053
1054 static bool
1055 set_union_with_increment  (bitmap to, bitmap from, HOST_WIDE_INT inc)
1056 {
1057   if (inc == 0)
1058     return bitmap_ior_into (to, from);
1059   else
1060     {
1061       bitmap tmp;
1062       bool res;
1063
1064       tmp = BITMAP_ALLOC (&iteration_obstack);
1065       bitmap_copy (tmp, from);
1066       solution_set_add (tmp, inc);
1067       res = bitmap_ior_into (to, tmp);
1068       BITMAP_FREE (tmp);
1069       return res;
1070     }
1071 }
1072
1073 /* Insert constraint C into the list of complex constraints for graph
1074    node VAR.  */
1075
1076 static void
1077 insert_into_complex (constraint_graph_t graph,
1078                      unsigned int var, constraint_t c)
1079 {
1080   VEC (constraint_t, heap) *complex = graph->complex[var];
1081   unsigned int place = VEC_lower_bound (constraint_t, complex, c,
1082                                         constraint_less);
1083
1084   /* Only insert constraints that do not already exist.  */
1085   if (place >= VEC_length (constraint_t, complex)
1086       || !constraint_equal (*c, *VEC_index (constraint_t, complex, place)))
1087     VEC_safe_insert (constraint_t, heap, graph->complex[var], place, c);
1088 }
1089
1090
1091 /* Condense two variable nodes into a single variable node, by moving
1092    all associated info from SRC to TO.  */
1093
1094 static void
1095 merge_node_constraints (constraint_graph_t graph, unsigned int to,
1096                         unsigned int from)
1097 {
1098   unsigned int i;
1099   constraint_t c;
1100
1101   gcc_assert (find (from) == to);
1102
1103   /* Move all complex constraints from src node into to node  */
1104   FOR_EACH_VEC_ELT (constraint_t, graph->complex[from], i, c)
1105     {
1106       /* In complex constraints for node src, we may have either
1107          a = *src, and *src = a, or an offseted constraint which are
1108          always added to the rhs node's constraints.  */
1109
1110       if (c->rhs.type == DEREF)
1111         c->rhs.var = to;
1112       else if (c->lhs.type == DEREF)
1113         c->lhs.var = to;
1114       else
1115         c->rhs.var = to;
1116     }
1117   constraint_set_union (&graph->complex[to], &graph->complex[from]);
1118   VEC_free (constraint_t, heap, graph->complex[from]);
1119   graph->complex[from] = NULL;
1120 }
1121
1122
1123 /* Remove edges involving NODE from GRAPH.  */
1124
1125 static void
1126 clear_edges_for_node (constraint_graph_t graph, unsigned int node)
1127 {
1128   if (graph->succs[node])
1129     BITMAP_FREE (graph->succs[node]);
1130 }
1131
1132 /* Merge GRAPH nodes FROM and TO into node TO.  */
1133
1134 static void
1135 merge_graph_nodes (constraint_graph_t graph, unsigned int to,
1136                    unsigned int from)
1137 {
1138   if (graph->indirect_cycles[from] != -1)
1139     {
1140       /* If we have indirect cycles with the from node, and we have
1141          none on the to node, the to node has indirect cycles from the
1142          from node now that they are unified.
1143          If indirect cycles exist on both, unify the nodes that they
1144          are in a cycle with, since we know they are in a cycle with
1145          each other.  */
1146       if (graph->indirect_cycles[to] == -1)
1147         graph->indirect_cycles[to] = graph->indirect_cycles[from];
1148     }
1149
1150   /* Merge all the successor edges.  */
1151   if (graph->succs[from])
1152     {
1153       if (!graph->succs[to])
1154         graph->succs[to] = BITMAP_ALLOC (&pta_obstack);
1155       bitmap_ior_into (graph->succs[to],
1156                        graph->succs[from]);
1157     }
1158
1159   clear_edges_for_node (graph, from);
1160 }
1161
1162
1163 /* Add an indirect graph edge to GRAPH, going from TO to FROM if
1164    it doesn't exist in the graph already.  */
1165
1166 static void
1167 add_implicit_graph_edge (constraint_graph_t graph, unsigned int to,
1168                          unsigned int from)
1169 {
1170   if (to == from)
1171     return;
1172
1173   if (!graph->implicit_preds[to])
1174     graph->implicit_preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1175
1176   if (bitmap_set_bit (graph->implicit_preds[to], from))
1177     stats.num_implicit_edges++;
1178 }
1179
1180 /* Add a predecessor graph edge to GRAPH, going from TO to FROM if
1181    it doesn't exist in the graph already.
1182    Return false if the edge already existed, true otherwise.  */
1183
1184 static void
1185 add_pred_graph_edge (constraint_graph_t graph, unsigned int to,
1186                      unsigned int from)
1187 {
1188   if (!graph->preds[to])
1189     graph->preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1190   bitmap_set_bit (graph->preds[to], from);
1191 }
1192
1193 /* Add a graph edge to GRAPH, going from FROM to TO if
1194    it doesn't exist in the graph already.
1195    Return false if the edge already existed, true otherwise.  */
1196
1197 static bool
1198 add_graph_edge (constraint_graph_t graph, unsigned int to,
1199                 unsigned int from)
1200 {
1201   if (to == from)
1202     {
1203       return false;
1204     }
1205   else
1206     {
1207       bool r = false;
1208
1209       if (!graph->succs[from])
1210         graph->succs[from] = BITMAP_ALLOC (&pta_obstack);
1211       if (bitmap_set_bit (graph->succs[from], to))
1212         {
1213           r = true;
1214           if (to < FIRST_REF_NODE && from < FIRST_REF_NODE)
1215             stats.num_edges++;
1216         }
1217       return r;
1218     }
1219 }
1220
1221
1222 /* Return true if {DEST.SRC} is an existing graph edge in GRAPH.  */
1223
1224 static bool
1225 valid_graph_edge (constraint_graph_t graph, unsigned int src,
1226                   unsigned int dest)
1227 {
1228   return (graph->succs[dest]
1229           && bitmap_bit_p (graph->succs[dest], src));
1230 }
1231
1232 /* Initialize the constraint graph structure to contain SIZE nodes.  */
1233
1234 static void
1235 init_graph (unsigned int size)
1236 {
1237   unsigned int j;
1238
1239   graph = XCNEW (struct constraint_graph);
1240   graph->size = size;
1241   graph->succs = XCNEWVEC (bitmap, graph->size);
1242   graph->indirect_cycles = XNEWVEC (int, graph->size);
1243   graph->rep = XNEWVEC (unsigned int, graph->size);
1244   graph->complex = XCNEWVEC (VEC(constraint_t, heap) *, size);
1245   graph->pe = XCNEWVEC (unsigned int, graph->size);
1246   graph->pe_rep = XNEWVEC (int, graph->size);
1247
1248   for (j = 0; j < graph->size; j++)
1249     {
1250       graph->rep[j] = j;
1251       graph->pe_rep[j] = -1;
1252       graph->indirect_cycles[j] = -1;
1253     }
1254 }
1255
1256 /* Build the constraint graph, adding only predecessor edges right now.  */
1257
1258 static void
1259 build_pred_graph (void)
1260 {
1261   int i;
1262   constraint_t c;
1263   unsigned int j;
1264
1265   graph->implicit_preds = XCNEWVEC (bitmap, graph->size);
1266   graph->preds = XCNEWVEC (bitmap, graph->size);
1267   graph->pointer_label = XCNEWVEC (unsigned int, graph->size);
1268   graph->loc_label = XCNEWVEC (unsigned int, graph->size);
1269   graph->pointed_by = XCNEWVEC (bitmap, graph->size);
1270   graph->points_to = XCNEWVEC (bitmap, graph->size);
1271   graph->eq_rep = XNEWVEC (int, graph->size);
1272   graph->direct_nodes = sbitmap_alloc (graph->size);
1273   graph->address_taken = BITMAP_ALLOC (&predbitmap_obstack);
1274   sbitmap_zero (graph->direct_nodes);
1275
1276   for (j = 0; j < FIRST_REF_NODE; j++)
1277     {
1278       if (!get_varinfo (j)->is_special_var)
1279         SET_BIT (graph->direct_nodes, j);
1280     }
1281
1282   for (j = 0; j < graph->size; j++)
1283     graph->eq_rep[j] = -1;
1284
1285   for (j = 0; j < VEC_length (varinfo_t, varmap); j++)
1286     graph->indirect_cycles[j] = -1;
1287
1288   FOR_EACH_VEC_ELT (constraint_t, constraints, i, c)
1289     {
1290       struct constraint_expr lhs = c->lhs;
1291       struct constraint_expr rhs = c->rhs;
1292       unsigned int lhsvar = lhs.var;
1293       unsigned int rhsvar = rhs.var;
1294
1295       if (lhs.type == DEREF)
1296         {
1297           /* *x = y.  */
1298           if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1299             add_pred_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1300         }
1301       else if (rhs.type == DEREF)
1302         {
1303           /* x = *y */
1304           if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1305             add_pred_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1306           else
1307             RESET_BIT (graph->direct_nodes, lhsvar);
1308         }
1309       else if (rhs.type == ADDRESSOF)
1310         {
1311           varinfo_t v;
1312
1313           /* x = &y */
1314           if (graph->points_to[lhsvar] == NULL)
1315             graph->points_to[lhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1316           bitmap_set_bit (graph->points_to[lhsvar], rhsvar);
1317
1318           if (graph->pointed_by[rhsvar] == NULL)
1319             graph->pointed_by[rhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1320           bitmap_set_bit (graph->pointed_by[rhsvar], lhsvar);
1321
1322           /* Implicitly, *x = y */
1323           add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1324
1325           /* All related variables are no longer direct nodes.  */
1326           RESET_BIT (graph->direct_nodes, rhsvar);
1327           v = get_varinfo (rhsvar);
1328           if (!v->is_full_var)
1329             {
1330               v = lookup_vi_for_tree (v->decl);
1331               do
1332                 {
1333                   RESET_BIT (graph->direct_nodes, v->id);
1334                   v = v->next;
1335                 }
1336               while (v != NULL);
1337             }
1338           bitmap_set_bit (graph->address_taken, rhsvar);
1339         }
1340       else if (lhsvar > anything_id
1341                && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1342         {
1343           /* x = y */
1344           add_pred_graph_edge (graph, lhsvar, rhsvar);
1345           /* Implicitly, *x = *y */
1346           add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar,
1347                                    FIRST_REF_NODE + rhsvar);
1348         }
1349       else if (lhs.offset != 0 || rhs.offset != 0)
1350         {
1351           if (rhs.offset != 0)
1352             RESET_BIT (graph->direct_nodes, lhs.var);
1353           else if (lhs.offset != 0)
1354             RESET_BIT (graph->direct_nodes, rhs.var);
1355         }
1356     }
1357 }
1358
1359 /* Build the constraint graph, adding successor edges.  */
1360
1361 static void
1362 build_succ_graph (void)
1363 {
1364   unsigned i, t;
1365   constraint_t c;
1366
1367   FOR_EACH_VEC_ELT (constraint_t, constraints, i, c)
1368     {
1369       struct constraint_expr lhs;
1370       struct constraint_expr rhs;
1371       unsigned int lhsvar;
1372       unsigned int rhsvar;
1373
1374       if (!c)
1375         continue;
1376
1377       lhs = c->lhs;
1378       rhs = c->rhs;
1379       lhsvar = find (lhs.var);
1380       rhsvar = find (rhs.var);
1381
1382       if (lhs.type == DEREF)
1383         {
1384           if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1385             add_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1386         }
1387       else if (rhs.type == DEREF)
1388         {
1389           if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1390             add_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1391         }
1392       else if (rhs.type == ADDRESSOF)
1393         {
1394           /* x = &y */
1395           gcc_assert (find (rhs.var) == rhs.var);
1396           bitmap_set_bit (get_varinfo (lhsvar)->solution, rhsvar);
1397         }
1398       else if (lhsvar > anything_id
1399                && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1400         {
1401           add_graph_edge (graph, lhsvar, rhsvar);
1402         }
1403     }
1404
1405   /* Add edges from STOREDANYTHING to all non-direct nodes that can
1406      receive pointers.  */
1407   t = find (storedanything_id);
1408   for (i = integer_id + 1; i < FIRST_REF_NODE; ++i)
1409     {
1410       if (!TEST_BIT (graph->direct_nodes, i)
1411           && get_varinfo (i)->may_have_pointers)
1412         add_graph_edge (graph, find (i), t);
1413     }
1414
1415   /* Everything stored to ANYTHING also potentially escapes.  */
1416   add_graph_edge (graph, find (escaped_id), t);
1417 }
1418
1419
1420 /* Changed variables on the last iteration.  */
1421 static unsigned int changed_count;
1422 static sbitmap changed;
1423
1424 /* Strongly Connected Component visitation info.  */
1425
1426 struct scc_info
1427 {
1428   sbitmap visited;
1429   sbitmap deleted;
1430   unsigned int *dfs;
1431   unsigned int *node_mapping;
1432   int current_index;
1433   VEC(unsigned,heap) *scc_stack;
1434 };
1435
1436
1437 /* Recursive routine to find strongly connected components in GRAPH.
1438    SI is the SCC info to store the information in, and N is the id of current
1439    graph node we are processing.
1440
1441    This is Tarjan's strongly connected component finding algorithm, as
1442    modified by Nuutila to keep only non-root nodes on the stack.
1443    The algorithm can be found in "On finding the strongly connected
1444    connected components in a directed graph" by Esko Nuutila and Eljas
1445    Soisalon-Soininen, in Information Processing Letters volume 49,
1446    number 1, pages 9-14.  */
1447
1448 static void
1449 scc_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1450 {
1451   unsigned int i;
1452   bitmap_iterator bi;
1453   unsigned int my_dfs;
1454
1455   SET_BIT (si->visited, n);
1456   si->dfs[n] = si->current_index ++;
1457   my_dfs = si->dfs[n];
1458
1459   /* Visit all the successors.  */
1460   EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[n], 0, i, bi)
1461     {
1462       unsigned int w;
1463
1464       if (i > LAST_REF_NODE)
1465         break;
1466
1467       w = find (i);
1468       if (TEST_BIT (si->deleted, w))
1469         continue;
1470
1471       if (!TEST_BIT (si->visited, w))
1472         scc_visit (graph, si, w);
1473       {
1474         unsigned int t = find (w);
1475         unsigned int nnode = find (n);
1476         gcc_assert (nnode == n);
1477
1478         if (si->dfs[t] < si->dfs[nnode])
1479           si->dfs[n] = si->dfs[t];
1480       }
1481     }
1482
1483   /* See if any components have been identified.  */
1484   if (si->dfs[n] == my_dfs)
1485     {
1486       if (VEC_length (unsigned, si->scc_stack) > 0
1487           && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
1488         {
1489           bitmap scc = BITMAP_ALLOC (NULL);
1490           unsigned int lowest_node;
1491           bitmap_iterator bi;
1492
1493           bitmap_set_bit (scc, n);
1494
1495           while (VEC_length (unsigned, si->scc_stack) != 0
1496                  && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
1497             {
1498               unsigned int w = VEC_pop (unsigned, si->scc_stack);
1499
1500               bitmap_set_bit (scc, w);
1501             }
1502
1503           lowest_node = bitmap_first_set_bit (scc);
1504           gcc_assert (lowest_node < FIRST_REF_NODE);
1505
1506           /* Collapse the SCC nodes into a single node, and mark the
1507              indirect cycles.  */
1508           EXECUTE_IF_SET_IN_BITMAP (scc, 0, i, bi)
1509             {
1510               if (i < FIRST_REF_NODE)
1511                 {
1512                   if (unite (lowest_node, i))
1513                     unify_nodes (graph, lowest_node, i, false);
1514                 }
1515               else
1516                 {
1517                   unite (lowest_node, i);
1518                   graph->indirect_cycles[i - FIRST_REF_NODE] = lowest_node;
1519                 }
1520             }
1521         }
1522       SET_BIT (si->deleted, n);
1523     }
1524   else
1525     VEC_safe_push (unsigned, heap, si->scc_stack, n);
1526 }
1527
1528 /* Unify node FROM into node TO, updating the changed count if
1529    necessary when UPDATE_CHANGED is true.  */
1530
1531 static void
1532 unify_nodes (constraint_graph_t graph, unsigned int to, unsigned int from,
1533              bool update_changed)
1534 {
1535
1536   gcc_assert (to != from && find (to) == to);
1537   if (dump_file && (dump_flags & TDF_DETAILS))
1538     fprintf (dump_file, "Unifying %s to %s\n",
1539              get_varinfo (from)->name,
1540              get_varinfo (to)->name);
1541
1542   if (update_changed)
1543     stats.unified_vars_dynamic++;
1544   else
1545     stats.unified_vars_static++;
1546
1547   merge_graph_nodes (graph, to, from);
1548   merge_node_constraints (graph, to, from);
1549
1550   /* Mark TO as changed if FROM was changed. If TO was already marked
1551      as changed, decrease the changed count.  */
1552
1553   if (update_changed && TEST_BIT (changed, from))
1554     {
1555       RESET_BIT (changed, from);
1556       if (!TEST_BIT (changed, to))
1557         SET_BIT (changed, to);
1558       else
1559         {
1560           gcc_assert (changed_count > 0);
1561           changed_count--;
1562         }
1563     }
1564   if (get_varinfo (from)->solution)
1565     {
1566       /* If the solution changes because of the merging, we need to mark
1567          the variable as changed.  */
1568       if (bitmap_ior_into (get_varinfo (to)->solution,
1569                            get_varinfo (from)->solution))
1570         {
1571           if (update_changed && !TEST_BIT (changed, to))
1572             {
1573               SET_BIT (changed, to);
1574               changed_count++;
1575             }
1576         }
1577
1578       BITMAP_FREE (get_varinfo (from)->solution);
1579       BITMAP_FREE (get_varinfo (from)->oldsolution);
1580
1581       if (stats.iterations > 0)
1582         {
1583           BITMAP_FREE (get_varinfo (to)->oldsolution);
1584           get_varinfo (to)->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
1585         }
1586     }
1587   if (valid_graph_edge (graph, to, to))
1588     {
1589       if (graph->succs[to])
1590         bitmap_clear_bit (graph->succs[to], to);
1591     }
1592 }
1593
1594 /* Information needed to compute the topological ordering of a graph.  */
1595
1596 struct topo_info
1597 {
1598   /* sbitmap of visited nodes.  */
1599   sbitmap visited;
1600   /* Array that stores the topological order of the graph, *in
1601      reverse*.  */
1602   VEC(unsigned,heap) *topo_order;
1603 };
1604
1605
1606 /* Initialize and return a topological info structure.  */
1607
1608 static struct topo_info *
1609 init_topo_info (void)
1610 {
1611   size_t size = graph->size;
1612   struct topo_info *ti = XNEW (struct topo_info);
1613   ti->visited = sbitmap_alloc (size);
1614   sbitmap_zero (ti->visited);
1615   ti->topo_order = VEC_alloc (unsigned, heap, 1);
1616   return ti;
1617 }
1618
1619
1620 /* Free the topological sort info pointed to by TI.  */
1621
1622 static void
1623 free_topo_info (struct topo_info *ti)
1624 {
1625   sbitmap_free (ti->visited);
1626   VEC_free (unsigned, heap, ti->topo_order);
1627   free (ti);
1628 }
1629
1630 /* Visit the graph in topological order, and store the order in the
1631    topo_info structure.  */
1632
1633 static void
1634 topo_visit (constraint_graph_t graph, struct topo_info *ti,
1635             unsigned int n)
1636 {
1637   bitmap_iterator bi;
1638   unsigned int j;
1639
1640   SET_BIT (ti->visited, n);
1641
1642   if (graph->succs[n])
1643     EXECUTE_IF_SET_IN_BITMAP (graph->succs[n], 0, j, bi)
1644       {
1645         if (!TEST_BIT (ti->visited, j))
1646           topo_visit (graph, ti, j);
1647       }
1648
1649   VEC_safe_push (unsigned, heap, ti->topo_order, n);
1650 }
1651
1652 /* Process a constraint C that represents x = *(y + off), using DELTA as the
1653    starting solution for y.  */
1654
1655 static void
1656 do_sd_constraint (constraint_graph_t graph, constraint_t c,
1657                   bitmap delta)
1658 {
1659   unsigned int lhs = c->lhs.var;
1660   bool flag = false;
1661   bitmap sol = get_varinfo (lhs)->solution;
1662   unsigned int j;
1663   bitmap_iterator bi;
1664   HOST_WIDE_INT roffset = c->rhs.offset;
1665
1666   /* Our IL does not allow this.  */
1667   gcc_assert (c->lhs.offset == 0);
1668
1669   /* If the solution of Y contains anything it is good enough to transfer
1670      this to the LHS.  */
1671   if (bitmap_bit_p (delta, anything_id))
1672     {
1673       flag |= bitmap_set_bit (sol, anything_id);
1674       goto done;
1675     }
1676
1677   /* If we do not know at with offset the rhs is dereferenced compute
1678      the reachability set of DELTA, conservatively assuming it is
1679      dereferenced at all valid offsets.  */
1680   if (roffset == UNKNOWN_OFFSET)
1681     {
1682       solution_set_expand (delta, delta);
1683       /* No further offset processing is necessary.  */
1684       roffset = 0;
1685     }
1686
1687   /* For each variable j in delta (Sol(y)), add
1688      an edge in the graph from j to x, and union Sol(j) into Sol(x).  */
1689   EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1690     {
1691       varinfo_t v = get_varinfo (j);
1692       HOST_WIDE_INT fieldoffset = v->offset + roffset;
1693       unsigned int t;
1694
1695       if (v->is_full_var)
1696         fieldoffset = v->offset;
1697       else if (roffset != 0)
1698         v = first_vi_for_offset (v, fieldoffset);
1699       /* If the access is outside of the variable we can ignore it.  */
1700       if (!v)
1701         continue;
1702
1703       do
1704         {
1705           t = find (v->id);
1706
1707           /* Adding edges from the special vars is pointless.
1708              They don't have sets that can change.  */
1709           if (get_varinfo (t)->is_special_var)
1710             flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1711           /* Merging the solution from ESCAPED needlessly increases
1712              the set.  Use ESCAPED as representative instead.  */
1713           else if (v->id == escaped_id)
1714             flag |= bitmap_set_bit (sol, escaped_id);
1715           else if (v->may_have_pointers
1716                    && add_graph_edge (graph, lhs, t))
1717             flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1718
1719           /* If the variable is not exactly at the requested offset
1720              we have to include the next one.  */
1721           if (v->offset == (unsigned HOST_WIDE_INT)fieldoffset
1722               || v->next == NULL)
1723             break;
1724
1725           v = v->next;
1726           fieldoffset = v->offset;
1727         }
1728       while (1);
1729     }
1730
1731 done:
1732   /* If the LHS solution changed, mark the var as changed.  */
1733   if (flag)
1734     {
1735       get_varinfo (lhs)->solution = sol;
1736       if (!TEST_BIT (changed, lhs))
1737         {
1738           SET_BIT (changed, lhs);
1739           changed_count++;
1740         }
1741     }
1742 }
1743
1744 /* Process a constraint C that represents *(x + off) = y using DELTA
1745    as the starting solution for x.  */
1746
1747 static void
1748 do_ds_constraint (constraint_t c, bitmap delta)
1749 {
1750   unsigned int rhs = c->rhs.var;
1751   bitmap sol = get_varinfo (rhs)->solution;
1752   unsigned int j;
1753   bitmap_iterator bi;
1754   HOST_WIDE_INT loff = c->lhs.offset;
1755   bool escaped_p = false;
1756
1757   /* Our IL does not allow this.  */
1758   gcc_assert (c->rhs.offset == 0);
1759
1760   /* If the solution of y contains ANYTHING simply use the ANYTHING
1761      solution.  This avoids needlessly increasing the points-to sets.  */
1762   if (bitmap_bit_p (sol, anything_id))
1763     sol = get_varinfo (find (anything_id))->solution;
1764
1765   /* If the solution for x contains ANYTHING we have to merge the
1766      solution of y into all pointer variables which we do via
1767      STOREDANYTHING.  */
1768   if (bitmap_bit_p (delta, anything_id))
1769     {
1770       unsigned t = find (storedanything_id);
1771       if (add_graph_edge (graph, t, rhs))
1772         {
1773           if (bitmap_ior_into (get_varinfo (t)->solution, sol))
1774             {
1775               if (!TEST_BIT (changed, t))
1776                 {
1777                   SET_BIT (changed, t);
1778                   changed_count++;
1779                 }
1780             }
1781         }
1782       return;
1783     }
1784
1785   /* If we do not know at with offset the rhs is dereferenced compute
1786      the reachability set of DELTA, conservatively assuming it is
1787      dereferenced at all valid offsets.  */
1788   if (loff == UNKNOWN_OFFSET)
1789     {
1790       solution_set_expand (delta, delta);
1791       loff = 0;
1792     }
1793
1794   /* For each member j of delta (Sol(x)), add an edge from y to j and
1795      union Sol(y) into Sol(j) */
1796   EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1797     {
1798       varinfo_t v = get_varinfo (j);
1799       unsigned int t;
1800       HOST_WIDE_INT fieldoffset = v->offset + loff;
1801
1802       if (v->is_full_var)
1803         fieldoffset = v->offset;
1804       else if (loff != 0)
1805         v = first_vi_for_offset (v, fieldoffset);
1806       /* If the access is outside of the variable we can ignore it.  */
1807       if (!v)
1808         continue;
1809
1810       do
1811         {
1812           if (v->may_have_pointers)
1813             {
1814               /* If v is a global variable then this is an escape point.  */
1815               if (v->is_global_var
1816                   && !escaped_p)
1817                 {
1818                   t = find (escaped_id);
1819                   if (add_graph_edge (graph, t, rhs)
1820                       && bitmap_ior_into (get_varinfo (t)->solution, sol)
1821                       && !TEST_BIT (changed, t))
1822                     {
1823                       SET_BIT (changed, t);
1824                       changed_count++;
1825                     }
1826                   /* Enough to let rhs escape once.  */
1827                   escaped_p = true;
1828                 }
1829
1830               if (v->is_special_var)
1831                 break;
1832
1833               t = find (v->id);
1834               if (add_graph_edge (graph, t, rhs)
1835                   && bitmap_ior_into (get_varinfo (t)->solution, sol)
1836                   && !TEST_BIT (changed, t))
1837                 {
1838                   SET_BIT (changed, t);
1839                   changed_count++;
1840                 }
1841             }
1842
1843           /* If the variable is not exactly at the requested offset
1844              we have to include the next one.  */
1845           if (v->offset == (unsigned HOST_WIDE_INT)fieldoffset
1846               || v->next == NULL)
1847             break;
1848
1849           v = v->next;
1850           fieldoffset = v->offset;
1851         }
1852       while (1);
1853     }
1854 }
1855
1856 /* Handle a non-simple (simple meaning requires no iteration),
1857    constraint (IE *x = &y, x = *y, *x = y, and x = y with offsets involved).  */
1858
1859 static void
1860 do_complex_constraint (constraint_graph_t graph, constraint_t c, bitmap delta)
1861 {
1862   if (c->lhs.type == DEREF)
1863     {
1864       if (c->rhs.type == ADDRESSOF)
1865         {
1866           gcc_unreachable();
1867         }
1868       else
1869         {
1870           /* *x = y */
1871           do_ds_constraint (c, delta);
1872         }
1873     }
1874   else if (c->rhs.type == DEREF)
1875     {
1876       /* x = *y */
1877       if (!(get_varinfo (c->lhs.var)->is_special_var))
1878         do_sd_constraint (graph, c, delta);
1879     }
1880   else
1881     {
1882       bitmap tmp;
1883       bitmap solution;
1884       bool flag = false;
1885
1886       gcc_assert (c->rhs.type == SCALAR && c->lhs.type == SCALAR);
1887       solution = get_varinfo (c->rhs.var)->solution;
1888       tmp = get_varinfo (c->lhs.var)->solution;
1889
1890       flag = set_union_with_increment (tmp, solution, c->rhs.offset);
1891
1892       if (flag)
1893         {
1894           get_varinfo (c->lhs.var)->solution = tmp;
1895           if (!TEST_BIT (changed, c->lhs.var))
1896             {
1897               SET_BIT (changed, c->lhs.var);
1898               changed_count++;
1899             }
1900         }
1901     }
1902 }
1903
1904 /* Initialize and return a new SCC info structure.  */
1905
1906 static struct scc_info *
1907 init_scc_info (size_t size)
1908 {
1909   struct scc_info *si = XNEW (struct scc_info);
1910   size_t i;
1911
1912   si->current_index = 0;
1913   si->visited = sbitmap_alloc (size);
1914   sbitmap_zero (si->visited);
1915   si->deleted = sbitmap_alloc (size);
1916   sbitmap_zero (si->deleted);
1917   si->node_mapping = XNEWVEC (unsigned int, size);
1918   si->dfs = XCNEWVEC (unsigned int, size);
1919
1920   for (i = 0; i < size; i++)
1921     si->node_mapping[i] = i;
1922
1923   si->scc_stack = VEC_alloc (unsigned, heap, 1);
1924   return si;
1925 }
1926
1927 /* Free an SCC info structure pointed to by SI */
1928
1929 static void
1930 free_scc_info (struct scc_info *si)
1931 {
1932   sbitmap_free (si->visited);
1933   sbitmap_free (si->deleted);
1934   free (si->node_mapping);
1935   free (si->dfs);
1936   VEC_free (unsigned, heap, si->scc_stack);
1937   free (si);
1938 }
1939
1940
1941 /* Find indirect cycles in GRAPH that occur, using strongly connected
1942    components, and note them in the indirect cycles map.
1943
1944    This technique comes from Ben Hardekopf and Calvin Lin,
1945    "It Pays to be Lazy: Fast and Accurate Pointer Analysis for Millions of
1946    Lines of Code", submitted to PLDI 2007.  */
1947
1948 static void
1949 find_indirect_cycles (constraint_graph_t graph)
1950 {
1951   unsigned int i;
1952   unsigned int size = graph->size;
1953   struct scc_info *si = init_scc_info (size);
1954
1955   for (i = 0; i < MIN (LAST_REF_NODE, size); i ++ )
1956     if (!TEST_BIT (si->visited, i) && find (i) == i)
1957       scc_visit (graph, si, i);
1958
1959   free_scc_info (si);
1960 }
1961
1962 /* Compute a topological ordering for GRAPH, and store the result in the
1963    topo_info structure TI.  */
1964
1965 static void
1966 compute_topo_order (constraint_graph_t graph,
1967                     struct topo_info *ti)
1968 {
1969   unsigned int i;
1970   unsigned int size = graph->size;
1971
1972   for (i = 0; i != size; ++i)
1973     if (!TEST_BIT (ti->visited, i) && find (i) == i)
1974       topo_visit (graph, ti, i);
1975 }
1976
1977 /* Structure used to for hash value numbering of pointer equivalence
1978    classes.  */
1979
1980 typedef struct equiv_class_label
1981 {
1982   hashval_t hashcode;
1983   unsigned int equivalence_class;
1984   bitmap labels;
1985 } *equiv_class_label_t;
1986 typedef const struct equiv_class_label *const_equiv_class_label_t;
1987
1988 /* A hashtable for mapping a bitmap of labels->pointer equivalence
1989    classes.  */
1990 static htab_t pointer_equiv_class_table;
1991
1992 /* A hashtable for mapping a bitmap of labels->location equivalence
1993    classes.  */
1994 static htab_t location_equiv_class_table;
1995
1996 /* Hash function for a equiv_class_label_t */
1997
1998 static hashval_t
1999 equiv_class_label_hash (const void *p)
2000 {
2001   const_equiv_class_label_t const ecl = (const_equiv_class_label_t) p;
2002   return ecl->hashcode;
2003 }
2004
2005 /* Equality function for two equiv_class_label_t's.  */
2006
2007 static int
2008 equiv_class_label_eq (const void *p1, const void *p2)
2009 {
2010   const_equiv_class_label_t const eql1 = (const_equiv_class_label_t) p1;
2011   const_equiv_class_label_t const eql2 = (const_equiv_class_label_t) p2;
2012   return (eql1->hashcode == eql2->hashcode
2013           && bitmap_equal_p (eql1->labels, eql2->labels));
2014 }
2015
2016 /* Lookup a equivalence class in TABLE by the bitmap of LABELS it
2017    contains.  */
2018
2019 static unsigned int
2020 equiv_class_lookup (htab_t table, bitmap labels)
2021 {
2022   void **slot;
2023   struct equiv_class_label ecl;
2024
2025   ecl.labels = labels;
2026   ecl.hashcode = bitmap_hash (labels);
2027
2028   slot = htab_find_slot_with_hash (table, &ecl,
2029                                    ecl.hashcode, NO_INSERT);
2030   if (!slot)
2031     return 0;
2032   else
2033     return ((equiv_class_label_t) *slot)->equivalence_class;
2034 }
2035
2036
2037 /* Add an equivalence class named EQUIVALENCE_CLASS with labels LABELS
2038    to TABLE.  */
2039
2040 static void
2041 equiv_class_add (htab_t table, unsigned int equivalence_class,
2042                  bitmap labels)
2043 {
2044   void **slot;
2045   equiv_class_label_t ecl = XNEW (struct equiv_class_label);
2046
2047   ecl->labels = labels;
2048   ecl->equivalence_class = equivalence_class;
2049   ecl->hashcode = bitmap_hash (labels);
2050
2051   slot = htab_find_slot_with_hash (table, ecl,
2052                                    ecl->hashcode, INSERT);
2053   gcc_assert (!*slot);
2054   *slot = (void *) ecl;
2055 }
2056
2057 /* Perform offline variable substitution.
2058
2059    This is a worst case quadratic time way of identifying variables
2060    that must have equivalent points-to sets, including those caused by
2061    static cycles, and single entry subgraphs, in the constraint graph.
2062
2063    The technique is described in "Exploiting Pointer and Location
2064    Equivalence to Optimize Pointer Analysis. In the 14th International
2065    Static Analysis Symposium (SAS), August 2007."  It is known as the
2066    "HU" algorithm, and is equivalent to value numbering the collapsed
2067    constraint graph including evaluating unions.
2068
2069    The general method of finding equivalence classes is as follows:
2070    Add fake nodes (REF nodes) and edges for *a = b and a = *b constraints.
2071    Initialize all non-REF nodes to be direct nodes.
2072    For each constraint a = a U {b}, we set pts(a) = pts(a) u {fresh
2073    variable}
2074    For each constraint containing the dereference, we also do the same
2075    thing.
2076
2077    We then compute SCC's in the graph and unify nodes in the same SCC,
2078    including pts sets.
2079
2080    For each non-collapsed node x:
2081     Visit all unvisited explicit incoming edges.
2082     Ignoring all non-pointers, set pts(x) = Union of pts(a) for y
2083     where y->x.
2084     Lookup the equivalence class for pts(x).
2085      If we found one, equivalence_class(x) = found class.
2086      Otherwise, equivalence_class(x) = new class, and new_class is
2087     added to the lookup table.
2088
2089    All direct nodes with the same equivalence class can be replaced
2090    with a single representative node.
2091    All unlabeled nodes (label == 0) are not pointers and all edges
2092    involving them can be eliminated.
2093    We perform these optimizations during rewrite_constraints
2094
2095    In addition to pointer equivalence class finding, we also perform
2096    location equivalence class finding.  This is the set of variables
2097    that always appear together in points-to sets.  We use this to
2098    compress the size of the points-to sets.  */
2099
2100 /* Current maximum pointer equivalence class id.  */
2101 static int pointer_equiv_class;
2102
2103 /* Current maximum location equivalence class id.  */
2104 static int location_equiv_class;
2105
2106 /* Recursive routine to find strongly connected components in GRAPH,
2107    and label it's nodes with DFS numbers.  */
2108
2109 static void
2110 condense_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
2111 {
2112   unsigned int i;
2113   bitmap_iterator bi;
2114   unsigned int my_dfs;
2115
2116   gcc_assert (si->node_mapping[n] == n);
2117   SET_BIT (si->visited, n);
2118   si->dfs[n] = si->current_index ++;
2119   my_dfs = si->dfs[n];
2120
2121   /* Visit all the successors.  */
2122   EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
2123     {
2124       unsigned int w = si->node_mapping[i];
2125
2126       if (TEST_BIT (si->deleted, w))
2127         continue;
2128
2129       if (!TEST_BIT (si->visited, w))
2130         condense_visit (graph, si, w);
2131       {
2132         unsigned int t = si->node_mapping[w];
2133         unsigned int nnode = si->node_mapping[n];
2134         gcc_assert (nnode == n);
2135
2136         if (si->dfs[t] < si->dfs[nnode])
2137           si->dfs[n] = si->dfs[t];
2138       }
2139     }
2140
2141   /* Visit all the implicit predecessors.  */
2142   EXECUTE_IF_IN_NONNULL_BITMAP (graph->implicit_preds[n], 0, i, bi)
2143     {
2144       unsigned int w = si->node_mapping[i];
2145
2146       if (TEST_BIT (si->deleted, w))
2147         continue;
2148
2149       if (!TEST_BIT (si->visited, w))
2150         condense_visit (graph, si, w);
2151       {
2152         unsigned int t = si->node_mapping[w];
2153         unsigned int nnode = si->node_mapping[n];
2154         gcc_assert (nnode == n);
2155
2156         if (si->dfs[t] < si->dfs[nnode])
2157           si->dfs[n] = si->dfs[t];
2158       }
2159     }
2160
2161   /* See if any components have been identified.  */
2162   if (si->dfs[n] == my_dfs)
2163     {
2164       while (VEC_length (unsigned, si->scc_stack) != 0
2165              && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
2166         {
2167           unsigned int w = VEC_pop (unsigned, si->scc_stack);
2168           si->node_mapping[w] = n;
2169
2170           if (!TEST_BIT (graph->direct_nodes, w))
2171             RESET_BIT (graph->direct_nodes, n);
2172
2173           /* Unify our nodes.  */
2174           if (graph->preds[w])
2175             {
2176               if (!graph->preds[n])
2177                 graph->preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2178               bitmap_ior_into (graph->preds[n], graph->preds[w]);
2179             }
2180           if (graph->implicit_preds[w])
2181             {
2182               if (!graph->implicit_preds[n])
2183                 graph->implicit_preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2184               bitmap_ior_into (graph->implicit_preds[n],
2185                                graph->implicit_preds[w]);
2186             }
2187           if (graph->points_to[w])
2188             {
2189               if (!graph->points_to[n])
2190                 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2191               bitmap_ior_into (graph->points_to[n],
2192                                graph->points_to[w]);
2193             }
2194         }
2195       SET_BIT (si->deleted, n);
2196     }
2197   else
2198     VEC_safe_push (unsigned, heap, si->scc_stack, n);
2199 }
2200
2201 /* Label pointer equivalences.  */
2202
2203 static void
2204 label_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
2205 {
2206   unsigned int i;
2207   bitmap_iterator bi;
2208   SET_BIT (si->visited, n);
2209
2210   if (!graph->points_to[n])
2211     graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2212
2213   /* Label and union our incoming edges's points to sets.  */
2214   EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
2215     {
2216       unsigned int w = si->node_mapping[i];
2217       if (!TEST_BIT (si->visited, w))
2218         label_visit (graph, si, w);
2219
2220       /* Skip unused edges  */
2221       if (w == n || graph->pointer_label[w] == 0)
2222         continue;
2223
2224       if (graph->points_to[w])
2225         bitmap_ior_into(graph->points_to[n], graph->points_to[w]);
2226     }
2227   /* Indirect nodes get fresh variables.  */
2228   if (!TEST_BIT (graph->direct_nodes, n))
2229     bitmap_set_bit (graph->points_to[n], FIRST_REF_NODE + n);
2230
2231   if (!bitmap_empty_p (graph->points_to[n]))
2232     {
2233       unsigned int label = equiv_class_lookup (pointer_equiv_class_table,
2234                                                graph->points_to[n]);
2235       if (!label)
2236         {
2237           label = pointer_equiv_class++;
2238           equiv_class_add (pointer_equiv_class_table,
2239                            label, graph->points_to[n]);
2240         }
2241       graph->pointer_label[n] = label;
2242     }
2243 }
2244
2245 /* Perform offline variable substitution, discovering equivalence
2246    classes, and eliminating non-pointer variables.  */
2247
2248 static struct scc_info *
2249 perform_var_substitution (constraint_graph_t graph)
2250 {
2251   unsigned int i;
2252   unsigned int size = graph->size;
2253   struct scc_info *si = init_scc_info (size);
2254
2255   bitmap_obstack_initialize (&iteration_obstack);
2256   pointer_equiv_class_table = htab_create (511, equiv_class_label_hash,
2257                                            equiv_class_label_eq, free);
2258   location_equiv_class_table = htab_create (511, equiv_class_label_hash,
2259                                             equiv_class_label_eq, free);
2260   pointer_equiv_class = 1;
2261   location_equiv_class = 1;
2262
2263   /* Condense the nodes, which means to find SCC's, count incoming
2264      predecessors, and unite nodes in SCC's.  */
2265   for (i = 0; i < FIRST_REF_NODE; i++)
2266     if (!TEST_BIT (si->visited, si->node_mapping[i]))
2267       condense_visit (graph, si, si->node_mapping[i]);
2268
2269   sbitmap_zero (si->visited);
2270   /* Actually the label the nodes for pointer equivalences  */
2271   for (i = 0; i < FIRST_REF_NODE; i++)
2272     if (!TEST_BIT (si->visited, si->node_mapping[i]))
2273       label_visit (graph, si, si->node_mapping[i]);
2274
2275   /* Calculate location equivalence labels.  */
2276   for (i = 0; i < FIRST_REF_NODE; i++)
2277     {
2278       bitmap pointed_by;
2279       bitmap_iterator bi;
2280       unsigned int j;
2281       unsigned int label;
2282
2283       if (!graph->pointed_by[i])
2284         continue;
2285       pointed_by = BITMAP_ALLOC (&iteration_obstack);
2286
2287       /* Translate the pointed-by mapping for pointer equivalence
2288          labels.  */
2289       EXECUTE_IF_SET_IN_BITMAP (graph->pointed_by[i], 0, j, bi)
2290         {
2291           bitmap_set_bit (pointed_by,
2292                           graph->pointer_label[si->node_mapping[j]]);
2293         }
2294       /* The original pointed_by is now dead.  */
2295       BITMAP_FREE (graph->pointed_by[i]);
2296
2297       /* Look up the location equivalence label if one exists, or make
2298          one otherwise.  */
2299       label = equiv_class_lookup (location_equiv_class_table,
2300                                   pointed_by);
2301       if (label == 0)
2302         {
2303           label = location_equiv_class++;
2304           equiv_class_add (location_equiv_class_table,
2305                            label, pointed_by);
2306         }
2307       else
2308         {
2309           if (dump_file && (dump_flags & TDF_DETAILS))
2310             fprintf (dump_file, "Found location equivalence for node %s\n",
2311                      get_varinfo (i)->name);
2312           BITMAP_FREE (pointed_by);
2313         }
2314       graph->loc_label[i] = label;
2315
2316     }
2317
2318   if (dump_file && (dump_flags & TDF_DETAILS))
2319     for (i = 0; i < FIRST_REF_NODE; i++)
2320       {
2321         bool direct_node = TEST_BIT (graph->direct_nodes, i);
2322         fprintf (dump_file,
2323                  "Equivalence classes for %s node id %d:%s are pointer: %d"
2324                  ", location:%d\n",
2325                  direct_node ? "Direct node" : "Indirect node", i,
2326                  get_varinfo (i)->name,
2327                  graph->pointer_label[si->node_mapping[i]],
2328                  graph->loc_label[si->node_mapping[i]]);
2329       }
2330
2331   /* Quickly eliminate our non-pointer variables.  */
2332
2333   for (i = 0; i < FIRST_REF_NODE; i++)
2334     {
2335       unsigned int node = si->node_mapping[i];
2336
2337       if (graph->pointer_label[node] == 0)
2338         {
2339           if (dump_file && (dump_flags & TDF_DETAILS))
2340             fprintf (dump_file,
2341                      "%s is a non-pointer variable, eliminating edges.\n",
2342                      get_varinfo (node)->name);
2343           stats.nonpointer_vars++;
2344           clear_edges_for_node (graph, node);
2345         }
2346     }
2347
2348   return si;
2349 }
2350
2351 /* Free information that was only necessary for variable
2352    substitution.  */
2353
2354 static void
2355 free_var_substitution_info (struct scc_info *si)
2356 {
2357   free_scc_info (si);
2358   free (graph->pointer_label);
2359   free (graph->loc_label);
2360   free (graph->pointed_by);
2361   free (graph->points_to);
2362   free (graph->eq_rep);
2363   sbitmap_free (graph->direct_nodes);
2364   htab_delete (pointer_equiv_class_table);
2365   htab_delete (location_equiv_class_table);
2366   bitmap_obstack_release (&iteration_obstack);
2367 }
2368
2369 /* Return an existing node that is equivalent to NODE, which has
2370    equivalence class LABEL, if one exists.  Return NODE otherwise.  */
2371
2372 static unsigned int
2373 find_equivalent_node (constraint_graph_t graph,
2374                       unsigned int node, unsigned int label)
2375 {
2376   /* If the address version of this variable is unused, we can
2377      substitute it for anything else with the same label.
2378      Otherwise, we know the pointers are equivalent, but not the
2379      locations, and we can unite them later.  */
2380
2381   if (!bitmap_bit_p (graph->address_taken, node))
2382     {
2383       gcc_assert (label < graph->size);
2384
2385       if (graph->eq_rep[label] != -1)
2386         {
2387           /* Unify the two variables since we know they are equivalent.  */
2388           if (unite (graph->eq_rep[label], node))
2389             unify_nodes (graph, graph->eq_rep[label], node, false);
2390           return graph->eq_rep[label];
2391         }
2392       else
2393         {
2394           graph->eq_rep[label] = node;
2395           graph->pe_rep[label] = node;
2396         }
2397     }
2398   else
2399     {
2400       gcc_assert (label < graph->size);
2401       graph->pe[node] = label;
2402       if (graph->pe_rep[label] == -1)
2403         graph->pe_rep[label] = node;
2404     }
2405
2406   return node;
2407 }
2408
2409 /* Unite pointer equivalent but not location equivalent nodes in
2410    GRAPH.  This may only be performed once variable substitution is
2411    finished.  */
2412
2413 static void
2414 unite_pointer_equivalences (constraint_graph_t graph)
2415 {
2416   unsigned int i;
2417
2418   /* Go through the pointer equivalences and unite them to their
2419      representative, if they aren't already.  */
2420   for (i = 0; i < FIRST_REF_NODE; i++)
2421     {
2422       unsigned int label = graph->pe[i];
2423       if (label)
2424         {
2425           int label_rep = graph->pe_rep[label];
2426
2427           if (label_rep == -1)
2428             continue;
2429
2430           label_rep = find (label_rep);
2431           if (label_rep >= 0 && unite (label_rep, find (i)))
2432             unify_nodes (graph, label_rep, i, false);
2433         }
2434     }
2435 }
2436
2437 /* Move complex constraints to the GRAPH nodes they belong to.  */
2438
2439 static void
2440 move_complex_constraints (constraint_graph_t graph)
2441 {
2442   int i;
2443   constraint_t c;
2444
2445   FOR_EACH_VEC_ELT (constraint_t, constraints, i, c)
2446     {
2447       if (c)
2448         {
2449           struct constraint_expr lhs = c->lhs;
2450           struct constraint_expr rhs = c->rhs;
2451
2452           if (lhs.type == DEREF)
2453             {
2454               insert_into_complex (graph, lhs.var, c);
2455             }
2456           else if (rhs.type == DEREF)
2457             {
2458               if (!(get_varinfo (lhs.var)->is_special_var))
2459                 insert_into_complex (graph, rhs.var, c);
2460             }
2461           else if (rhs.type != ADDRESSOF && lhs.var > anything_id
2462                    && (lhs.offset != 0 || rhs.offset != 0))
2463             {
2464               insert_into_complex (graph, rhs.var, c);
2465             }
2466         }
2467     }
2468 }
2469
2470
2471 /* Optimize and rewrite complex constraints while performing
2472    collapsing of equivalent nodes.  SI is the SCC_INFO that is the
2473    result of perform_variable_substitution.  */
2474
2475 static void
2476 rewrite_constraints (constraint_graph_t graph,
2477                      struct scc_info *si)
2478 {
2479   int i;
2480   unsigned int j;
2481   constraint_t c;
2482
2483   for (j = 0; j < graph->size; j++)
2484     gcc_assert (find (j) == j);
2485
2486   FOR_EACH_VEC_ELT (constraint_t, constraints, i, c)
2487     {
2488       struct constraint_expr lhs = c->lhs;
2489       struct constraint_expr rhs = c->rhs;
2490       unsigned int lhsvar = find (lhs.var);
2491       unsigned int rhsvar = find (rhs.var);
2492       unsigned int lhsnode, rhsnode;
2493       unsigned int lhslabel, rhslabel;
2494
2495       lhsnode = si->node_mapping[lhsvar];
2496       rhsnode = si->node_mapping[rhsvar];
2497       lhslabel = graph->pointer_label[lhsnode];
2498       rhslabel = graph->pointer_label[rhsnode];
2499
2500       /* See if it is really a non-pointer variable, and if so, ignore
2501          the constraint.  */
2502       if (lhslabel == 0)
2503         {
2504           if (dump_file && (dump_flags & TDF_DETAILS))
2505             {
2506
2507               fprintf (dump_file, "%s is a non-pointer variable,"
2508                        "ignoring constraint:",
2509                        get_varinfo (lhs.var)->name);
2510               dump_constraint (dump_file, c);
2511             }
2512           VEC_replace (constraint_t, constraints, i, NULL);
2513           continue;
2514         }
2515
2516       if (rhslabel == 0)
2517         {
2518           if (dump_file && (dump_flags & TDF_DETAILS))
2519             {
2520
2521               fprintf (dump_file, "%s is a non-pointer variable,"
2522                        "ignoring constraint:",
2523                        get_varinfo (rhs.var)->name);
2524               dump_constraint (dump_file, c);
2525             }
2526           VEC_replace (constraint_t, constraints, i, NULL);
2527           continue;
2528         }
2529
2530       lhsvar = find_equivalent_node (graph, lhsvar, lhslabel);
2531       rhsvar = find_equivalent_node (graph, rhsvar, rhslabel);
2532       c->lhs.var = lhsvar;
2533       c->rhs.var = rhsvar;
2534
2535     }
2536 }
2537
2538 /* Eliminate indirect cycles involving NODE.  Return true if NODE was
2539    part of an SCC, false otherwise.  */
2540
2541 static bool
2542 eliminate_indirect_cycles (unsigned int node)
2543 {
2544   if (graph->indirect_cycles[node] != -1
2545       && !bitmap_empty_p (get_varinfo (node)->solution))
2546     {
2547       unsigned int i;
2548       VEC(unsigned,heap) *queue = NULL;
2549       int queuepos;
2550       unsigned int to = find (graph->indirect_cycles[node]);
2551       bitmap_iterator bi;
2552
2553       /* We can't touch the solution set and call unify_nodes
2554          at the same time, because unify_nodes is going to do
2555          bitmap unions into it. */
2556
2557       EXECUTE_IF_SET_IN_BITMAP (get_varinfo (node)->solution, 0, i, bi)
2558         {
2559           if (find (i) == i && i != to)
2560             {
2561               if (unite (to, i))
2562                 VEC_safe_push (unsigned, heap, queue, i);
2563             }
2564         }
2565
2566       for (queuepos = 0;
2567            VEC_iterate (unsigned, queue, queuepos, i);
2568            queuepos++)
2569         {
2570           unify_nodes (graph, to, i, true);
2571         }
2572       VEC_free (unsigned, heap, queue);
2573       return true;
2574     }
2575   return false;
2576 }
2577
2578 /* Solve the constraint graph GRAPH using our worklist solver.
2579    This is based on the PW* family of solvers from the "Efficient Field
2580    Sensitive Pointer Analysis for C" paper.
2581    It works by iterating over all the graph nodes, processing the complex
2582    constraints and propagating the copy constraints, until everything stops
2583    changed.  This corresponds to steps 6-8 in the solving list given above.  */
2584
2585 static void
2586 solve_graph (constraint_graph_t graph)
2587 {
2588   unsigned int size = graph->size;
2589   unsigned int i;
2590   bitmap pts;
2591
2592   changed_count = 0;
2593   changed = sbitmap_alloc (size);
2594   sbitmap_zero (changed);
2595
2596   /* Mark all initial non-collapsed nodes as changed.  */
2597   for (i = 0; i < size; i++)
2598     {
2599       varinfo_t ivi = get_varinfo (i);
2600       if (find (i) == i && !bitmap_empty_p (ivi->solution)
2601           && ((graph->succs[i] && !bitmap_empty_p (graph->succs[i]))
2602               || VEC_length (constraint_t, graph->complex[i]) > 0))
2603         {
2604           SET_BIT (changed, i);
2605           changed_count++;
2606         }
2607     }
2608
2609   /* Allocate a bitmap to be used to store the changed bits.  */
2610   pts = BITMAP_ALLOC (&pta_obstack);
2611
2612   while (changed_count > 0)
2613     {
2614       unsigned int i;
2615       struct topo_info *ti = init_topo_info ();
2616       stats.iterations++;
2617
2618       bitmap_obstack_initialize (&iteration_obstack);
2619
2620       compute_topo_order (graph, ti);
2621
2622       while (VEC_length (unsigned, ti->topo_order) != 0)
2623         {
2624
2625           i = VEC_pop (unsigned, ti->topo_order);
2626
2627           /* If this variable is not a representative, skip it.  */
2628           if (find (i) != i)
2629             continue;
2630
2631           /* In certain indirect cycle cases, we may merge this
2632              variable to another.  */
2633           if (eliminate_indirect_cycles (i) && find (i) != i)
2634             continue;
2635
2636           /* If the node has changed, we need to process the
2637              complex constraints and outgoing edges again.  */
2638           if (TEST_BIT (changed, i))
2639             {
2640               unsigned int j;
2641               constraint_t c;
2642               bitmap solution;
2643               VEC(constraint_t,heap) *complex = graph->complex[i];
2644               bool solution_empty;
2645
2646               RESET_BIT (changed, i);
2647               changed_count--;
2648
2649               /* Compute the changed set of solution bits.  */
2650               bitmap_and_compl (pts, get_varinfo (i)->solution,
2651                                 get_varinfo (i)->oldsolution);
2652
2653               if (bitmap_empty_p (pts))
2654                 continue;
2655
2656               bitmap_ior_into (get_varinfo (i)->oldsolution, pts);
2657
2658               solution = get_varinfo (i)->solution;
2659               solution_empty = bitmap_empty_p (solution);
2660
2661               /* Process the complex constraints */
2662               FOR_EACH_VEC_ELT (constraint_t, complex, j, c)
2663                 {
2664                   /* XXX: This is going to unsort the constraints in
2665                      some cases, which will occasionally add duplicate
2666                      constraints during unification.  This does not
2667                      affect correctness.  */
2668                   c->lhs.var = find (c->lhs.var);
2669                   c->rhs.var = find (c->rhs.var);
2670
2671                   /* The only complex constraint that can change our
2672                      solution to non-empty, given an empty solution,
2673                      is a constraint where the lhs side is receiving
2674                      some set from elsewhere.  */
2675                   if (!solution_empty || c->lhs.type != DEREF)
2676                     do_complex_constraint (graph, c, pts);
2677                 }
2678
2679               solution_empty = bitmap_empty_p (solution);
2680
2681               if (!solution_empty)
2682                 {
2683                   bitmap_iterator bi;
2684                   unsigned eff_escaped_id = find (escaped_id);
2685
2686                   /* Propagate solution to all successors.  */
2687                   EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i],
2688                                                 0, j, bi)
2689                     {
2690                       bitmap tmp;
2691                       bool flag;
2692
2693                       unsigned int to = find (j);
2694                       tmp = get_varinfo (to)->solution;
2695                       flag = false;
2696
2697                       /* Don't try to propagate to ourselves.  */
2698                       if (to == i)
2699                         continue;
2700
2701                       /* If we propagate from ESCAPED use ESCAPED as
2702                          placeholder.  */
2703                       if (i == eff_escaped_id)
2704                         flag = bitmap_set_bit (tmp, escaped_id);
2705                       else
2706                         flag = set_union_with_increment (tmp, pts, 0);
2707
2708                       if (flag)
2709                         {
2710                           get_varinfo (to)->solution = tmp;
2711                           if (!TEST_BIT (changed, to))
2712                             {
2713                               SET_BIT (changed, to);
2714                               changed_count++;
2715                             }
2716                         }
2717                     }
2718                 }
2719             }
2720         }
2721       free_topo_info (ti);
2722       bitmap_obstack_release (&iteration_obstack);
2723     }
2724
2725   BITMAP_FREE (pts);
2726   sbitmap_free (changed);
2727   bitmap_obstack_release (&oldpta_obstack);
2728 }
2729
2730 /* Map from trees to variable infos.  */
2731 static struct pointer_map_t *vi_for_tree;
2732
2733
2734 /* Insert ID as the variable id for tree T in the vi_for_tree map.  */
2735
2736 static void
2737 insert_vi_for_tree (tree t, varinfo_t vi)
2738 {
2739   void **slot = pointer_map_insert (vi_for_tree, t);
2740   gcc_assert (vi);
2741   gcc_assert (*slot == NULL);
2742   *slot = vi;
2743 }
2744
2745 /* Find the variable info for tree T in VI_FOR_TREE.  If T does not
2746    exist in the map, return NULL, otherwise, return the varinfo we found.  */
2747
2748 static varinfo_t
2749 lookup_vi_for_tree (tree t)
2750 {
2751   void **slot = pointer_map_contains (vi_for_tree, t);
2752   if (slot == NULL)
2753     return NULL;
2754
2755   return (varinfo_t) *slot;
2756 }
2757
2758 /* Return a printable name for DECL  */
2759
2760 static const char *
2761 alias_get_name (tree decl)
2762 {
2763   const char *res;
2764   char *temp;
2765   int num_printed = 0;
2766
2767   if (DECL_ASSEMBLER_NAME_SET_P (decl))
2768     res = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));
2769   else
2770     res= get_name (decl);
2771   if (res != NULL)
2772     return res;
2773
2774   res = "NULL";
2775   if (!dump_file)
2776     return res;
2777
2778   if (TREE_CODE (decl) == SSA_NAME)
2779     {
2780       num_printed = asprintf (&temp, "%s_%u",
2781                               alias_get_name (SSA_NAME_VAR (decl)),
2782                               SSA_NAME_VERSION (decl));
2783     }
2784   else if (DECL_P (decl))
2785     {
2786       num_printed = asprintf (&temp, "D.%u", DECL_UID (decl));
2787     }
2788   if (num_printed > 0)
2789     {
2790       res = ggc_strdup (temp);
2791       free (temp);
2792     }
2793   return res;
2794 }
2795
2796 /* Find the variable id for tree T in the map.
2797    If T doesn't exist in the map, create an entry for it and return it.  */
2798
2799 static varinfo_t
2800 get_vi_for_tree (tree t)
2801 {
2802   void **slot = pointer_map_contains (vi_for_tree, t);
2803   if (slot == NULL)
2804     return get_varinfo (create_variable_info_for (t, alias_get_name (t)));
2805
2806   return (varinfo_t) *slot;
2807 }
2808
2809 /* Get a scalar constraint expression for a new temporary variable.  */
2810
2811 static struct constraint_expr
2812 new_scalar_tmp_constraint_exp (const char *name)
2813 {
2814   struct constraint_expr tmp;
2815   varinfo_t vi;
2816
2817   vi = new_var_info (NULL_TREE, name);
2818   vi->offset = 0;
2819   vi->size = -1;
2820   vi->fullsize = -1;
2821   vi->is_full_var = 1;
2822
2823   tmp.var = vi->id;
2824   tmp.type = SCALAR;
2825   tmp.offset = 0;
2826
2827   return tmp;
2828 }
2829
2830 /* Get a constraint expression vector from an SSA_VAR_P node.
2831    If address_p is true, the result will be taken its address of.  */
2832
2833 static void
2834 get_constraint_for_ssa_var (tree t, VEC(ce_s, heap) **results, bool address_p)
2835 {
2836   struct constraint_expr cexpr;
2837   varinfo_t vi;
2838
2839   /* We allow FUNCTION_DECLs here even though it doesn't make much sense.  */
2840   gcc_assert (SSA_VAR_P (t) || DECL_P (t));
2841
2842   /* For parameters, get at the points-to set for the actual parm
2843      decl.  */
2844   if (TREE_CODE (t) == SSA_NAME
2845       && (TREE_CODE (SSA_NAME_VAR (t)) == PARM_DECL
2846           || TREE_CODE (SSA_NAME_VAR (t)) == RESULT_DECL)
2847       && SSA_NAME_IS_DEFAULT_DEF (t))
2848     {
2849       get_constraint_for_ssa_var (SSA_NAME_VAR (t), results, address_p);
2850       return;
2851     }
2852
2853   vi = get_vi_for_tree (t);
2854   cexpr.var = vi->id;
2855   cexpr.type = SCALAR;
2856   cexpr.offset = 0;
2857   /* If we determine the result is "anything", and we know this is readonly,
2858      say it points to readonly memory instead.  */
2859   if (cexpr.var == anything_id && TREE_READONLY (t))
2860     {
2861       gcc_unreachable ();
2862       cexpr.type = ADDRESSOF;
2863       cexpr.var = readonly_id;
2864     }
2865
2866   /* If we are not taking the address of the constraint expr, add all
2867      sub-fiels of the variable as well.  */
2868   if (!address_p
2869       && !vi->is_full_var)
2870     {
2871       for (; vi; vi = vi->next)
2872         {
2873           cexpr.var = vi->id;
2874           VEC_safe_push (ce_s, heap, *results, &cexpr);
2875         }
2876       return;
2877     }
2878
2879   VEC_safe_push (ce_s, heap, *results, &cexpr);
2880 }
2881
2882 /* Process constraint T, performing various simplifications and then
2883    adding it to our list of overall constraints.  */
2884
2885 static void
2886 process_constraint (constraint_t t)
2887 {
2888   struct constraint_expr rhs = t->rhs;
2889   struct constraint_expr lhs = t->lhs;
2890
2891   gcc_assert (rhs.var < VEC_length (varinfo_t, varmap));
2892   gcc_assert (lhs.var < VEC_length (varinfo_t, varmap));
2893
2894   /* If we didn't get any useful constraint from the lhs we get
2895      &ANYTHING as fallback from get_constraint_for.  Deal with
2896      it here by turning it into *ANYTHING.  */
2897   if (lhs.type == ADDRESSOF
2898       && lhs.var == anything_id)
2899     lhs.type = DEREF;
2900
2901   /* ADDRESSOF on the lhs is invalid.  */
2902   gcc_assert (lhs.type != ADDRESSOF);
2903
2904   /* We shouldn't add constraints from things that cannot have pointers.
2905      It's not completely trivial to avoid in the callers, so do it here.  */
2906   if (rhs.type != ADDRESSOF
2907       && !get_varinfo (rhs.var)->may_have_pointers)
2908     return;
2909
2910   /* Likewise adding to the solution of a non-pointer var isn't useful.  */
2911   if (!get_varinfo (lhs.var)->may_have_pointers)
2912     return;
2913
2914   /* This can happen in our IR with things like n->a = *p */
2915   if (rhs.type == DEREF && lhs.type == DEREF && rhs.var != anything_id)
2916     {
2917       /* Split into tmp = *rhs, *lhs = tmp */
2918       struct constraint_expr tmplhs;
2919       tmplhs = new_scalar_tmp_constraint_exp ("doubledereftmp");
2920       process_constraint (new_constraint (tmplhs, rhs));
2921       process_constraint (new_constraint (lhs, tmplhs));
2922     }
2923   else if (rhs.type == ADDRESSOF && lhs.type == DEREF)
2924     {
2925       /* Split into tmp = &rhs, *lhs = tmp */
2926       struct constraint_expr tmplhs;
2927       tmplhs = new_scalar_tmp_constraint_exp ("derefaddrtmp");
2928       process_constraint (new_constraint (tmplhs, rhs));
2929       process_constraint (new_constraint (lhs, tmplhs));
2930     }
2931   else
2932     {
2933       gcc_assert (rhs.type != ADDRESSOF || rhs.offset == 0);
2934       VEC_safe_push (constraint_t, heap, constraints, t);
2935     }
2936 }
2937
2938
2939 /* Return the position, in bits, of FIELD_DECL from the beginning of its
2940    structure.  */
2941
2942 static HOST_WIDE_INT
2943 bitpos_of_field (const tree fdecl)
2944 {
2945   if (!host_integerp (DECL_FIELD_OFFSET (fdecl), 0)
2946       || !host_integerp (DECL_FIELD_BIT_OFFSET (fdecl), 0))
2947     return -1;
2948
2949   return (TREE_INT_CST_LOW (DECL_FIELD_OFFSET (fdecl)) * BITS_PER_UNIT
2950           + TREE_INT_CST_LOW (DECL_FIELD_BIT_OFFSET (fdecl)));
2951 }
2952
2953
2954 /* Get constraint expressions for offsetting PTR by OFFSET.  Stores the
2955    resulting constraint expressions in *RESULTS.  */
2956
2957 static void
2958 get_constraint_for_ptr_offset (tree ptr, tree offset,
2959                                VEC (ce_s, heap) **results)
2960 {
2961   struct constraint_expr c;
2962   unsigned int j, n;
2963   HOST_WIDE_INT rhsunitoffset, rhsoffset;
2964
2965   /* If we do not do field-sensitive PTA adding offsets to pointers
2966      does not change the points-to solution.  */
2967   if (!use_field_sensitive)
2968     {
2969       get_constraint_for_rhs (ptr, results);
2970       return;
2971     }
2972
2973   /* If the offset is not a non-negative integer constant that fits
2974      in a HOST_WIDE_INT, we have to fall back to a conservative
2975      solution which includes all sub-fields of all pointed-to
2976      variables of ptr.  */
2977   if (offset == NULL_TREE
2978       || !host_integerp (offset, 0))
2979     rhsoffset = UNKNOWN_OFFSET;
2980   else
2981     {
2982       /* Make sure the bit-offset also fits.  */
2983       rhsunitoffset = TREE_INT_CST_LOW (offset);
2984       rhsoffset = rhsunitoffset * BITS_PER_UNIT;
2985       if (rhsunitoffset != rhsoffset / BITS_PER_UNIT)
2986         rhsoffset = UNKNOWN_OFFSET;
2987     }
2988
2989   get_constraint_for_rhs (ptr, results);
2990   if (rhsoffset == 0)
2991     return;
2992
2993   /* As we are eventually appending to the solution do not use
2994      VEC_iterate here.  */
2995   n = VEC_length (ce_s, *results);
2996   for (j = 0; j < n; j++)
2997     {
2998       varinfo_t curr;
2999       c = *VEC_index (ce_s, *results, j);
3000       curr = get_varinfo (c.var);
3001
3002       if (c.type == ADDRESSOF
3003           /* If this varinfo represents a full variable just use it.  */
3004           && curr->is_full_var)
3005         c.offset = 0;
3006       else if (c.type == ADDRESSOF
3007                /* If we do not know the offset add all subfields.  */
3008                && rhsoffset == UNKNOWN_OFFSET)
3009         {
3010           varinfo_t temp = lookup_vi_for_tree (curr->decl);
3011           do
3012             {
3013               struct constraint_expr c2;
3014               c2.var = temp->id;
3015               c2.type = ADDRESSOF;
3016               c2.offset = 0;
3017               if (c2.var != c.var)
3018                 VEC_safe_push (ce_s, heap, *results, &c2);
3019               temp = temp->next;
3020             }
3021           while (temp);
3022         }
3023       else if (c.type == ADDRESSOF)
3024         {
3025           varinfo_t temp;
3026           unsigned HOST_WIDE_INT offset = curr->offset + rhsoffset;
3027
3028           /* Search the sub-field which overlaps with the
3029              pointed-to offset.  If the result is outside of the variable
3030              we have to provide a conservative result, as the variable is
3031              still reachable from the resulting pointer (even though it
3032              technically cannot point to anything).  The last and first
3033              sub-fields are such conservative results.
3034              ???  If we always had a sub-field for &object + 1 then
3035              we could represent this in a more precise way.  */
3036           if (rhsoffset < 0
3037               && curr->offset < offset)
3038             offset = 0;
3039           temp = first_or_preceding_vi_for_offset (curr, offset);
3040
3041           /* If the found variable is not exactly at the pointed to
3042              result, we have to include the next variable in the
3043              solution as well.  Otherwise two increments by offset / 2
3044              do not result in the same or a conservative superset
3045              solution.  */
3046           if (temp->offset != offset
3047               && temp->next != NULL)
3048             {
3049               struct constraint_expr c2;
3050               c2.var = temp->next->id;
3051               c2.type = ADDRESSOF;
3052               c2.offset = 0;
3053               VEC_safe_push (ce_s, heap, *results, &c2);
3054             }
3055           c.var = temp->id;
3056           c.offset = 0;
3057         }
3058       else
3059         c.offset = rhsoffset;
3060
3061       VEC_replace (ce_s, *results, j, &c);
3062     }
3063 }
3064
3065
3066 /* Given a COMPONENT_REF T, return the constraint_expr vector for it.
3067    If address_p is true the result will be taken its address of.
3068    If lhs_p is true then the constraint expression is assumed to be used
3069    as the lhs.  */
3070
3071 static void
3072 get_constraint_for_component_ref (tree t, VEC(ce_s, heap) **results,
3073                                   bool address_p, bool lhs_p)
3074 {
3075   tree orig_t = t;
3076   HOST_WIDE_INT bitsize = -1;
3077   HOST_WIDE_INT bitmaxsize = -1;
3078   HOST_WIDE_INT bitpos;
3079   tree forzero;
3080   struct constraint_expr *result;
3081
3082   /* Some people like to do cute things like take the address of
3083      &0->a.b */
3084   forzero = t;
3085   while (handled_component_p (forzero)
3086          || INDIRECT_REF_P (forzero)
3087          || TREE_CODE (forzero) == MEM_REF)
3088     forzero = TREE_OPERAND (forzero, 0);
3089
3090   if (CONSTANT_CLASS_P (forzero) && integer_zerop (forzero))
3091     {
3092       struct constraint_expr temp;
3093
3094       temp.offset = 0;
3095       temp.var = integer_id;
3096       temp.type = SCALAR;
3097       VEC_safe_push (ce_s, heap, *results, &temp);
3098       return;
3099     }
3100
3101   /* Handle type-punning through unions.  If we are extracting a pointer
3102      from a union via a possibly type-punning access that pointer
3103      points to anything, similar to a conversion of an integer to
3104      a pointer.  */
3105   if (!lhs_p)
3106     {
3107       tree u;
3108       for (u = t;
3109            TREE_CODE (u) == COMPONENT_REF || TREE_CODE (u) == ARRAY_REF;
3110            u = TREE_OPERAND (u, 0))
3111         if (TREE_CODE (u) == COMPONENT_REF
3112             && TREE_CODE (TREE_TYPE (TREE_OPERAND (u, 0))) == UNION_TYPE)
3113           {
3114             struct constraint_expr temp;
3115
3116             temp.offset = 0;
3117             temp.var = anything_id;
3118             temp.type = ADDRESSOF;
3119             VEC_safe_push (ce_s, heap, *results, &temp);
3120             return;
3121           }
3122     }
3123
3124   t = get_ref_base_and_extent (t, &bitpos, &bitsize, &bitmaxsize);
3125
3126   /* Pretend to take the address of the base, we'll take care of
3127      adding the required subset of sub-fields below.  */
3128   get_constraint_for_1 (t, results, true, lhs_p);
3129   gcc_assert (VEC_length (ce_s, *results) == 1);
3130   result = VEC_last (ce_s, *results);
3131
3132   if (result->type == SCALAR
3133       && get_varinfo (result->var)->is_full_var)
3134     /* For single-field vars do not bother about the offset.  */
3135     result->offset = 0;
3136   else if (result->type == SCALAR)
3137     {
3138       /* In languages like C, you can access one past the end of an
3139          array.  You aren't allowed to dereference it, so we can
3140          ignore this constraint. When we handle pointer subtraction,
3141          we may have to do something cute here.  */
3142
3143       if ((unsigned HOST_WIDE_INT)bitpos < get_varinfo (result->var)->fullsize
3144           && bitmaxsize != 0)
3145         {
3146           /* It's also not true that the constraint will actually start at the
3147              right offset, it may start in some padding.  We only care about
3148              setting the constraint to the first actual field it touches, so
3149              walk to find it.  */
3150           struct constraint_expr cexpr = *result;
3151           varinfo_t curr;
3152           VEC_pop (ce_s, *results);
3153           cexpr.offset = 0;
3154           for (curr = get_varinfo (cexpr.var); curr; curr = curr->next)
3155             {
3156               if (ranges_overlap_p (curr->offset, curr->size,
3157                                     bitpos, bitmaxsize))
3158                 {
3159                   cexpr.var = curr->id;
3160                   VEC_safe_push (ce_s, heap, *results, &cexpr);
3161                   if (address_p)
3162                     break;
3163                 }
3164             }
3165           /* If we are going to take the address of this field then
3166              to be able to compute reachability correctly add at least
3167              the last field of the variable.  */
3168           if (address_p
3169               && VEC_length (ce_s, *results) == 0)
3170             {
3171               curr = get_varinfo (cexpr.var);
3172               while (curr->next != NULL)
3173                 curr = curr->next;
3174               cexpr.var = curr->id;
3175               VEC_safe_push (ce_s, heap, *results, &cexpr);
3176             }
3177           else if (VEC_length (ce_s, *results) == 0)
3178             /* Assert that we found *some* field there. The user couldn't be
3179                accessing *only* padding.  */
3180             /* Still the user could access one past the end of an array
3181                embedded in a struct resulting in accessing *only* padding.  */
3182             /* Or accessing only padding via type-punning to a type
3183                that has a filed just in padding space.  */
3184             {
3185               cexpr.type = SCALAR;
3186               cexpr.var = anything_id;
3187               cexpr.offset = 0;
3188               VEC_safe_push (ce_s, heap, *results, &cexpr);
3189             }
3190         }
3191       else if (bitmaxsize == 0)
3192         {
3193           if (dump_file && (dump_flags & TDF_DETAILS))
3194             fprintf (dump_file, "Access to zero-sized part of variable,"
3195                      "ignoring\n");
3196         }
3197       else
3198         if (dump_file && (dump_flags & TDF_DETAILS))
3199           fprintf (dump_file, "Access to past the end of variable, ignoring\n");
3200     }
3201   else if (result->type == DEREF)
3202     {
3203       /* If we do not know exactly where the access goes say so.  Note
3204          that only for non-structure accesses we know that we access
3205          at most one subfiled of any variable.  */
3206       if (bitpos == -1
3207           || bitsize != bitmaxsize
3208           || AGGREGATE_TYPE_P (TREE_TYPE (orig_t))
3209           || result->offset == UNKNOWN_OFFSET)
3210         result->offset = UNKNOWN_OFFSET;
3211       else
3212         result->offset += bitpos;
3213     }
3214   else if (result->type == ADDRESSOF)
3215     {
3216       /* We can end up here for component references on a
3217          VIEW_CONVERT_EXPR <>(&foobar).  */
3218       result->type = SCALAR;
3219       result->var = anything_id;
3220       result->offset = 0;
3221     }
3222   else
3223     gcc_unreachable ();
3224 }
3225
3226
3227 /* Dereference the constraint expression CONS, and return the result.
3228    DEREF (ADDRESSOF) = SCALAR
3229    DEREF (SCALAR) = DEREF
3230    DEREF (DEREF) = (temp = DEREF1; result = DEREF(temp))
3231    This is needed so that we can handle dereferencing DEREF constraints.  */
3232
3233 static void
3234 do_deref (VEC (ce_s, heap) **constraints)
3235 {
3236   struct constraint_expr *c;
3237   unsigned int i = 0;
3238
3239   FOR_EACH_VEC_ELT (ce_s, *constraints, i, c)
3240     {
3241       if (c->type == SCALAR)
3242         c->type = DEREF;
3243       else if (c->type == ADDRESSOF)
3244         c->type = SCALAR;
3245       else if (c->type == DEREF)
3246         {
3247           struct constraint_expr tmplhs;
3248           tmplhs = new_scalar_tmp_constraint_exp ("dereftmp");
3249           process_constraint (new_constraint (tmplhs, *c));
3250           c->var = tmplhs.var;
3251         }
3252       else
3253         gcc_unreachable ();
3254     }
3255 }
3256
3257 /* Given a tree T, return the constraint expression for taking the
3258    address of it.  */
3259
3260 static void
3261 get_constraint_for_address_of (tree t, VEC (ce_s, heap) **results)
3262 {
3263   struct constraint_expr *c;
3264   unsigned int i;
3265
3266   get_constraint_for_1 (t, results, true, true);
3267
3268   FOR_EACH_VEC_ELT (ce_s, *results, i, c)
3269     {
3270       if (c->type == DEREF)
3271         c->type = SCALAR;
3272       else
3273         c->type = ADDRESSOF;
3274     }
3275 }
3276
3277 /* Given a tree T, return the constraint expression for it.  */
3278
3279 static void
3280 get_constraint_for_1 (tree t, VEC (ce_s, heap) **results, bool address_p,
3281                       bool lhs_p)
3282 {
3283   struct constraint_expr temp;
3284
3285   /* x = integer is all glommed to a single variable, which doesn't
3286      point to anything by itself.  That is, of course, unless it is an
3287      integer constant being treated as a pointer, in which case, we
3288      will return that this is really the addressof anything.  This
3289      happens below, since it will fall into the default case. The only
3290      case we know something about an integer treated like a pointer is
3291      when it is the NULL pointer, and then we just say it points to
3292      NULL.
3293
3294      Do not do that if -fno-delete-null-pointer-checks though, because
3295      in that case *NULL does not fail, so it _should_ alias *anything.
3296      It is not worth adding a new option or renaming the existing one,
3297      since this case is relatively obscure.  */
3298   if ((TREE_CODE (t) == INTEGER_CST
3299        && integer_zerop (t))
3300       /* The only valid CONSTRUCTORs in gimple with pointer typed
3301          elements are zero-initializer.  But in IPA mode we also
3302          process global initializers, so verify at least.  */
3303       || (TREE_CODE (t) == CONSTRUCTOR
3304           && CONSTRUCTOR_NELTS (t) == 0))
3305     {
3306       if (flag_delete_null_pointer_checks)
3307         temp.var = nothing_id;
3308       else
3309         temp.var = nonlocal_id;
3310       temp.type = ADDRESSOF;
3311       temp.offset = 0;
3312       VEC_safe_push (ce_s, heap, *results, &temp);
3313       return;
3314     }
3315
3316   /* String constants are read-only.  */
3317   if (TREE_CODE (t) == STRING_CST)
3318     {
3319       temp.var = readonly_id;
3320       temp.type = SCALAR;
3321       temp.offset = 0;
3322       VEC_safe_push (ce_s, heap, *results, &temp);
3323       return;
3324     }
3325
3326   switch (TREE_CODE_CLASS (TREE_CODE (t)))
3327     {
3328     case tcc_expression:
3329       {
3330         switch (TREE_CODE (t))
3331           {
3332           case ADDR_EXPR:
3333             get_constraint_for_address_of (TREE_OPERAND (t, 0), results);
3334             return;
3335           default:;
3336           }
3337         break;
3338       }
3339     case tcc_reference:
3340       {
3341         switch (TREE_CODE (t))
3342           {
3343           case MEM_REF:
3344             {
3345               struct constraint_expr cs;
3346               varinfo_t vi, curr;
3347               tree off = double_int_to_tree (sizetype, mem_ref_offset (t));
3348               get_constraint_for_ptr_offset (TREE_OPERAND (t, 0), off, results);
3349               do_deref (results);
3350
3351               /* If we are not taking the address then make sure to process
3352                  all subvariables we might access.  */
3353               if (address_p)
3354                 return;
3355
3356               cs = *VEC_last (ce_s, *results);
3357               if (cs.type == DEREF
3358                   && type_can_have_subvars (TREE_TYPE (t)))
3359                 {
3360                   /* For dereferences this means we have to defer it
3361                      to solving time.  */
3362                   VEC_last (ce_s, *results)->offset = UNKNOWN_OFFSET;
3363                   return;
3364                 }
3365               if (cs.type != SCALAR)
3366                 return;
3367
3368               vi = get_varinfo (cs.var);
3369               curr = vi->next;
3370               if (!vi->is_full_var
3371                   && curr)
3372                 {
3373                   unsigned HOST_WIDE_INT size;
3374                   if (host_integerp (TYPE_SIZE (TREE_TYPE (t)), 1))
3375                     size = TREE_INT_CST_LOW (TYPE_SIZE (TREE_TYPE (t)));
3376                   else
3377                     size = -1;
3378                   for (; curr; curr = curr->next)
3379                     {
3380                       if (curr->offset - vi->offset < size)
3381                         {
3382                           cs.var = curr->id;
3383                           VEC_safe_push (ce_s, heap, *results, &cs);
3384                         }
3385                       else
3386                         break;
3387                     }
3388                 }
3389               return;
3390             }
3391           case ARRAY_REF:
3392           case ARRAY_RANGE_REF:
3393           case COMPONENT_REF:
3394             get_constraint_for_component_ref (t, results, address_p, lhs_p);
3395             return;
3396           case VIEW_CONVERT_EXPR:
3397             get_constraint_for_1 (TREE_OPERAND (t, 0), results, address_p,
3398                                   lhs_p);
3399             return;
3400           /* We are missing handling for TARGET_MEM_REF here.  */
3401           default:;
3402           }
3403         break;
3404       }
3405     case tcc_exceptional:
3406       {
3407         switch (TREE_CODE (t))
3408           {
3409           case SSA_NAME:
3410             {
3411               get_constraint_for_ssa_var (t, results, address_p);
3412               return;
3413             }
3414           case CONSTRUCTOR:
3415             {
3416               unsigned int i;
3417               tree val;
3418               VEC (ce_s, heap) *tmp = NULL;
3419               FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (t), i, val)
3420                 {
3421                   struct constraint_expr *rhsp;
3422                   unsigned j;
3423                   get_constraint_for_1 (val, &tmp, address_p, lhs_p);
3424                   FOR_EACH_VEC_ELT (ce_s, tmp, j, rhsp)
3425                     VEC_safe_push (ce_s, heap, *results, rhsp);
3426                   VEC_truncate (ce_s, tmp, 0);
3427                 }
3428               VEC_free (ce_s, heap, tmp);
3429               /* We do not know whether the constructor was complete,
3430                  so technically we have to add &NOTHING or &ANYTHING
3431                  like we do for an empty constructor as well.  */
3432               return;
3433             }
3434           default:;
3435           }
3436         break;
3437       }
3438     case tcc_declaration:
3439       {
3440         get_constraint_for_ssa_var (t, results, address_p);
3441         return;
3442       }
3443     case tcc_constant:
3444       {
3445         /* We cannot refer to automatic variables through constants.  */ 
3446         temp.type = ADDRESSOF;
3447         temp.var = nonlocal_id;
3448         temp.offset = 0;
3449         VEC_safe_push (ce_s, heap, *results, &temp);
3450         return;
3451       }
3452     default:;
3453     }
3454
3455   /* The default fallback is a constraint from anything.  */
3456   temp.type = ADDRESSOF;
3457   temp.var = anything_id;
3458   temp.offset = 0;
3459   VEC_safe_push (ce_s, heap, *results, &temp);
3460 }
3461
3462 /* Given a gimple tree T, return the constraint expression vector for it.  */
3463
3464 static void
3465 get_constraint_for (tree t, VEC (ce_s, heap) **results)
3466 {
3467   gcc_assert (VEC_length (ce_s, *results) == 0);
3468
3469   get_constraint_for_1 (t, results, false, true);
3470 }
3471
3472 /* Given a gimple tree T, return the constraint expression vector for it
3473    to be used as the rhs of a constraint.  */
3474
3475 static void
3476 get_constraint_for_rhs (tree t, VEC (ce_s, heap) **results)
3477 {
3478   gcc_assert (VEC_length (ce_s, *results) == 0);
3479
3480   get_constraint_for_1 (t, results, false, false);
3481 }
3482
3483
3484 /* Efficiently generates constraints from all entries in *RHSC to all
3485    entries in *LHSC.  */
3486
3487 static void
3488 process_all_all_constraints (VEC (ce_s, heap) *lhsc, VEC (ce_s, heap) *rhsc)
3489 {
3490   struct constraint_expr *lhsp, *rhsp;
3491   unsigned i, j;
3492
3493   if (VEC_length (ce_s, lhsc) <= 1
3494       || VEC_length (ce_s, rhsc) <= 1)
3495     {
3496       FOR_EACH_VEC_ELT (ce_s, lhsc, i, lhsp)
3497         FOR_EACH_VEC_ELT (ce_s, rhsc, j, rhsp)
3498           process_constraint (new_constraint (*lhsp, *rhsp));
3499     }
3500   else
3501     {
3502       struct constraint_expr tmp;
3503       tmp = new_scalar_tmp_constraint_exp ("allalltmp");
3504       FOR_EACH_VEC_ELT (ce_s, rhsc, i, rhsp)
3505         process_constraint (new_constraint (tmp, *rhsp));
3506       FOR_EACH_VEC_ELT (ce_s, lhsc, i, lhsp)
3507         process_constraint (new_constraint (*lhsp, tmp));
3508     }
3509 }
3510
3511 /* Handle aggregate copies by expanding into copies of the respective
3512    fields of the structures.  */
3513
3514 static void
3515 do_structure_copy (tree lhsop, tree rhsop)
3516 {
3517   struct constraint_expr *lhsp, *rhsp;
3518   VEC (ce_s, heap) *lhsc = NULL, *rhsc = NULL;
3519   unsigned j;
3520
3521   get_constraint_for (lhsop, &lhsc);
3522   get_constraint_for_rhs (rhsop, &rhsc);
3523   lhsp = VEC_index (ce_s, lhsc, 0);
3524   rhsp = VEC_index (ce_s, rhsc, 0);
3525   if (lhsp->type == DEREF
3526       || (lhsp->type == ADDRESSOF && lhsp->var == anything_id)
3527       || rhsp->type == DEREF)
3528     {
3529       if (lhsp->type == DEREF)
3530         {
3531           gcc_assert (VEC_length (ce_s, lhsc) == 1);
3532           lhsp->offset = UNKNOWN_OFFSET;
3533         }
3534       if (rhsp->type == DEREF)
3535         {
3536           gcc_assert (VEC_length (ce_s, rhsc) == 1);
3537           rhsp->offset = UNKNOWN_OFFSET;
3538         }
3539       process_all_all_constraints (lhsc, rhsc);
3540     }
3541   else if (lhsp->type == SCALAR
3542            && (rhsp->type == SCALAR
3543                || rhsp->type == ADDRESSOF))
3544     {
3545       HOST_WIDE_INT lhssize, lhsmaxsize, lhsoffset;
3546       HOST_WIDE_INT rhssize, rhsmaxsize, rhsoffset;
3547       unsigned k = 0;
3548       get_ref_base_and_extent (lhsop, &lhsoffset, &lhssize, &lhsmaxsize);
3549       get_ref_base_and_extent (rhsop, &rhsoffset, &rhssize, &rhsmaxsize);
3550       for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp);)
3551         {
3552           varinfo_t lhsv, rhsv;
3553           rhsp = VEC_index (ce_s, rhsc, k);
3554           lhsv = get_varinfo (lhsp->var);
3555           rhsv = get_varinfo (rhsp->var);
3556           if (lhsv->may_have_pointers
3557               && (lhsv->is_full_var
3558                   || rhsv->is_full_var
3559                   || ranges_overlap_p (lhsv->offset + rhsoffset, lhsv->size,
3560                                        rhsv->offset + lhsoffset, rhsv->size)))
3561             process_constraint (new_constraint (*lhsp, *rhsp));
3562           if (!rhsv->is_full_var
3563               && (lhsv->is_full_var
3564                   || (lhsv->offset + rhsoffset + lhsv->size
3565                       > rhsv->offset + lhsoffset + rhsv->size)))
3566             {
3567               ++k;
3568               if (k >= VEC_length (ce_s, rhsc))
3569                 break;
3570             }
3571           else
3572             ++j;
3573         }
3574     }
3575   else
3576     gcc_unreachable ();
3577
3578   VEC_free (ce_s, heap, lhsc);
3579   VEC_free (ce_s, heap, rhsc);
3580 }
3581
3582 /* Create constraints ID = { rhsc }.  */
3583
3584 static void
3585 make_constraints_to (unsigned id, VEC(ce_s, heap) *rhsc)
3586 {
3587   struct constraint_expr *c;
3588   struct constraint_expr includes;
3589   unsigned int j;
3590
3591   includes.var = id;
3592   includes.offset = 0;
3593   includes.type = SCALAR;
3594
3595   FOR_EACH_VEC_ELT (ce_s, rhsc, j, c)
3596     process_constraint (new_constraint (includes, *c));
3597 }
3598
3599 /* Create a constraint ID = OP.  */
3600
3601 static void
3602 make_constraint_to (unsigned id, tree op)
3603 {
3604   VEC(ce_s, heap) *rhsc = NULL;
3605   get_constraint_for_rhs (op, &rhsc);
3606   make_constraints_to (id, rhsc);
3607   VEC_free (ce_s, heap, rhsc);
3608 }
3609
3610 /* Create a constraint ID = &FROM.  */
3611
3612 static void
3613 make_constraint_from (varinfo_t vi, int from)
3614 {
3615   struct constraint_expr lhs, rhs;
3616
3617   lhs.var = vi->id;
3618   lhs.offset = 0;
3619   lhs.type = SCALAR;
3620
3621   rhs.var = from;
3622   rhs.offset = 0;
3623   rhs.type = ADDRESSOF;
3624   process_constraint (new_constraint (lhs, rhs));
3625 }
3626
3627 /* Create a constraint ID = FROM.  */
3628
3629 static void
3630 make_copy_constraint (varinfo_t vi, int from)
3631 {
3632   struct constraint_expr lhs, rhs;
3633
3634   lhs.var = vi->id;
3635   lhs.offset = 0;
3636   lhs.type = SCALAR;
3637
3638   rhs.var = from;
3639   rhs.offset = 0;
3640   rhs.type = SCALAR;
3641   process_constraint (new_constraint (lhs, rhs));
3642 }
3643
3644 /* Make constraints necessary to make OP escape.  */
3645
3646 static void
3647 make_escape_constraint (tree op)
3648 {
3649   make_constraint_to (escaped_id, op);
3650 }
3651
3652 /* Add constraints to that the solution of VI is transitively closed.  */
3653
3654 static void
3655 make_transitive_closure_constraints (varinfo_t vi)
3656 {
3657   struct constraint_expr lhs, rhs;
3658
3659   /* VAR = *VAR;  */
3660   lhs.type = SCALAR;
3661   lhs.var = vi->id;
3662   lhs.offset = 0;
3663   rhs.type = DEREF;
3664   rhs.var = vi->id;
3665   rhs.offset = 0;
3666   process_constraint (new_constraint (lhs, rhs));
3667
3668   /* VAR = VAR + UNKNOWN;  */
3669   lhs.type = SCALAR;
3670   lhs.var = vi->id;
3671   lhs.offset = 0;
3672   rhs.type = SCALAR;
3673   rhs.var = vi->id;
3674   rhs.offset = UNKNOWN_OFFSET;
3675   process_constraint (new_constraint (lhs, rhs));
3676 }
3677
3678 /* Create a new artificial heap variable with NAME.
3679    Return the created variable.  */
3680
3681 static varinfo_t
3682 make_heapvar_for (varinfo_t lhs, const char *name)
3683 {
3684   varinfo_t vi;
3685   tree heapvar = heapvar_lookup (lhs->decl, lhs->offset);
3686
3687   if (heapvar == NULL_TREE)
3688     {
3689       var_ann_t ann;
3690       heapvar = create_tmp_var_raw (ptr_type_node, name);
3691       DECL_EXTERNAL (heapvar) = 1;
3692
3693       heapvar_insert (lhs->decl, lhs->offset, heapvar);
3694
3695       ann = get_var_ann (heapvar);
3696       ann->is_heapvar = 1;
3697     }
3698
3699   /* For global vars we need to add a heapvar to the list of referenced
3700      vars of a different function than it was created for originally.  */
3701   if (cfun && gimple_referenced_vars (cfun))
3702     add_referenced_var (heapvar);
3703
3704   vi = new_var_info (heapvar, name);
3705   vi->is_artificial_var = true;
3706   vi->is_heap_var = true;
3707   vi->is_unknown_size_var = true;
3708   vi->offset = 0;
3709   vi->fullsize = ~0;
3710   vi->size = ~0;
3711   vi->is_full_var = true;
3712   insert_vi_for_tree (heapvar, vi);
3713
3714   return vi;
3715 }
3716
3717 /* Create a new artificial heap variable with NAME and make a
3718    constraint from it to LHS.  Return the created variable.  */
3719
3720 static varinfo_t
3721 make_constraint_from_heapvar (varinfo_t lhs, const char *name)
3722 {
3723   varinfo_t vi = make_heapvar_for (lhs, name);
3724   make_constraint_from (lhs, vi->id);
3725
3726   return vi;
3727 }
3728
3729 /* Create a new artificial heap variable with NAME and make a
3730    constraint from it to LHS.  Set flags according to a tag used
3731    for tracking restrict pointers.  */
3732
3733 static void
3734 make_constraint_from_restrict (varinfo_t lhs, const char *name)
3735 {
3736   varinfo_t vi;
3737   vi = make_constraint_from_heapvar (lhs, name);
3738   vi->is_restrict_var = 1;
3739   vi->is_global_var = 0;
3740   vi->is_special_var = 1;
3741   vi->may_have_pointers = 0;
3742 }
3743
3744 /* In IPA mode there are varinfos for different aspects of reach
3745    function designator.  One for the points-to set of the return
3746    value, one for the variables that are clobbered by the function,
3747    one for its uses and one for each parameter (including a single
3748    glob for remaining variadic arguments).  */
3749
3750 enum { fi_clobbers = 1, fi_uses = 2,
3751        fi_static_chain = 3, fi_result = 4, fi_parm_base = 5 };
3752
3753 /* Get a constraint for the requested part of a function designator FI
3754    when operating in IPA mode.  */
3755
3756 static struct constraint_expr
3757 get_function_part_constraint (varinfo_t fi, unsigned part)
3758 {
3759   struct constraint_expr c;
3760
3761   gcc_assert (in_ipa_mode);
3762
3763   if (fi->id == anything_id)
3764     {
3765       /* ???  We probably should have a ANYFN special variable.  */
3766       c.var = anything_id;
3767       c.offset = 0;
3768       c.type = SCALAR;
3769     }
3770   else if (TREE_CODE (fi->decl) == FUNCTION_DECL)
3771     {
3772       varinfo_t ai = first_vi_for_offset (fi, part);
3773       if (ai)
3774         c.var = ai->id;
3775       else
3776         c.var = anything_id;
3777       c.offset = 0;
3778       c.type = SCALAR;
3779     }
3780   else
3781     {
3782       c.var = fi->id;
3783       c.offset = part;
3784       c.type = DEREF;
3785     }
3786
3787   return c;
3788 }
3789
3790 /* For non-IPA mode, generate constraints necessary for a call on the
3791    RHS.  */
3792
3793 static void
3794 handle_rhs_call (gimple stmt, VEC(ce_s, heap) **results)
3795 {
3796   struct constraint_expr rhsc;
3797   unsigned i;
3798   bool returns_uses = false;
3799
3800   for (i = 0; i < gimple_call_num_args (stmt); ++i)
3801     {
3802       tree arg = gimple_call_arg (stmt, i);
3803       int flags = gimple_call_arg_flags (stmt, i);
3804
3805       /* If the argument is not used we can ignore it.  */
3806       if (flags & EAF_UNUSED)
3807         continue;
3808
3809       /* As we compute ESCAPED context-insensitive we do not gain
3810          any precision with just EAF_NOCLOBBER but not EAF_NOESCAPE
3811          set.  The argument would still get clobbered through the
3812          escape solution.
3813          ???  We might get away with less (and more precise) constraints
3814          if using a temporary for transitively closing things.  */
3815       if ((flags & EAF_NOCLOBBER)
3816            && (flags & EAF_NOESCAPE))
3817         {
3818           varinfo_t uses = get_call_use_vi (stmt);
3819           if (!(flags & EAF_DIRECT))
3820             make_transitive_closure_constraints (uses);
3821           make_constraint_to (uses->id, arg);
3822           returns_uses = true;
3823         }
3824       else if (flags & EAF_NOESCAPE)
3825         {
3826           varinfo_t uses = get_call_use_vi (stmt);
3827           varinfo_t clobbers = get_call_clobber_vi (stmt);
3828           if (!(flags & EAF_DIRECT))
3829             {
3830               make_transitive_closure_constraints (uses);
3831               make_transitive_closure_constraints (clobbers);
3832             }
3833           make_constraint_to (uses->id, arg);
3834           make_constraint_to (clobbers->id, arg);
3835           returns_uses = true;
3836         }
3837       else
3838         make_escape_constraint (arg);
3839     }
3840
3841   /* If we added to the calls uses solution make sure we account for
3842      pointers to it to be returned.  */
3843   if (returns_uses)
3844     {
3845       rhsc.var = get_call_use_vi (stmt)->id;
3846       rhsc.offset = 0;
3847       rhsc.type = SCALAR;
3848       VEC_safe_push (ce_s, heap, *results, &rhsc);
3849     }
3850
3851   /* The static chain escapes as well.  */
3852   if (gimple_call_chain (stmt))
3853     make_escape_constraint (gimple_call_chain (stmt));
3854
3855   /* And if we applied NRV the address of the return slot escapes as well.  */
3856   if (gimple_call_return_slot_opt_p (stmt)
3857       && gimple_call_lhs (stmt) != NULL_TREE
3858       && TREE_ADDRESSABLE (TREE_TYPE (gimple_call_lhs (stmt))))
3859     {
3860       VEC(ce_s, heap) *tmpc = NULL;
3861       struct constraint_expr lhsc, *c;
3862       get_constraint_for_address_of (gimple_call_lhs (stmt), &tmpc);
3863       lhsc.var = escaped_id;
3864       lhsc.offset = 0;
3865       lhsc.type = SCALAR;
3866       FOR_EACH_VEC_ELT (ce_s, tmpc, i, c)
3867         process_constraint (new_constraint (lhsc, *c));
3868       VEC_free(ce_s, heap, tmpc);
3869     }
3870
3871   /* Regular functions return nonlocal memory.  */
3872   rhsc.var = nonlocal_id;
3873   rhsc.offset = 0;
3874   rhsc.type = SCALAR;
3875   VEC_safe_push (ce_s, heap, *results, &rhsc);
3876 }
3877
3878 /* For non-IPA mode, generate constraints necessary for a call
3879    that returns a pointer and assigns it to LHS.  This simply makes
3880    the LHS point to global and escaped variables.  */
3881
3882 static void
3883 handle_lhs_call (gimple stmt, tree lhs, int flags, VEC(ce_s, heap) *rhsc,
3884                  tree fndecl)
3885 {
3886   VEC(ce_s, heap) *lhsc = NULL;
3887
3888   get_constraint_for (lhs, &lhsc);
3889   /* If the store is to a global decl make sure to
3890      add proper escape constraints.  */
3891   lhs = get_base_address (lhs);
3892   if (lhs
3893       && DECL_P (lhs)
3894       && is_global_var (lhs))
3895     {
3896       struct constraint_expr tmpc;
3897       tmpc.var = escaped_id;
3898       tmpc.offset = 0;
3899       tmpc.type = SCALAR;
3900       VEC_safe_push (ce_s, heap, lhsc, &tmpc);
3901     }
3902
3903   /* If the call returns an argument unmodified override the rhs
3904      constraints.  */
3905   flags = gimple_call_return_flags (stmt);
3906   if (flags & ERF_RETURNS_ARG
3907       && (flags & ERF_RETURN_ARG_MASK) < gimple_call_num_args (stmt))
3908     {
3909       tree arg;
3910       rhsc = NULL;
3911       arg = gimple_call_arg (stmt, flags & ERF_RETURN_ARG_MASK);
3912       get_constraint_for (arg, &rhsc);
3913       process_all_all_constraints (lhsc, rhsc);
3914       VEC_free (ce_s, heap, rhsc);
3915     }
3916   else if (flags & ERF_NOALIAS)
3917     {
3918       varinfo_t vi;
3919       struct constraint_expr tmpc;
3920       rhsc = NULL;
3921       vi = make_heapvar_for (get_vi_for_tree (lhs), "HEAP");
3922       /* We delay marking allocated storage global until we know if
3923          it escapes.  */
3924       DECL_EXTERNAL (vi->decl) = 0;
3925       vi->is_global_var = 0;
3926       /* If this is not a real malloc call assume the memory was
3927          initialized and thus may point to global memory.  All
3928          builtin functions with the malloc attribute behave in a sane way.  */
3929       if (!fndecl
3930           || DECL_BUILT_IN_CLASS (fndecl) != BUILT_IN_NORMAL)
3931         make_constraint_from (vi, nonlocal_id);
3932       tmpc.var = vi->id;
3933       tmpc.offset = 0;
3934       tmpc.type = ADDRESSOF;
3935       VEC_safe_push (ce_s, heap, rhsc, &tmpc);
3936     }
3937
3938   process_all_all_constraints (lhsc, rhsc);
3939
3940   VEC_free (ce_s, heap, lhsc);
3941 }
3942
3943 /* For non-IPA mode, generate constraints necessary for a call of a
3944    const function that returns a pointer in the statement STMT.  */
3945
3946 static void
3947 handle_const_call (gimple stmt, VEC(ce_s, heap) **results)
3948 {
3949   struct constraint_expr rhsc;
3950   unsigned int k;
3951
3952   /* Treat nested const functions the same as pure functions as far
3953      as the static chain is concerned.  */
3954   if (gimple_call_chain (stmt))
3955     {
3956       varinfo_t uses = get_call_use_vi (stmt);
3957       make_transitive_closure_constraints (uses);
3958       make_constraint_to (uses->id, gimple_call_chain (stmt));
3959       rhsc.var = uses->id;
3960       rhsc.offset = 0;
3961       rhsc.type = SCALAR;
3962       VEC_safe_push (ce_s, heap, *results, &rhsc);
3963     }
3964
3965   /* May return arguments.  */
3966   for (k = 0; k < gimple_call_num_args (stmt); ++k)
3967     {
3968       tree arg = gimple_call_arg (stmt, k);
3969       VEC(ce_s, heap) *argc = NULL;
3970       unsigned i;
3971       struct constraint_expr *argp;
3972       get_constraint_for_rhs (arg, &argc);
3973       FOR_EACH_VEC_ELT (ce_s, argc, i, argp)
3974         VEC_safe_push (ce_s, heap, *results, argp);
3975       VEC_free(ce_s, heap, argc);
3976     }
3977
3978   /* May return addresses of globals.  */
3979   rhsc.var = nonlocal_id;
3980   rhsc.offset = 0;
3981   rhsc.type = ADDRESSOF;
3982   VEC_safe_push (ce_s, heap, *results, &rhsc);
3983 }
3984
3985 /* For non-IPA mode, generate constraints necessary for a call to a
3986    pure function in statement STMT.  */
3987
3988 static void
3989 handle_pure_call (gimple stmt, VEC(ce_s, heap) **results)
3990 {
3991   struct constraint_expr rhsc;
3992   unsigned i;
3993   varinfo_t uses = NULL;
3994
3995   /* Memory reached from pointer arguments is call-used.  */
3996   for (i = 0; i < gimple_call_num_args (stmt); ++i)
3997     {
3998       tree arg = gimple_call_arg (stmt, i);
3999       if (!uses)
4000         {
4001           uses = get_call_use_vi (stmt);
4002           make_transitive_closure_constraints (uses);
4003         }
4004       make_constraint_to (uses->id, arg);
4005     }
4006
4007   /* The static chain is used as well.  */
4008   if (gimple_call_chain (stmt))
4009     {
4010       if (!uses)
4011         {
4012           uses = get_call_use_vi (stmt);
4013           make_transitive_closure_constraints (uses);
4014         }
4015       make_constraint_to (uses->id, gimple_call_chain (stmt));
4016     }
4017
4018   /* Pure functions may return call-used and nonlocal memory.  */
4019   if (uses)
4020     {
4021       rhsc.var = uses->id;
4022       rhsc.offset = 0;
4023       rhsc.type = SCALAR;
4024       VEC_safe_push (ce_s, heap, *results, &rhsc);
4025     }
4026   rhsc.var = nonlocal_id;
4027   rhsc.offset = 0;
4028   rhsc.type = SCALAR;
4029   VEC_safe_push (ce_s, heap, *results, &rhsc);
4030 }
4031
4032
4033 /* Return the varinfo for the callee of CALL.  */
4034
4035 static varinfo_t
4036 get_fi_for_callee (gimple call)
4037 {
4038   tree decl;
4039
4040   /* If we can directly resolve the function being called, do so.
4041      Otherwise, it must be some sort of indirect expression that
4042      we should still be able to handle.  */
4043   decl = gimple_call_fndecl (call);
4044   if (decl)
4045     return get_vi_for_tree (decl);
4046
4047   decl = gimple_call_fn (call);
4048   /* The function can be either an SSA name pointer or,
4049      worse, an OBJ_TYPE_REF.  In this case we have no
4050      clue and should be getting ANYFN (well, ANYTHING for now).  */
4051   if (TREE_CODE (decl) == SSA_NAME)
4052     {
4053       if (TREE_CODE (decl) == SSA_NAME
4054           && (TREE_CODE (SSA_NAME_VAR (decl)) == PARM_DECL
4055               || TREE_CODE (SSA_NAME_VAR (decl)) == RESULT_DECL)
4056           && SSA_NAME_IS_DEFAULT_DEF (decl))
4057         decl = SSA_NAME_VAR (decl);
4058       return get_vi_for_tree (decl);
4059     }
4060   else if (TREE_CODE (decl) == INTEGER_CST
4061            || TREE_CODE (decl) == OBJ_TYPE_REF)
4062     return get_varinfo (anything_id);
4063   else
4064     gcc_unreachable ();
4065 }
4066
4067 /* Walk statement T setting up aliasing constraints according to the
4068    references found in T.  This function is the main part of the
4069    constraint builder.  AI points to auxiliary alias information used
4070    when building alias sets and computing alias grouping heuristics.  */
4071
4072 static void
4073 find_func_aliases (gimple origt)
4074 {
4075   gimple t = origt;
4076   VEC(ce_s, heap) *lhsc = NULL;
4077   VEC(ce_s, heap) *rhsc = NULL;
4078   struct constraint_expr *c;
4079   varinfo_t fi;
4080
4081   /* Now build constraints expressions.  */
4082   if (gimple_code (t) == GIMPLE_PHI)
4083     {
4084       size_t i;
4085       unsigned int j;
4086
4087       /* For a phi node, assign all the arguments to
4088          the result.  */
4089       get_constraint_for (gimple_phi_result (t), &lhsc);
4090       for (i = 0; i < gimple_phi_num_args (t); i++)
4091         {
4092           tree strippedrhs = PHI_ARG_DEF (t, i);
4093
4094           STRIP_NOPS (strippedrhs);
4095           get_constraint_for_rhs (gimple_phi_arg_def (t, i), &rhsc);
4096
4097           FOR_EACH_VEC_ELT (ce_s, lhsc, j, c)
4098             {
4099               struct constraint_expr *c2;
4100               while (VEC_length (ce_s, rhsc) > 0)
4101                 {
4102                   c2 = VEC_last (ce_s, rhsc);
4103                   process_constraint (new_constraint (*c, *c2));
4104                   VEC_pop (ce_s, rhsc);
4105                 }
4106             }
4107         }
4108     }
4109   /* In IPA mode, we need to generate constraints to pass call
4110      arguments through their calls.   There are two cases,
4111      either a GIMPLE_CALL returning a value, or just a plain
4112      GIMPLE_CALL when we are not.
4113
4114      In non-ipa mode, we need to generate constraints for each
4115      pointer passed by address.  */
4116   else if (is_gimple_call (t))
4117     {
4118       tree fndecl = gimple_call_fndecl (t);
4119       if (fndecl != NULL_TREE
4120           && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
4121         /* ???  All builtins that are handled here need to be handled
4122            in the alias-oracle query functions explicitly!  */
4123         switch (DECL_FUNCTION_CODE (fndecl))
4124           {
4125           /* All the following functions return a pointer to the same object
4126              as their first argument points to.  The functions do not add
4127              to the ESCAPED solution.  The functions make the first argument
4128              pointed to memory point to what the second argument pointed to
4129              memory points to.  */
4130           case BUILT_IN_STRCPY:
4131           case BUILT_IN_STRNCPY:
4132           case BUILT_IN_BCOPY:
4133           case BUILT_IN_MEMCPY:
4134           case BUILT_IN_MEMMOVE:
4135           case BUILT_IN_MEMPCPY:
4136           case BUILT_IN_STPCPY:
4137           case BUILT_IN_STPNCPY:
4138           case BUILT_IN_STRCAT:
4139           case BUILT_IN_STRNCAT:
4140             {
4141               tree res = gimple_call_lhs (t);
4142               tree dest = gimple_call_arg (t, (DECL_FUNCTION_CODE (fndecl)
4143                                                == BUILT_IN_BCOPY ? 1 : 0));
4144               tree src = gimple_call_arg (t, (DECL_FUNCTION_CODE (fndecl)
4145                                               == BUILT_IN_BCOPY ? 0 : 1));
4146               if (res != NULL_TREE)
4147                 {
4148                   get_constraint_for (res, &lhsc);
4149                   if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_MEMPCPY
4150                       || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPCPY
4151                       || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPNCPY)
4152                     get_constraint_for_ptr_offset (dest, NULL_TREE, &rhsc);
4153                   else
4154                     get_constraint_for (dest, &rhsc);
4155                   process_all_all_constraints (lhsc, rhsc);
4156                   VEC_free (ce_s, heap, lhsc);
4157                   VEC_free (ce_s, heap, rhsc);
4158                 }
4159               get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4160               get_constraint_for_ptr_offset (src, NULL_TREE, &rhsc);
4161               do_deref (&lhsc);
4162               do_deref (&rhsc);
4163               process_all_all_constraints (lhsc, rhsc);
4164               VEC_free (ce_s, heap, lhsc);
4165               VEC_free (ce_s, heap, rhsc);
4166               return;
4167             }
4168           case BUILT_IN_MEMSET:
4169             {
4170               tree res = gimple_call_lhs (t);
4171               tree dest = gimple_call_arg (t, 0);
4172               unsigned i;
4173               ce_s *lhsp;
4174               struct constraint_expr ac;
4175               if (res != NULL_TREE)
4176                 {
4177                   get_constraint_for (res, &lhsc);
4178                   get_constraint_for (dest, &rhsc);
4179                   process_all_all_constraints (lhsc, rhsc);
4180                   VEC_free (ce_s, heap, lhsc);
4181                   VEC_free (ce_s, heap, rhsc);
4182                 }
4183               get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4184               do_deref (&lhsc);
4185               if (flag_delete_null_pointer_checks
4186                   && integer_zerop (gimple_call_arg (t, 1)))
4187                 {
4188                   ac.type = ADDRESSOF;
4189                   ac.var = nothing_id;
4190                 }
4191               else
4192                 {
4193                   ac.type = SCALAR;
4194                   ac.var = integer_id;
4195                 }
4196               ac.offset = 0;
4197               FOR_EACH_VEC_ELT (ce_s, lhsc, i, lhsp)
4198                 process_constraint (new_constraint (*lhsp, ac));
4199               VEC_free (ce_s, heap, lhsc);
4200               return;
4201             }
4202           /* All the following functions do not return pointers, do not
4203              modify the points-to sets of memory reachable from their
4204              arguments and do not add to the ESCAPED solution.  */
4205           case BUILT_IN_SINCOS:
4206           case BUILT_IN_SINCOSF:
4207           case BUILT_IN_SINCOSL:
4208           case BUILT_IN_FREXP:
4209           case BUILT_IN_FREXPF:
4210           case BUILT_IN_FREXPL:
4211           case BUILT_IN_GAMMA_R:
4212           case BUILT_IN_GAMMAF_R:
4213           case BUILT_IN_GAMMAL_R:
4214           case BUILT_IN_LGAMMA_R:
4215           case BUILT_IN_LGAMMAF_R:
4216           case BUILT_IN_LGAMMAL_R:
4217           case BUILT_IN_MODF:
4218           case BUILT_IN_MODFF:
4219           case BUILT_IN_MODFL:
4220           case BUILT_IN_REMQUO:
4221           case BUILT_IN_REMQUOF:
4222           case BUILT_IN_REMQUOL:
4223           case BUILT_IN_FREE:
4224             return;
4225           /* Trampolines are special - they set up passing the static
4226              frame.  */
4227           case BUILT_IN_INIT_TRAMPOLINE:
4228             {
4229               tree tramp = gimple_call_arg (t, 0);
4230               tree nfunc = gimple_call_arg (t, 1);
4231               tree frame = gimple_call_arg (t, 2);
4232               unsigned i;
4233               struct constraint_expr lhs, *rhsp;
4234               if (in_ipa_mode)
4235                 {
4236                   varinfo_t nfi = NULL;
4237                   gcc_assert (TREE_CODE (nfunc) == ADDR_EXPR);
4238                   nfi = lookup_vi_for_tree (TREE_OPERAND (nfunc, 0));
4239                   if (nfi)
4240                     {
4241                       lhs = get_function_part_constraint (nfi, fi_static_chain);
4242                       get_constraint_for (frame, &rhsc);
4243                       FOR_EACH_VEC_ELT (ce_s, rhsc, i, rhsp)
4244                         process_constraint (new_constraint (lhs, *rhsp));
4245                       VEC_free (ce_s, heap, rhsc);
4246
4247                       /* Make the frame point to the function for
4248                          the trampoline adjustment call.  */
4249                       get_constraint_for (tramp, &lhsc);
4250                       do_deref (&lhsc);
4251                       get_constraint_for (nfunc, &rhsc);
4252                       process_all_all_constraints (lhsc, rhsc);
4253                       VEC_free (ce_s, heap, rhsc);
4254                       VEC_free (ce_s, heap, lhsc);
4255
4256                       return;
4257                     }
4258                 }
4259               /* Else fallthru to generic handling which will let
4260                  the frame escape.  */
4261               break;
4262             }
4263           case BUILT_IN_ADJUST_TRAMPOLINE:
4264             {
4265               tree tramp = gimple_call_arg (t, 0);
4266               tree res = gimple_call_lhs (t);
4267               if (in_ipa_mode && res)
4268                 {
4269                   get_constraint_for (res, &lhsc);
4270                   get_constraint_for (tramp, &rhsc);
4271                   do_deref (&rhsc);
4272                   process_all_all_constraints (lhsc, rhsc);
4273                   VEC_free (ce_s, heap, rhsc);
4274                   VEC_free (ce_s, heap, lhsc);
4275                 }
4276               return;
4277             }
4278           /* Variadic argument handling needs to be handled in IPA
4279              mode as well.  */
4280           case BUILT_IN_VA_START:
4281             {
4282               if (in_ipa_mode)
4283                 {
4284                   tree valist = gimple_call_arg (t, 0);
4285                   struct constraint_expr rhs, *lhsp;
4286                   unsigned i;
4287                   /* The va_list gets access to pointers in variadic
4288                      arguments.  */
4289                   fi = lookup_vi_for_tree (cfun->decl);
4290                   gcc_assert (fi != NULL);
4291                   get_constraint_for (valist, &lhsc);
4292                   do_deref (&lhsc);
4293                   rhs = get_function_part_constraint (fi, ~0);
4294                   rhs.type = ADDRESSOF;
4295                   FOR_EACH_VEC_ELT (ce_s, lhsc, i, lhsp)
4296                     process_constraint (new_constraint (*lhsp, rhs));
4297                   VEC_free (ce_s, heap, lhsc);
4298                   /* va_list is clobbered.  */
4299                   make_constraint_to (get_call_clobber_vi (t)->id, valist);
4300                   return;
4301                 }
4302               break;
4303             }
4304           /* va_end doesn't have any effect that matters.  */
4305           case BUILT_IN_VA_END:
4306             return;
4307           /* Alternate return.  Simply give up for now.  */
4308           case BUILT_IN_RETURN:
4309             {
4310               fi = NULL;
4311               if (!in_ipa_mode
4312                   || !(fi = get_vi_for_tree (cfun->decl)))
4313                 make_constraint_from (get_varinfo (escaped_id), anything_id);
4314               else if (in_ipa_mode
4315                        && fi != NULL)
4316                 {
4317                   struct constraint_expr lhs, rhs;
4318                   lhs = get_function_part_constraint (fi, fi_result);
4319                   rhs.var = anything_id;
4320                   rhs.offset = 0;
4321                   rhs.type = SCALAR;
4322                   process_constraint (new_constraint (lhs, rhs));
4323                 }
4324               return;
4325             }
4326           /* printf-style functions may have hooks to set pointers to
4327              point to somewhere into the generated string.  Leave them
4328              for a later excercise...  */
4329           default:
4330             /* Fallthru to general call handling.  */;
4331           }
4332       if (!in_ipa_mode
4333           || (fndecl
4334               && (!(fi = lookup_vi_for_tree (fndecl))
4335                   || !fi->is_fn_info)))
4336         {
4337           VEC(ce_s, heap) *rhsc = NULL;
4338           int flags = gimple_call_flags (t);
4339
4340           /* Const functions can return their arguments and addresses
4341              of global memory but not of escaped memory.  */
4342           if (flags & (ECF_CONST|ECF_NOVOPS))
4343             {
4344               if (gimple_call_lhs (t))
4345                 handle_const_call (t, &rhsc);
4346             }
4347           /* Pure functions can return addresses in and of memory
4348              reachable from their arguments, but they are not an escape
4349              point for reachable memory of their arguments.  */
4350           else if (flags & (ECF_PURE|ECF_LOOPING_CONST_OR_PURE))
4351             handle_pure_call (t, &rhsc);
4352           else
4353             handle_rhs_call (t, &rhsc);
4354           if (gimple_call_lhs (t))
4355             handle_lhs_call (t, gimple_call_lhs (t), flags, rhsc, fndecl);
4356           VEC_free (ce_s, heap, rhsc);
4357         }
4358       else
4359         {
4360           tree lhsop;
4361           unsigned j;
4362
4363           fi = get_fi_for_callee (t);
4364
4365           /* Assign all the passed arguments to the appropriate incoming
4366              parameters of the function.  */
4367           for (j = 0; j < gimple_call_num_args (t); j++)
4368             {
4369               struct constraint_expr lhs ;
4370               struct constraint_expr *rhsp;
4371               tree arg = gimple_call_arg (t, j);
4372
4373               get_constraint_for_rhs (arg, &rhsc);
4374               lhs = get_function_part_constraint (fi, fi_parm_base + j);
4375               while (VEC_length (ce_s, rhsc) != 0)
4376                 {
4377                   rhsp = VEC_last (ce_s, rhsc);
4378                   process_constraint (new_constraint (lhs, *rhsp));
4379                   VEC_pop (ce_s, rhsc);
4380                 }
4381             }
4382
4383           /* If we are returning a value, assign it to the result.  */
4384           lhsop = gimple_call_lhs (t);
4385           if (lhsop)
4386             {
4387               struct constraint_expr rhs;
4388               struct constraint_expr *lhsp;
4389
4390               get_constraint_for (lhsop, &lhsc);
4391               rhs = get_function_part_constraint (fi, fi_result);
4392               if (fndecl
4393                   && DECL_RESULT (fndecl)
4394                   && DECL_BY_REFERENCE (DECL_RESULT (fndecl)))
4395                 {
4396                   VEC(ce_s, heap) *tem = NULL;
4397                   VEC_safe_push (ce_s, heap, tem, &rhs);
4398                   do_deref (&tem);
4399                   rhs = *VEC_index (ce_s, tem, 0);
4400                   VEC_free(ce_s, heap, tem);
4401                 }
4402               FOR_EACH_VEC_ELT (ce_s, lhsc, j, lhsp)
4403                 process_constraint (new_constraint (*lhsp, rhs));
4404             }
4405
4406           /* If we pass the result decl by reference, honor that.  */
4407           if (lhsop
4408               && fndecl
4409               && DECL_RESULT (fndecl)
4410               && DECL_BY_REFERENCE (DECL_RESULT (fndecl)))
4411             {
4412               struct constraint_expr lhs;
4413               struct constraint_expr *rhsp;
4414
4415               get_constraint_for_address_of (lhsop, &rhsc);
4416               lhs = get_function_part_constraint (fi, fi_result);
4417               FOR_EACH_VEC_ELT (ce_s, rhsc, j, rhsp)
4418                 process_constraint (new_constraint (lhs, *rhsp));
4419               VEC_free (ce_s, heap, rhsc);
4420             }
4421
4422           /* If we use a static chain, pass it along.  */
4423           if (gimple_call_chain (t))
4424             {
4425               struct constraint_expr lhs;
4426               struct constraint_expr *rhsp;
4427
4428               get_constraint_for (gimple_call_chain (t), &rhsc);
4429               lhs = get_function_part_constraint (fi, fi_static_chain);
4430               FOR_EACH_VEC_ELT (ce_s, rhsc, j, rhsp)
4431                 process_constraint (new_constraint (lhs, *rhsp));
4432             }
4433         }
4434     }
4435   /* Otherwise, just a regular assignment statement.  Only care about
4436      operations with pointer result, others are dealt with as escape
4437      points if they have pointer operands.  */
4438   else if (is_gimple_assign (t))
4439     {
4440       /* Otherwise, just a regular assignment statement.  */
4441       tree lhsop = gimple_assign_lhs (t);
4442       tree rhsop = (gimple_num_ops (t) == 2) ? gimple_assign_rhs1 (t) : NULL;
4443
4444       if (rhsop && AGGREGATE_TYPE_P (TREE_TYPE (lhsop)))
4445         do_structure_copy (lhsop, rhsop);
4446       else
4447         {
4448           enum tree_code code = gimple_assign_rhs_code (t);
4449
4450           get_constraint_for (lhsop, &lhsc);
4451
4452           if (code == POINTER_PLUS_EXPR)
4453             get_constraint_for_ptr_offset (gimple_assign_rhs1 (t),
4454                                            gimple_assign_rhs2 (t), &rhsc);
4455           else if (code == BIT_AND_EXPR
4456                    && TREE_CODE (gimple_assign_rhs2 (t)) == INTEGER_CST)
4457             {
4458               /* Aligning a pointer via a BIT_AND_EXPR is offsetting
4459                  the pointer.  Handle it by offsetting it by UNKNOWN.  */
4460               get_constraint_for_ptr_offset (gimple_assign_rhs1 (t),
4461                                              NULL_TREE, &rhsc);
4462             }
4463           else if ((CONVERT_EXPR_CODE_P (code)
4464                     && !(POINTER_TYPE_P (gimple_expr_type (t))
4465                          && !POINTER_TYPE_P (TREE_TYPE (rhsop))))
4466                    || gimple_assign_single_p (t))
4467             get_constraint_for_rhs (rhsop, &rhsc);
4468           else if (truth_value_p (code))
4469             /* Truth value results are not pointer (parts).  Or at least
4470                very very unreasonable obfuscation of a part.  */
4471             ;
4472           else
4473             {
4474               /* All other operations are merges.  */
4475               VEC (ce_s, heap) *tmp = NULL;
4476               struct constraint_expr *rhsp;
4477               unsigned i, j;
4478               get_constraint_for_rhs (gimple_assign_rhs1 (t), &rhsc);
4479               for (i = 2; i < gimple_num_ops (t); ++i)
4480                 {
4481                   get_constraint_for_rhs (gimple_op (t, i), &tmp);
4482                   FOR_EACH_VEC_ELT (ce_s, tmp, j, rhsp)
4483                     VEC_safe_push (ce_s, heap, rhsc, rhsp);
4484                   VEC_truncate (ce_s, tmp, 0);
4485                 }
4486               VEC_free (ce_s, heap, tmp);
4487             }
4488           process_all_all_constraints (lhsc, rhsc);
4489         }
4490       /* If there is a store to a global variable the rhs escapes.  */
4491       if ((lhsop = get_base_address (lhsop)) != NULL_TREE
4492           && DECL_P (lhsop)
4493           && is_global_var (lhsop)
4494           && (!in_ipa_mode
4495               || DECL_EXTERNAL (lhsop) || TREE_PUBLIC (lhsop)))
4496         make_escape_constraint (rhsop);
4497     }
4498   /* Handle escapes through return.  */
4499   else if (gimple_code (t) == GIMPLE_RETURN
4500            && gimple_return_retval (t) != NULL_TREE)
4501     {
4502       fi = NULL;
4503       if (!in_ipa_mode
4504           || !(fi = get_vi_for_tree (cfun->decl)))
4505         make_escape_constraint (gimple_return_retval (t));
4506       else if (in_ipa_mode
4507                && fi != NULL)
4508         {
4509           struct constraint_expr lhs ;
4510           struct constraint_expr *rhsp;
4511           unsigned i;
4512
4513           lhs = get_function_part_constraint (fi, fi_result);
4514           get_constraint_for_rhs (gimple_return_retval (t), &rhsc);
4515           FOR_EACH_VEC_ELT (ce_s, rhsc, i, rhsp)
4516             process_constraint (new_constraint (lhs, *rhsp));
4517         }
4518     }
4519   /* Handle asms conservatively by adding escape constraints to everything.  */
4520   else if (gimple_code (t) == GIMPLE_ASM)
4521     {
4522       unsigned i, noutputs;
4523       const char **oconstraints;
4524       const char *constraint;
4525       bool allows_mem, allows_reg, is_inout;
4526
4527       noutputs = gimple_asm_noutputs (t);
4528       oconstraints = XALLOCAVEC (const char *, noutputs);
4529
4530       for (i = 0; i < noutputs; ++i)
4531         {
4532           tree link = gimple_asm_output_op (t, i);
4533           tree op = TREE_VALUE (link);
4534
4535           constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
4536           oconstraints[i] = constraint;
4537           parse_output_constraint (&constraint, i, 0, 0, &allows_mem,
4538                                    &allows_reg, &is_inout);
4539
4540           /* A memory constraint makes the address of the operand escape.  */
4541           if (!allows_reg && allows_mem)
4542             make_escape_constraint (build_fold_addr_expr (op));
4543
4544           /* The asm may read global memory, so outputs may point to
4545              any global memory.  */
4546           if (op)
4547             {
4548               VEC(ce_s, heap) *lhsc = NULL;
4549               struct constraint_expr rhsc, *lhsp;
4550               unsigned j;
4551               get_constraint_for (op, &lhsc);
4552               rhsc.var = nonlocal_id;
4553               rhsc.offset = 0;
4554               rhsc.type = SCALAR;
4555               FOR_EACH_VEC_ELT (ce_s, lhsc, j, lhsp)
4556                 process_constraint (new_constraint (*lhsp, rhsc));
4557               VEC_free (ce_s, heap, lhsc);
4558             }
4559         }
4560       for (i = 0; i < gimple_asm_ninputs (t); ++i)
4561         {
4562           tree link = gimple_asm_input_op (t, i);
4563           tree op = TREE_VALUE (link);
4564
4565           constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
4566
4567           parse_input_constraint (&constraint, 0, 0, noutputs, 0, oconstraints,
4568                                   &allows_mem, &allows_reg);
4569
4570           /* A memory constraint makes the address of the operand escape.  */
4571           if (!allows_reg && allows_mem)
4572             make_escape_constraint (build_fold_addr_expr (op));
4573           /* Strictly we'd only need the constraint to ESCAPED if
4574              the asm clobbers memory, otherwise using something
4575              along the lines of per-call clobbers/uses would be enough.  */
4576           else if (op)
4577             make_escape_constraint (op);
4578         }
4579     }
4580
4581   VEC_free (ce_s, heap, rhsc);
4582   VEC_free (ce_s, heap, lhsc);
4583 }
4584
4585
4586 /* Create a constraint adding to the clobber set of FI the memory
4587    pointed to by PTR.  */
4588
4589 static void
4590 process_ipa_clobber (varinfo_t fi, tree ptr)
4591 {
4592   VEC(ce_s, heap) *ptrc = NULL;
4593   struct constraint_expr *c, lhs;
4594   unsigned i;
4595   get_constraint_for_rhs (ptr, &ptrc);
4596   lhs = get_function_part_constraint (fi, fi_clobbers);
4597   FOR_EACH_VEC_ELT (ce_s, ptrc, i, c)
4598     process_constraint (new_constraint (lhs, *c));
4599   VEC_free (ce_s, heap, ptrc);
4600 }
4601
4602 /* Walk statement T setting up clobber and use constraints according to the
4603    references found in T.  This function is a main part of the
4604    IPA constraint builder.  */
4605
4606 static void
4607 find_func_clobbers (gimple origt)
4608 {
4609   gimple t = origt;
4610   VEC(ce_s, heap) *lhsc = NULL;
4611   VEC(ce_s, heap) *rhsc = NULL;
4612   varinfo_t fi;
4613
4614   /* Add constraints for clobbered/used in IPA mode.
4615      We are not interested in what automatic variables are clobbered
4616      or used as we only use the information in the caller to which
4617      they do not escape.  */
4618   gcc_assert (in_ipa_mode);
4619
4620   /* If the stmt refers to memory in any way it better had a VUSE.  */
4621   if (gimple_vuse (t) == NULL_TREE)
4622     return;
4623
4624   /* We'd better have function information for the current function.  */
4625   fi = lookup_vi_for_tree (cfun->decl);
4626   gcc_assert (fi != NULL);
4627
4628   /* Account for stores in assignments and calls.  */
4629   if (gimple_vdef (t) != NULL_TREE
4630       && gimple_has_lhs (t))
4631     {
4632       tree lhs = gimple_get_lhs (t);
4633       tree tem = lhs;
4634       while (handled_component_p (tem))
4635         tem = TREE_OPERAND (tem, 0);
4636       if ((DECL_P (tem)
4637            && !auto_var_in_fn_p (tem, cfun->decl))
4638           || INDIRECT_REF_P (tem)
4639           || (TREE_CODE (tem) == MEM_REF
4640               && !(TREE_CODE (TREE_OPERAND (tem, 0)) == ADDR_EXPR
4641                    && auto_var_in_fn_p
4642                         (TREE_OPERAND (TREE_OPERAND (tem, 0), 0), cfun->decl))))
4643         {
4644           struct constraint_expr lhsc, *rhsp;
4645           unsigned i;
4646           lhsc = get_function_part_constraint (fi, fi_clobbers);
4647           get_constraint_for_address_of (lhs, &rhsc);
4648           FOR_EACH_VEC_ELT (ce_s, rhsc, i, rhsp)
4649             process_constraint (new_constraint (lhsc, *rhsp));
4650           VEC_free (ce_s, heap, rhsc);
4651         }
4652     }
4653
4654   /* Account for uses in assigments and returns.  */
4655   if (gimple_assign_single_p (t)
4656       || (gimple_code (t) == GIMPLE_RETURN
4657           && gimple_return_retval (t) != NULL_TREE))
4658     {
4659       tree rhs = (gimple_assign_single_p (t)
4660                   ? gimple_assign_rhs1 (t) : gimple_return_retval (t));
4661       tree tem = rhs;
4662       while (handled_component_p (tem))
4663         tem = TREE_OPERAND (tem, 0);
4664       if ((DECL_P (tem)
4665            && !auto_var_in_fn_p (tem, cfun->decl))
4666           || INDIRECT_REF_P (tem)
4667           || (TREE_CODE (tem) == MEM_REF
4668               && !(TREE_CODE (TREE_OPERAND (tem, 0)) == ADDR_EXPR
4669                    && auto_var_in_fn_p
4670                         (TREE_OPERAND (TREE_OPERAND (tem, 0), 0), cfun->decl))))
4671         {
4672           struct constraint_expr lhs, *rhsp;
4673           unsigned i;
4674           lhs = get_function_part_constraint (fi, fi_uses);
4675           get_constraint_for_address_of (rhs, &rhsc);
4676           FOR_EACH_VEC_ELT (ce_s, rhsc, i, rhsp)
4677             process_constraint (new_constraint (lhs, *rhsp));
4678           VEC_free (ce_s, heap, rhsc);
4679         }
4680     }
4681
4682   if (is_gimple_call (t))
4683     {
4684       varinfo_t cfi = NULL;
4685       tree decl = gimple_call_fndecl (t);
4686       struct constraint_expr lhs, rhs;
4687       unsigned i, j;
4688
4689       /* For builtins we do not have separate function info.  For those
4690          we do not generate escapes for we have to generate clobbers/uses.  */
4691       if (decl
4692           && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL)
4693         switch (DECL_FUNCTION_CODE (decl))
4694           {
4695           /* The following functions use and clobber memory pointed to
4696              by their arguments.  */
4697           case BUILT_IN_STRCPY:
4698           case BUILT_IN_STRNCPY:
4699           case BUILT_IN_BCOPY:
4700           case BUILT_IN_MEMCPY:
4701           case BUILT_IN_MEMMOVE:
4702           case BUILT_IN_MEMPCPY:
4703           case BUILT_IN_STPCPY:
4704           case BUILT_IN_STPNCPY:
4705           case BUILT_IN_STRCAT:
4706           case BUILT_IN_STRNCAT:
4707             {
4708               tree dest = gimple_call_arg (t, (DECL_FUNCTION_CODE (decl)
4709                                                == BUILT_IN_BCOPY ? 1 : 0));
4710               tree src = gimple_call_arg (t, (DECL_FUNCTION_CODE (decl)
4711                                               == BUILT_IN_BCOPY ? 0 : 1));
4712               unsigned i;
4713               struct constraint_expr *rhsp, *lhsp;
4714               get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4715               lhs = get_function_part_constraint (fi, fi_clobbers);
4716               FOR_EACH_VEC_ELT (ce_s, lhsc, i, lhsp)
4717                 process_constraint (new_constraint (lhs, *lhsp));
4718               VEC_free (ce_s, heap, lhsc);
4719               get_constraint_for_ptr_offset (src, NULL_TREE, &rhsc);
4720               lhs = get_function_part_constraint (fi, fi_uses);
4721               FOR_EACH_VEC_ELT (ce_s, rhsc, i, rhsp)
4722                 process_constraint (new_constraint (lhs, *rhsp));
4723               VEC_free (ce_s, heap, rhsc);
4724               return;
4725             }
4726           /* The following function clobbers memory pointed to by
4727              its argument.  */
4728           case BUILT_IN_MEMSET:
4729             {
4730               tree dest = gimple_call_arg (t, 0);
4731               unsigned i;
4732               ce_s *lhsp;
4733               get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4734               lhs = get_function_part_constraint (fi, fi_clobbers);
4735               FOR_EACH_VEC_ELT (ce_s, lhsc, i, lhsp)
4736                 process_constraint (new_constraint (lhs, *lhsp));
4737               VEC_free (ce_s, heap, lhsc);
4738               return;
4739             }
4740           /* The following functions clobber their second and third
4741              arguments.  */
4742           case BUILT_IN_SINCOS:
4743           case BUILT_IN_SINCOSF:
4744           case BUILT_IN_SINCOSL:
4745             {
4746               process_ipa_clobber (fi, gimple_call_arg (t, 1));
4747               process_ipa_clobber (fi, gimple_call_arg (t, 2));
4748               return;
4749             }
4750           /* The following functions clobber their second argument.  */
4751           case BUILT_IN_FREXP:
4752           case BUILT_IN_FREXPF:
4753           case BUILT_IN_FREXPL:
4754           case BUILT_IN_LGAMMA_R:
4755           case BUILT_IN_LGAMMAF_R:
4756           case BUILT_IN_LGAMMAL_R:
4757           case BUILT_IN_GAMMA_R:
4758           case BUILT_IN_GAMMAF_R:
4759           case BUILT_IN_GAMMAL_R:
4760           case BUILT_IN_MODF:
4761           case BUILT_IN_MODFF:
4762           case BUILT_IN_MODFL:
4763             {
4764               process_ipa_clobber (fi, gimple_call_arg (t, 1));
4765               return;
4766             }
4767           /* The following functions clobber their third argument.  */
4768           case BUILT_IN_REMQUO:
4769           case BUILT_IN_REMQUOF:
4770           case BUILT_IN_REMQUOL:
4771             {
4772               process_ipa_clobber (fi, gimple_call_arg (t, 2));
4773               return;
4774             }
4775           /* The following functions neither read nor clobber memory.  */
4776           case BUILT_IN_FREE:
4777             return;
4778           /* Trampolines are of no interest to us.  */
4779           case BUILT_IN_INIT_TRAMPOLINE:
4780           case BUILT_IN_ADJUST_TRAMPOLINE:
4781             return;
4782           case BUILT_IN_VA_START:
4783           case BUILT_IN_VA_END:
4784             return;
4785           /* printf-style functions may have hooks to set pointers to
4786              point to somewhere into the generated string.  Leave them
4787              for a later excercise...  */
4788           default:
4789             /* Fallthru to general call handling.  */;
4790           }
4791
4792       /* Parameters passed by value are used.  */
4793       lhs = get_function_part_constraint (fi, fi_uses);
4794       for (i = 0; i < gimple_call_num_args (t); i++)
4795         {
4796           struct constraint_expr *rhsp;
4797           tree arg = gimple_call_arg (t, i);
4798
4799           if (TREE_CODE (arg) == SSA_NAME
4800               || is_gimple_min_invariant (arg))
4801             continue;
4802
4803           get_constraint_for_address_of (arg, &rhsc);
4804           FOR_EACH_VEC_ELT (ce_s, rhsc, j, rhsp)
4805             process_constraint (new_constraint (lhs, *rhsp));
4806           VEC_free (ce_s, heap, rhsc);
4807         }
4808
4809       /* Build constraints for propagating clobbers/uses along the
4810          callgraph edges.  */
4811       cfi = get_fi_for_callee (t);
4812       if (cfi->id == anything_id)
4813         {
4814           if (gimple_vdef (t))
4815             make_constraint_from (first_vi_for_offset (fi, fi_clobbers),
4816                                   anything_id);
4817           make_constraint_from (first_vi_for_offset (fi, fi_uses),
4818                                 anything_id);
4819           return;
4820         }
4821
4822       /* For callees without function info (that's external functions),
4823          ESCAPED is clobbered and used.  */
4824       if (gimple_call_fndecl (t)
4825           && !cfi->is_fn_info)
4826         {
4827           varinfo_t vi;
4828
4829           if (gimple_vdef (t))
4830             make_copy_constraint (first_vi_for_offset (fi, fi_clobbers),
4831                                   escaped_id);
4832           make_copy_constraint (first_vi_for_offset (fi, fi_uses), escaped_id);
4833
4834           /* Also honor the call statement use/clobber info.  */
4835           if ((vi = lookup_call_clobber_vi (t)) != NULL)
4836             make_copy_constraint (first_vi_for_offset (fi, fi_clobbers),
4837                                   vi->id);
4838           if ((vi = lookup_call_use_vi (t)) != NULL)
4839             make_copy_constraint (first_vi_for_offset (fi, fi_uses),
4840                                   vi->id);
4841           return;
4842         }
4843
4844       /* Otherwise the caller clobbers and uses what the callee does.
4845          ???  This should use a new complex constraint that filters
4846          local variables of the callee.  */
4847       if (gimple_vdef (t))
4848         {
4849           lhs = get_function_part_constraint (fi, fi_clobbers);
4850           rhs = get_function_part_constraint (cfi, fi_clobbers);
4851           process_constraint (new_constraint (lhs, rhs));
4852         }
4853       lhs = get_function_part_constraint (fi, fi_uses);
4854       rhs = get_function_part_constraint (cfi, fi_uses);
4855       process_constraint (new_constraint (lhs, rhs));
4856     }
4857   else if (gimple_code (t) == GIMPLE_ASM)
4858     {
4859       /* ???  Ick.  We can do better.  */
4860       if (gimple_vdef (t))
4861         make_constraint_from (first_vi_for_offset (fi, fi_clobbers),
4862                               anything_id);
4863       make_constraint_from (first_vi_for_offset (fi, fi_uses),
4864                             anything_id);
4865     }
4866
4867   VEC_free (ce_s, heap, rhsc);
4868 }
4869
4870
4871 /* Find the first varinfo in the same variable as START that overlaps with
4872    OFFSET.  Return NULL if we can't find one.  */
4873
4874 static varinfo_t
4875 first_vi_for_offset (varinfo_t start, unsigned HOST_WIDE_INT offset)
4876 {
4877   /* If the offset is outside of the variable, bail out.  */
4878   if (offset >= start->fullsize)
4879     return NULL;
4880
4881   /* If we cannot reach offset from start, lookup the first field
4882      and start from there.  */
4883   if (start->offset > offset)
4884     start = lookup_vi_for_tree (start->decl);
4885
4886   while (start)
4887     {
4888       /* We may not find a variable in the field list with the actual
4889          offset when when we have glommed a structure to a variable.
4890          In that case, however, offset should still be within the size
4891          of the variable. */
4892       if (offset >= start->offset
4893           && (offset - start->offset) < start->size)
4894         return start;
4895
4896       start= start->next;
4897     }
4898
4899   return NULL;
4900 }
4901
4902 /* Find the first varinfo in the same variable as START that overlaps with
4903    OFFSET.  If there is no such varinfo the varinfo directly preceding
4904    OFFSET is returned.  */
4905
4906 static varinfo_t
4907 first_or_preceding_vi_for_offset (varinfo_t start,
4908                                   unsigned HOST_WIDE_INT offset)
4909 {
4910   /* If we cannot reach offset from start, lookup the first field
4911      and start from there.  */
4912   if (start->offset > offset)
4913     start = lookup_vi_for_tree (start->decl);
4914
4915   /* We may not find a variable in the field list with the actual
4916      offset when when we have glommed a structure to a variable.
4917      In that case, however, offset should still be within the size
4918      of the variable.
4919      If we got beyond the offset we look for return the field
4920      directly preceding offset which may be the last field.  */
4921   while (start->next
4922          && offset >= start->offset
4923          && !((offset - start->offset) < start->size))
4924     start = start->next;
4925
4926   return start;
4927 }
4928
4929
4930 /* This structure is used during pushing fields onto the fieldstack
4931    to track the offset of the field, since bitpos_of_field gives it
4932    relative to its immediate containing type, and we want it relative
4933    to the ultimate containing object.  */
4934
4935 struct fieldoff
4936 {
4937   /* Offset from the base of the base containing object to this field.  */
4938   HOST_WIDE_INT offset;
4939
4940   /* Size, in bits, of the field.  */
4941   unsigned HOST_WIDE_INT size;
4942
4943   unsigned has_unknown_size : 1;
4944
4945   unsigned must_have_pointers : 1;
4946
4947   unsigned may_have_pointers : 1;
4948
4949   unsigned only_restrict_pointers : 1;
4950 };
4951 typedef struct fieldoff fieldoff_s;
4952
4953 DEF_VEC_O(fieldoff_s);
4954 DEF_VEC_ALLOC_O(fieldoff_s,heap);
4955
4956 /* qsort comparison function for two fieldoff's PA and PB */
4957
4958 static int
4959 fieldoff_compare (const void *pa, const void *pb)
4960 {
4961   const fieldoff_s *foa = (const fieldoff_s *)pa;
4962   const fieldoff_s *fob = (const fieldoff_s *)pb;
4963   unsigned HOST_WIDE_INT foasize, fobsize;
4964
4965   if (foa->offset < fob->offset)
4966     return -1;
4967   else if (foa->offset > fob->offset)
4968     return 1;
4969
4970   foasize = foa->size;
4971   fobsize = fob->size;
4972   if (foasize < fobsize)
4973     return -1;
4974   else if (foasize > fobsize)
4975     return 1;
4976   return 0;
4977 }
4978
4979 /* Sort a fieldstack according to the field offset and sizes.  */
4980 static void
4981 sort_fieldstack (VEC(fieldoff_s,heap) *fieldstack)
4982 {
4983   VEC_qsort (fieldoff_s, fieldstack, fieldoff_compare);
4984 }
4985
4986 /* Return true if T is a type that can have subvars.  */
4987
4988 static inline bool
4989 type_can_have_subvars (const_tree t)
4990 {
4991   /* Aggregates without overlapping fields can have subvars.  */
4992   return TREE_CODE (t) == RECORD_TYPE;
4993 }
4994
4995 /* Return true if V is a tree that we can have subvars for.
4996    Normally, this is any aggregate type.  Also complex
4997    types which are not gimple registers can have subvars.  */
4998
4999 static inline bool
5000 var_can_have_subvars (const_tree v)
5001 {
5002   /* Volatile variables should never have subvars.  */
5003   if (TREE_THIS_VOLATILE (v))
5004     return false;
5005
5006   /* Non decls or memory tags can never have subvars.  */
5007   if (!DECL_P (v))
5008     return false;
5009
5010   return type_can_have_subvars (TREE_TYPE (v));
5011 }
5012
5013 /* Return true if T is a type that does contain pointers.  */
5014
5015 static bool
5016 type_must_have_pointers (tree type)
5017 {
5018   if (POINTER_TYPE_P (type))
5019     return true;
5020
5021   if (TREE_CODE (type) == ARRAY_TYPE)
5022     return type_must_have_pointers (TREE_TYPE (type));
5023
5024   /* A function or method can have pointers as arguments, so track
5025      those separately.  */
5026   if (TREE_CODE (type) == FUNCTION_TYPE
5027       || TREE_CODE (type) == METHOD_TYPE)
5028     return true;
5029
5030   return false;
5031 }
5032
5033 static bool
5034 field_must_have_pointers (tree t)
5035 {
5036   return type_must_have_pointers (TREE_TYPE (t));
5037 }
5038
5039 /* Given a TYPE, and a vector of field offsets FIELDSTACK, push all
5040    the fields of TYPE onto fieldstack, recording their offsets along
5041    the way.
5042
5043    OFFSET is used to keep track of the offset in this entire
5044    structure, rather than just the immediately containing structure.
5045    Returns false if the caller is supposed to handle the field we
5046    recursed for.  */
5047
5048 static bool
5049 push_fields_onto_fieldstack (tree type, VEC(fieldoff_s,heap) **fieldstack,
5050                              HOST_WIDE_INT offset)
5051 {
5052   tree field;
5053   bool empty_p = true;
5054
5055   if (TREE_CODE (type) != RECORD_TYPE)
5056     return false;
5057
5058   /* If the vector of fields is growing too big, bail out early.
5059      Callers check for VEC_length <= MAX_FIELDS_FOR_FIELD_SENSITIVE, make
5060      sure this fails.  */
5061   if (VEC_length (fieldoff_s, *fieldstack) > MAX_FIELDS_FOR_FIELD_SENSITIVE)
5062     return false;
5063
5064   for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
5065     if (TREE_CODE (field) == FIELD_DECL)
5066       {
5067         bool push = false;
5068         HOST_WIDE_INT foff = bitpos_of_field (field);
5069
5070         if (!var_can_have_subvars (field)
5071             || TREE_CODE (TREE_TYPE (field)) == QUAL_UNION_TYPE
5072             || TREE_CODE (TREE_TYPE (field)) == UNION_TYPE)
5073           push = true;
5074         else if (!push_fields_onto_fieldstack
5075                     (TREE_TYPE (field), fieldstack, offset + foff)
5076                  && (DECL_SIZE (field)
5077                      && !integer_zerop (DECL_SIZE (field))))
5078           /* Empty structures may have actual size, like in C++.  So
5079              see if we didn't push any subfields and the size is
5080              nonzero, push the field onto the stack.  */
5081           push = true;
5082
5083         if (push)
5084           {
5085             fieldoff_s *pair = NULL;
5086             bool has_unknown_size = false;
5087             bool must_have_pointers_p;
5088
5089             if (!VEC_empty (fieldoff_s, *fieldstack))
5090               pair = VEC_last (fieldoff_s, *fieldstack);
5091
5092             /* If there isn't anything at offset zero, create sth.  */
5093             if (!pair
5094                 && offset + foff != 0)
5095               {
5096                 pair = VEC_safe_push (fieldoff_s, heap, *fieldstack, NULL);
5097                 pair->offset = 0;
5098                 pair->size = offset + foff;
5099                 pair->has_unknown_size = false;
5100                 pair->must_have_pointers = false;
5101                 pair->may_have_pointers = false;
5102                 pair->only_restrict_pointers = false;
5103               }
5104
5105             if (!DECL_SIZE (field)
5106                 || !host_integerp (DECL_SIZE (field), 1))
5107               has_unknown_size = true;
5108
5109             /* If adjacent fields do not contain pointers merge them.  */
5110             must_have_pointers_p = field_must_have_pointers (field);
5111             if (pair
5112                 && !has_unknown_size
5113                 && !must_have_pointers_p
5114                 && !pair->must_have_pointers
5115                 && !pair->has_unknown_size
5116                 && pair->offset + (HOST_WIDE_INT)pair->size == offset + foff)
5117               {
5118                 pair->size += TREE_INT_CST_LOW (DECL_SIZE (field));
5119               }
5120             else
5121               {
5122                 pair = VEC_safe_push (fieldoff_s, heap, *fieldstack, NULL);
5123                 pair->offset = offset + foff;
5124                 pair->has_unknown_size = has_unknown_size;
5125                 if (!has_unknown_size)
5126                   pair->size = TREE_INT_CST_LOW (DECL_SIZE (field));
5127                 else
5128                   pair->size = -1;
5129                 pair->must_have_pointers = must_have_pointers_p;
5130                 pair->may_have_pointers = true;
5131                 pair->only_restrict_pointers
5132                   = (!has_unknown_size
5133                      && POINTER_TYPE_P (TREE_TYPE (field))
5134                      && TYPE_RESTRICT (TREE_TYPE (field)));
5135               }
5136           }
5137
5138         empty_p = false;
5139       }
5140
5141   return !empty_p;
5142 }
5143
5144 /* Count the number of arguments DECL has, and set IS_VARARGS to true
5145    if it is a varargs function.  */
5146
5147 static unsigned int
5148 count_num_arguments (tree decl, bool *is_varargs)
5149 {
5150   unsigned int num = 0;
5151   tree t;
5152
5153   /* Capture named arguments for K&R functions.  They do not
5154      have a prototype and thus no TYPE_ARG_TYPES.  */
5155   for (t = DECL_ARGUMENTS (decl); t; t = DECL_CHAIN (t))
5156     ++num;
5157
5158   /* Check if the function has variadic arguments.  */
5159   for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
5160     if (TREE_VALUE (t) == void_type_node)
5161       break;
5162   if (!t)
5163     *is_varargs = true;
5164
5165   return num;
5166 }
5167
5168 /* Creation function node for DECL, using NAME, and return the index
5169    of the variable we've created for the function.  */
5170
5171 static varinfo_t
5172 create_function_info_for (tree decl, const char *name)
5173 {
5174   struct function *fn = DECL_STRUCT_FUNCTION (decl);
5175   varinfo_t vi, prev_vi;
5176   tree arg;
5177   unsigned int i;
5178   bool is_varargs = false;
5179   unsigned int num_args = count_num_arguments (decl, &is_varargs);
5180
5181   /* Create the variable info.  */
5182
5183   vi = new_var_info (decl, name);
5184   vi->offset = 0;
5185   vi->size = 1;
5186   vi->fullsize = fi_parm_base + num_args;
5187   vi->is_fn_info = 1;
5188   vi->may_have_pointers = false;
5189   if (is_varargs)
5190     vi->fullsize = ~0;
5191   insert_vi_for_tree (vi->decl, vi);
5192
5193   prev_vi = vi;
5194
5195   /* Create a variable for things the function clobbers and one for
5196      things the function uses.  */
5197     {
5198       varinfo_t clobbervi, usevi;
5199       const char *newname;
5200       char *tempname;
5201
5202       asprintf (&tempname, "%s.clobber", name);
5203       newname = ggc_strdup (tempname);
5204       free (tempname);
5205
5206       clobbervi = new_var_info (NULL, newname);
5207       clobbervi->offset = fi_clobbers;
5208       clobbervi->size = 1;
5209       clobbervi->fullsize = vi->fullsize;
5210       clobbervi->is_full_var = true;
5211       clobbervi->is_global_var = false;
5212       gcc_assert (prev_vi->offset < clobbervi->offset);
5213       prev_vi->next = clobbervi;
5214       prev_vi = clobbervi;
5215
5216       asprintf (&tempname, "%s.use", name);
5217       newname = ggc_strdup (tempname);
5218       free (tempname);
5219
5220       usevi = new_var_info (NULL, newname);
5221       usevi->offset = fi_uses;
5222       usevi->size = 1;
5223       usevi->fullsize = vi->fullsize;
5224       usevi->is_full_var = true;
5225       usevi->is_global_var = false;
5226       gcc_assert (prev_vi->offset < usevi->offset);
5227       prev_vi->next = usevi;
5228       prev_vi = usevi;
5229     }
5230
5231   /* And one for the static chain.  */
5232   if (fn->static_chain_decl != NULL_TREE)
5233     {
5234       varinfo_t chainvi;
5235       const char *newname;
5236       char *tempname;
5237
5238       asprintf (&tempname, "%s.chain", name);
5239       newname = ggc_strdup (tempname);
5240       free (tempname);
5241
5242       chainvi = new_var_info (fn->static_chain_decl, newname);
5243       chainvi->offset = fi_static_chain;
5244       chainvi->size = 1;
5245       chainvi->fullsize = vi->fullsize;
5246       chainvi->is_full_var = true;
5247       chainvi->is_global_var = false;
5248       gcc_assert (prev_vi->offset < chainvi->offset);
5249       prev_vi->next = chainvi;
5250       prev_vi = chainvi;
5251       insert_vi_for_tree (fn->static_chain_decl, chainvi);
5252     }
5253
5254   /* Create a variable for the return var.  */
5255   if (DECL_RESULT (decl) != NULL
5256       || !VOID_TYPE_P (TREE_TYPE (TREE_TYPE (decl))))
5257     {
5258       varinfo_t resultvi;
5259       const char *newname;
5260       char *tempname;
5261       tree resultdecl = decl;
5262
5263       if (DECL_RESULT (decl))
5264         resultdecl = DECL_RESULT (decl);
5265
5266       asprintf (&tempname, "%s.result", name);
5267       newname = ggc_strdup (tempname);
5268       free (tempname);
5269
5270       resultvi = new_var_info (resultdecl, newname);
5271       resultvi->offset = fi_result;
5272       resultvi->size = 1;
5273       resultvi->fullsize = vi->fullsize;
5274       resultvi->is_full_var = true;
5275       if (DECL_RESULT (decl))
5276         resultvi->may_have_pointers = true;
5277       gcc_assert (prev_vi->offset < resultvi->offset);
5278       prev_vi->next = resultvi;
5279       prev_vi = resultvi;
5280       if (DECL_RESULT (decl))
5281         insert_vi_for_tree (DECL_RESULT (decl), resultvi);
5282     }
5283
5284   /* Set up variables for each argument.  */
5285   arg = DECL_ARGUMENTS (decl);
5286   for (i = 0; i < num_args; i++)
5287     {
5288       varinfo_t argvi;
5289       const char *newname;
5290       char *tempname;
5291       tree argdecl = decl;
5292
5293       if (arg)
5294         argdecl = arg;
5295
5296       asprintf (&tempname, "%s.arg%d", name, i);
5297       newname = ggc_strdup (tempname);
5298       free (tempname);
5299
5300       argvi = new_var_info (argdecl, newname);
5301       argvi->offset = fi_parm_base + i;
5302       argvi->size = 1;
5303       argvi->is_full_var = true;
5304       argvi->fullsize = vi->fullsize;
5305       if (arg)
5306         argvi->may_have_pointers = true;
5307       gcc_assert (prev_vi->offset < argvi->offset);
5308       prev_vi->next = argvi;
5309       prev_vi = argvi;
5310       if (arg)
5311         {
5312           insert_vi_for_tree (arg, argvi);
5313           arg = DECL_CHAIN (arg);
5314         }
5315     }
5316
5317   /* Add one representative for all further args.  */
5318   if (is_varargs)
5319     {
5320       varinfo_t argvi;
5321       const char *newname;
5322       char *tempname;
5323       tree decl;
5324
5325       asprintf (&tempname, "%s.varargs", name);
5326       newname = ggc_strdup (tempname);
5327       free (tempname);
5328
5329       /* We need sth that can be pointed to for va_start.  */
5330       decl = create_tmp_var_raw (ptr_type_node, name);
5331       get_var_ann (decl);
5332
5333       argvi = new_var_info (decl, newname);
5334       argvi->offset = fi_parm_base + num_args;
5335       argvi->size = ~0;
5336       argvi->is_full_var = true;
5337       argvi->is_heap_var = true;
5338       argvi->fullsize = vi->fullsize;
5339       gcc_assert (prev_vi->offset < argvi->offset);
5340       prev_vi->next = argvi;
5341       prev_vi = argvi;
5342     }
5343
5344   return vi;
5345 }
5346
5347
5348 /* Return true if FIELDSTACK contains fields that overlap.
5349    FIELDSTACK is assumed to be sorted by offset.  */
5350
5351 static bool
5352 check_for_overlaps (VEC (fieldoff_s,heap) *fieldstack)
5353 {
5354   fieldoff_s *fo = NULL;
5355   unsigned int i;
5356   HOST_WIDE_INT lastoffset = -1;
5357
5358   FOR_EACH_VEC_ELT (fieldoff_s, fieldstack, i, fo)
5359     {
5360       if (fo->offset == lastoffset)
5361         return true;
5362       lastoffset = fo->offset;
5363     }
5364   return false;
5365 }
5366
5367 /* Create a varinfo structure for NAME and DECL, and add it to VARMAP.
5368    This will also create any varinfo structures necessary for fields
5369    of DECL.  */
5370
5371 static varinfo_t
5372 create_variable_info_for_1 (tree decl, const char *name)
5373 {
5374   varinfo_t vi, newvi;
5375   tree decl_type = TREE_TYPE (decl);
5376   tree declsize = DECL_P (decl) ? DECL_SIZE (decl) : TYPE_SIZE (decl_type);
5377   VEC (fieldoff_s,heap) *fieldstack = NULL;
5378   fieldoff_s *fo;
5379   unsigned int i;
5380
5381   if (!declsize
5382       || !host_integerp (declsize, 1))
5383     {
5384       vi = new_var_info (decl, name);
5385       vi->offset = 0;
5386       vi->size = ~0;
5387       vi->fullsize = ~0;
5388       vi->is_unknown_size_var = true;
5389       vi->is_full_var = true;
5390       vi->may_have_pointers = true;
5391       return vi;
5392     }
5393
5394   /* Collect field information.  */
5395   if (use_field_sensitive
5396       && var_can_have_subvars (decl)
5397       /* ???  Force us to not use subfields for global initializers
5398          in IPA mode.  Else we'd have to parse arbitrary initializers.  */
5399       && !(in_ipa_mode
5400            && is_global_var (decl)
5401            && DECL_INITIAL (decl)))
5402     {
5403       fieldoff_s *fo = NULL;
5404       bool notokay = false;
5405       unsigned int i;
5406
5407       push_fields_onto_fieldstack (decl_type, &fieldstack, 0);
5408
5409       for (i = 0; !notokay && VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
5410         if (fo->has_unknown_size
5411             || fo->offset < 0)
5412           {
5413             notokay = true;
5414             break;
5415           }
5416
5417       /* We can't sort them if we have a field with a variable sized type,
5418          which will make notokay = true.  In that case, we are going to return
5419          without creating varinfos for the fields anyway, so sorting them is a
5420          waste to boot.  */
5421       if (!notokay)
5422         {
5423           sort_fieldstack (fieldstack);
5424           /* Due to some C++ FE issues, like PR 22488, we might end up
5425              what appear to be overlapping fields even though they,
5426              in reality, do not overlap.  Until the C++ FE is fixed,
5427              we will simply disable field-sensitivity for these cases.  */
5428           notokay = check_for_overlaps (fieldstack);
5429         }
5430
5431       if (notokay)
5432         VEC_free (fieldoff_s, heap, fieldstack);
5433     }
5434
5435   /* If we didn't end up collecting sub-variables create a full
5436      variable for the decl.  */
5437   if (VEC_length (fieldoff_s, fieldstack) <= 1
5438       || VEC_length (fieldoff_s, fieldstack) > MAX_FIELDS_FOR_FIELD_SENSITIVE)
5439     {
5440       vi = new_var_info (decl, name);
5441       vi->offset = 0;
5442       vi->may_have_pointers = true;
5443       vi->fullsize = TREE_INT_CST_LOW (declsize);
5444       vi->size = vi->fullsize;
5445       vi->is_full_var = true;
5446       VEC_free (fieldoff_s, heap, fieldstack);
5447       return vi;
5448     }
5449
5450   vi = new_var_info (decl, name);
5451   vi->fullsize = TREE_INT_CST_LOW (declsize);
5452   for (i = 0, newvi = vi;
5453        VEC_iterate (fieldoff_s, fieldstack, i, fo);
5454        ++i, newvi = newvi->next)
5455     {
5456       const char *newname = "NULL";
5457       char *tempname;
5458
5459       if (dump_file)
5460         {
5461           asprintf (&tempname, "%s." HOST_WIDE_INT_PRINT_DEC
5462                     "+" HOST_WIDE_INT_PRINT_DEC, name, fo->offset, fo->size);
5463           newname = ggc_strdup (tempname);
5464           free (tempname);
5465         }
5466       newvi->name = newname;
5467       newvi->offset = fo->offset;
5468       newvi->size = fo->size;
5469       newvi->fullsize = vi->fullsize;
5470       newvi->may_have_pointers = fo->may_have_pointers;
5471       newvi->only_restrict_pointers = fo->only_restrict_pointers;
5472       if (i + 1 < VEC_length (fieldoff_s, fieldstack))
5473         newvi->next = new_var_info (decl, name);
5474     }
5475
5476   VEC_free (fieldoff_s, heap, fieldstack);
5477
5478   return vi;
5479 }
5480
5481 static unsigned int
5482 create_variable_info_for (tree decl, const char *name)
5483 {
5484   varinfo_t vi = create_variable_info_for_1 (decl, name);
5485   unsigned int id = vi->id;
5486
5487   insert_vi_for_tree (decl, vi);
5488
5489   /* Create initial constraints for globals.  */
5490   for (; vi; vi = vi->next)
5491     {
5492       if (!vi->may_have_pointers
5493           || !vi->is_global_var)
5494         continue;
5495
5496       /* Mark global restrict qualified pointers.  */
5497       if ((POINTER_TYPE_P (TREE_TYPE (decl))
5498            && TYPE_RESTRICT (TREE_TYPE (decl)))
5499           || vi->only_restrict_pointers)
5500         make_constraint_from_restrict (vi, "GLOBAL_RESTRICT");
5501
5502       /* For escaped variables initialize them from nonlocal.  */
5503       if (!in_ipa_mode
5504           || DECL_EXTERNAL (decl) || TREE_PUBLIC (decl))
5505         make_copy_constraint (vi, nonlocal_id);
5506
5507       /* If this is a global variable with an initializer and we are in
5508          IPA mode generate constraints for it.  In non-IPA mode
5509          the initializer from nonlocal is all we need.  */
5510       if (in_ipa_mode
5511           && DECL_INITIAL (decl))
5512         {
5513           VEC (ce_s, heap) *rhsc = NULL;
5514           struct constraint_expr lhs, *rhsp;
5515           unsigned i;
5516           get_constraint_for_rhs (DECL_INITIAL (decl), &rhsc);
5517           lhs.var = vi->id;
5518           lhs.offset = 0;
5519           lhs.type = SCALAR;
5520           FOR_EACH_VEC_ELT (ce_s, rhsc, i, rhsp)
5521             process_constraint (new_constraint (lhs, *rhsp));
5522           /* If this is a variable that escapes from the unit
5523              the initializer escapes as well.  */
5524           if (DECL_EXTERNAL (decl) || TREE_PUBLIC (decl))
5525             {
5526               lhs.var = escaped_id;
5527               lhs.offset = 0;
5528               lhs.type = SCALAR;
5529               FOR_EACH_VEC_ELT (ce_s, rhsc, i, rhsp)
5530                 process_constraint (new_constraint (lhs, *rhsp));
5531             }
5532           VEC_free (ce_s, heap, rhsc);
5533         }
5534     }
5535
5536   return id;
5537 }
5538
5539 /* Print out the points-to solution for VAR to FILE.  */
5540
5541 static void
5542 dump_solution_for_var (FILE *file, unsigned int var)
5543 {
5544   varinfo_t vi = get_varinfo (var);
5545   unsigned int i;
5546   bitmap_iterator bi;
5547
5548   /* Dump the solution for unified vars anyway, this avoids difficulties
5549      in scanning dumps in the testsuite.  */
5550   fprintf (file, "%s = { ", vi->name);
5551   vi = get_varinfo (find (var));
5552   EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
5553     fprintf (file, "%s ", get_varinfo (i)->name);
5554   fprintf (file, "}");
5555
5556   /* But note when the variable was unified.  */
5557   if (vi->id != var)
5558     fprintf (file, " same as %s", vi->name);
5559
5560   fprintf (file, "\n");
5561 }
5562
5563 /* Print the points-to solution for VAR to stdout.  */
5564
5565 DEBUG_FUNCTION void
5566 debug_solution_for_var (unsigned int var)
5567 {
5568   dump_solution_for_var (stdout, var);
5569 }
5570
5571 /* Create varinfo structures for all of the variables in the
5572    function for intraprocedural mode.  */
5573
5574 static void
5575 intra_create_variable_infos (void)
5576 {
5577   tree t;
5578
5579   /* For each incoming pointer argument arg, create the constraint ARG
5580      = NONLOCAL or a dummy variable if it is a restrict qualified
5581      passed-by-reference argument.  */
5582   for (t = DECL_ARGUMENTS (current_function_decl); t; t = DECL_CHAIN (t))
5583     {
5584       varinfo_t p;
5585
5586       /* For restrict qualified pointers to objects passed by
5587          reference build a real representative for the pointed-to object.  */
5588       if (DECL_BY_REFERENCE (t)
5589           && POINTER_TYPE_P (TREE_TYPE (t))
5590           && TYPE_RESTRICT (TREE_TYPE (t)))
5591         {
5592           struct constraint_expr lhsc, rhsc;
5593           varinfo_t vi;
5594           tree heapvar = heapvar_lookup (t, 0);
5595           if (heapvar == NULL_TREE)
5596             {
5597               var_ann_t ann;
5598               heapvar = create_tmp_var_raw (TREE_TYPE (TREE_TYPE (t)),
5599                                             "PARM_NOALIAS");
5600               DECL_EXTERNAL (heapvar) = 1;
5601               heapvar_insert (t, 0, heapvar);
5602               ann = get_var_ann (heapvar);
5603               ann->is_heapvar = 1;
5604             }
5605           if (gimple_referenced_vars (cfun))
5606             add_referenced_var (heapvar);
5607           lhsc.var = get_vi_for_tree (t)->id;
5608           lhsc.type = SCALAR;
5609           lhsc.offset = 0;
5610           rhsc.var = (vi = get_vi_for_tree (heapvar))->id;
5611           rhsc.type = ADDRESSOF;
5612           rhsc.offset = 0;
5613           process_constraint (new_constraint (lhsc, rhsc));
5614           vi->is_restrict_var = 1;
5615           continue;
5616         }
5617
5618       for (p = get_vi_for_tree (t); p; p = p->next)
5619         {
5620           if (p->may_have_pointers)
5621             make_constraint_from (p, nonlocal_id);
5622           if (p->only_restrict_pointers)
5623             make_constraint_from_restrict (p, "PARM_RESTRICT");
5624         }
5625       if (POINTER_TYPE_P (TREE_TYPE (t))
5626           && TYPE_RESTRICT (TREE_TYPE (t)))
5627         make_constraint_from_restrict (get_vi_for_tree (t), "PARM_RESTRICT");
5628     }
5629
5630   /* Add a constraint for a result decl that is passed by reference.  */
5631   if (DECL_RESULT (cfun->decl)
5632       && DECL_BY_REFERENCE (DECL_RESULT (cfun->decl)))
5633     {
5634       varinfo_t p, result_vi = get_vi_for_tree (DECL_RESULT (cfun->decl));
5635
5636       for (p = result_vi; p; p = p->next)
5637         make_constraint_from (p, nonlocal_id);
5638     }
5639
5640   /* Add a constraint for the incoming static chain parameter.  */
5641   if (cfun->static_chain_decl != NULL_TREE)
5642     {
5643       varinfo_t p, chain_vi = get_vi_for_tree (cfun->static_chain_decl);
5644
5645       for (p = chain_vi; p; p = p->next)
5646         make_constraint_from (p, nonlocal_id);
5647     }
5648 }
5649
5650 /* Structure used to put solution bitmaps in a hashtable so they can
5651    be shared among variables with the same points-to set.  */
5652
5653 typedef struct shared_bitmap_info
5654 {
5655   bitmap pt_vars;
5656   hashval_t hashcode;
5657 } *shared_bitmap_info_t;
5658 typedef const struct shared_bitmap_info *const_shared_bitmap_info_t;
5659
5660 static htab_t shared_bitmap_table;
5661
5662 /* Hash function for a shared_bitmap_info_t */
5663
5664 static hashval_t
5665 shared_bitmap_hash (const void *p)
5666 {
5667   const_shared_bitmap_info_t const bi = (const_shared_bitmap_info_t) p;
5668   return bi->hashcode;
5669 }
5670
5671 /* Equality function for two shared_bitmap_info_t's. */
5672
5673 static int
5674 shared_bitmap_eq (const void *p1, const void *p2)
5675 {
5676   const_shared_bitmap_info_t const sbi1 = (const_shared_bitmap_info_t) p1;
5677   const_shared_bitmap_info_t const sbi2 = (const_shared_bitmap_info_t) p2;
5678   return bitmap_equal_p (sbi1->pt_vars, sbi2->pt_vars);
5679 }
5680
5681 /* Lookup a bitmap in the shared bitmap hashtable, and return an already
5682    existing instance if there is one, NULL otherwise.  */
5683
5684 static bitmap
5685 shared_bitmap_lookup (bitmap pt_vars)
5686 {
5687   void **slot;
5688   struct shared_bitmap_info sbi;
5689
5690   sbi.pt_vars = pt_vars;
5691   sbi.hashcode = bitmap_hash (pt_vars);
5692
5693   slot = htab_find_slot_with_hash (shared_bitmap_table, &sbi,
5694                                    sbi.hashcode, NO_INSERT);
5695   if (!slot)
5696     return NULL;
5697   else
5698     return ((shared_bitmap_info_t) *slot)->pt_vars;
5699 }
5700
5701
5702 /* Add a bitmap to the shared bitmap hashtable.  */
5703
5704 static void
5705 shared_bitmap_add (bitmap pt_vars)
5706 {
5707   void **slot;
5708   shared_bitmap_info_t sbi = XNEW (struct shared_bitmap_info);
5709
5710   sbi->pt_vars = pt_vars;
5711   sbi->hashcode = bitmap_hash (pt_vars);
5712
5713   slot = htab_find_slot_with_hash (shared_bitmap_table, sbi,
5714                                    sbi->hashcode, INSERT);
5715   gcc_assert (!*slot);
5716   *slot = (void *) sbi;
5717 }
5718
5719
5720 /* Set bits in INTO corresponding to the variable uids in solution set FROM.  */
5721
5722 static void
5723 set_uids_in_ptset (bitmap into, bitmap from, struct pt_solution *pt)
5724 {
5725   unsigned int i;
5726   bitmap_iterator bi;
5727
5728   EXECUTE_IF_SET_IN_BITMAP (from, 0, i, bi)
5729     {
5730       varinfo_t vi = get_varinfo (i);
5731
5732       /* The only artificial variables that are allowed in a may-alias
5733          set are heap variables.  */
5734       if (vi->is_artificial_var && !vi->is_heap_var)
5735         continue;
5736
5737       if (TREE_CODE (vi->decl) == VAR_DECL
5738           || TREE_CODE (vi->decl) == PARM_DECL
5739           || TREE_CODE (vi->decl) == RESULT_DECL)
5740         {
5741           /* If we are in IPA mode we will not recompute points-to
5742              sets after inlining so make sure they stay valid.  */
5743           if (in_ipa_mode
5744               && !DECL_PT_UID_SET_P (vi->decl))
5745             SET_DECL_PT_UID (vi->decl, DECL_UID (vi->decl));
5746
5747           /* Add the decl to the points-to set.  Note that the points-to
5748              set contains global variables.  */
5749           bitmap_set_bit (into, DECL_PT_UID (vi->decl));
5750           if (vi->is_global_var)
5751             pt->vars_contains_global = true;
5752         }
5753     }
5754 }
5755
5756
5757 /* Compute the points-to solution *PT for the variable VI.  */
5758
5759 static void
5760 find_what_var_points_to (varinfo_t orig_vi, struct pt_solution *pt)
5761 {
5762   unsigned int i;
5763   bitmap_iterator bi;
5764   bitmap finished_solution;
5765   bitmap result;
5766   varinfo_t vi;
5767
5768   memset (pt, 0, sizeof (struct pt_solution));
5769
5770   /* This variable may have been collapsed, let's get the real
5771      variable.  */
5772   vi = get_varinfo (find (orig_vi->id));
5773
5774   /* Translate artificial variables into SSA_NAME_PTR_INFO
5775      attributes.  */
5776   EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
5777     {
5778       varinfo_t vi = get_varinfo (i);
5779
5780       if (vi->is_artificial_var)
5781         {
5782           if (vi->id == nothing_id)
5783             pt->null = 1;
5784           else if (vi->id == escaped_id)
5785             {
5786               if (in_ipa_mode)
5787                 pt->ipa_escaped = 1;
5788               else
5789                 pt->escaped = 1;
5790             }
5791           else if (vi->id == nonlocal_id)
5792             pt->nonlocal = 1;
5793           else if (vi->is_heap_var)
5794             /* We represent heapvars in the points-to set properly.  */
5795             ;
5796           else if (vi->id == readonly_id)
5797             /* Nobody cares.  */
5798             ;
5799           else if (vi->id == anything_id
5800                    || vi->id == integer_id)
5801             pt->anything = 1;
5802         }
5803       if (vi->is_restrict_var)
5804         pt->vars_contains_restrict = true;
5805     }
5806
5807   /* Instead of doing extra work, simply do not create
5808      elaborate points-to information for pt_anything pointers.  */
5809   if (pt->anything
5810       && (orig_vi->is_artificial_var
5811           || !pt->vars_contains_restrict))
5812     return;
5813
5814   /* Share the final set of variables when possible.  */
5815   finished_solution = BITMAP_GGC_ALLOC ();
5816   stats.points_to_sets_created++;
5817
5818   set_uids_in_ptset (finished_solution, vi->solution, pt);
5819   result = shared_bitmap_lookup (finished_solution);
5820   if (!result)
5821     {
5822       shared_bitmap_add (finished_solution);
5823       pt->vars = finished_solution;
5824     }
5825   else
5826     {
5827       pt->vars = result;
5828       bitmap_clear (finished_solution);
5829     }
5830 }
5831
5832 /* Given a pointer variable P, fill in its points-to set.  */
5833
5834 static void
5835 find_what_p_points_to (tree p)
5836 {
5837   struct ptr_info_def *pi;
5838   tree lookup_p = p;
5839   varinfo_t vi;
5840
5841   /* For parameters, get at the points-to set for the actual parm
5842      decl.  */
5843   if (TREE_CODE (p) == SSA_NAME
5844       && (TREE_CODE (SSA_NAME_VAR (p)) == PARM_DECL
5845           || TREE_CODE (SSA_NAME_VAR (p)) == RESULT_DECL)
5846       && SSA_NAME_IS_DEFAULT_DEF (p))
5847     lookup_p = SSA_NAME_VAR (p);
5848
5849   vi = lookup_vi_for_tree (lookup_p);
5850   if (!vi)
5851     return;
5852
5853   pi = get_ptr_info (p);
5854   find_what_var_points_to (vi, &pi->pt);
5855 }
5856
5857
5858 /* Query statistics for points-to solutions.  */
5859
5860 static struct {
5861   unsigned HOST_WIDE_INT pt_solution_includes_may_alias;
5862   unsigned HOST_WIDE_INT pt_solution_includes_no_alias;
5863   unsigned HOST_WIDE_INT pt_solutions_intersect_may_alias;
5864   unsigned HOST_WIDE_INT pt_solutions_intersect_no_alias;
5865 } pta_stats;
5866
5867 void
5868 dump_pta_stats (FILE *s)
5869 {
5870   fprintf (s, "\nPTA query stats:\n");
5871   fprintf (s, "  pt_solution_includes: "
5872            HOST_WIDE_INT_PRINT_DEC" disambiguations, "
5873            HOST_WIDE_INT_PRINT_DEC" queries\n",
5874            pta_stats.pt_solution_includes_no_alias,
5875            pta_stats.pt_solution_includes_no_alias
5876            + pta_stats.pt_solution_includes_may_alias);
5877   fprintf (s, "  pt_solutions_intersect: "
5878            HOST_WIDE_INT_PRINT_DEC" disambiguations, "
5879            HOST_WIDE_INT_PRINT_DEC" queries\n",
5880            pta_stats.pt_solutions_intersect_no_alias,
5881            pta_stats.pt_solutions_intersect_no_alias
5882            + pta_stats.pt_solutions_intersect_may_alias);
5883 }
5884
5885
5886 /* Reset the points-to solution *PT to a conservative default
5887    (point to anything).  */
5888
5889 void
5890 pt_solution_reset (struct pt_solution *pt)
5891 {
5892   memset (pt, 0, sizeof (struct pt_solution));
5893   pt->anything = true;
5894 }
5895
5896 /* Set the points-to solution *PT to point only to the variables
5897    in VARS.  VARS_CONTAINS_GLOBAL specifies whether that contains
5898    global variables and VARS_CONTAINS_RESTRICT specifies whether
5899    it contains restrict tag variables.  */
5900
5901 void
5902 pt_solution_set (struct pt_solution *pt, bitmap vars,
5903                  bool vars_contains_global, bool vars_contains_restrict)
5904 {
5905   memset (pt, 0, sizeof (struct pt_solution));
5906   pt->vars = vars;
5907   pt->vars_contains_global = vars_contains_global;
5908   pt->vars_contains_restrict = vars_contains_restrict;
5909 }
5910
5911 /* Set the points-to solution *PT to point only to the variable VAR.  */
5912
5913 void
5914 pt_solution_set_var (struct pt_solution *pt, tree var)
5915 {
5916   memset (pt, 0, sizeof (struct pt_solution));
5917   pt->vars = BITMAP_GGC_ALLOC ();
5918   bitmap_set_bit (pt->vars, DECL_PT_UID (var));
5919   pt->vars_contains_global = is_global_var (var);
5920 }
5921
5922 /* Computes the union of the points-to solutions *DEST and *SRC and
5923    stores the result in *DEST.  This changes the points-to bitmap
5924    of *DEST and thus may not be used if that might be shared.
5925    The points-to bitmap of *SRC and *DEST will not be shared after
5926    this function if they were not before.  */
5927
5928 static void
5929 pt_solution_ior_into (struct pt_solution *dest, struct pt_solution *src)
5930 {
5931   dest->anything |= src->anything;
5932   if (dest->anything)
5933     {
5934       pt_solution_reset (dest);
5935       return;
5936     }
5937
5938   dest->nonlocal |= src->nonlocal;
5939   dest->escaped |= src->escaped;
5940   dest->ipa_escaped |= src->ipa_escaped;
5941   dest->null |= src->null;
5942   dest->vars_contains_global |= src->vars_contains_global;
5943   dest->vars_contains_restrict |= src->vars_contains_restrict;
5944   if (!src->vars)
5945     return;
5946
5947   if (!dest->vars)
5948     dest->vars = BITMAP_GGC_ALLOC ();
5949   bitmap_ior_into (dest->vars, src->vars);
5950 }
5951
5952 /* Return true if the points-to solution *PT is empty.  */
5953
5954 bool
5955 pt_solution_empty_p (struct pt_solution *pt)
5956 {
5957   if (pt->anything
5958       || pt->nonlocal)
5959     return false;
5960
5961   if (pt->vars
5962       && !bitmap_empty_p (pt->vars))
5963     return false;
5964
5965   /* If the solution includes ESCAPED, check if that is empty.  */
5966   if (pt->escaped
5967       && !pt_solution_empty_p (&cfun->gimple_df->escaped))
5968     return false;
5969
5970   /* If the solution includes ESCAPED, check if that is empty.  */
5971   if (pt->ipa_escaped
5972       && !pt_solution_empty_p (&ipa_escaped_pt))
5973     return false;
5974
5975   return true;
5976 }
5977
5978 /* Return true if the points-to solution *PT includes global memory.  */
5979
5980 bool
5981 pt_solution_includes_global (struct pt_solution *pt)
5982 {
5983   if (pt->anything
5984       || pt->nonlocal
5985       || pt->vars_contains_global)
5986     return true;
5987
5988   if (pt->escaped)
5989     return pt_solution_includes_global (&cfun->gimple_df->escaped);
5990
5991   if (pt->ipa_escaped)
5992     return pt_solution_includes_global (&ipa_escaped_pt);
5993
5994   /* ???  This predicate is not correct for the IPA-PTA solution
5995      as we do not properly distinguish between unit escape points
5996      and global variables.  */
5997   if (cfun->gimple_df->ipa_pta)
5998     return true;
5999
6000   return false;
6001 }
6002
6003 /* Return true if the points-to solution *PT includes the variable
6004    declaration DECL.  */
6005
6006 static bool
6007 pt_solution_includes_1 (struct pt_solution *pt, const_tree decl)
6008 {
6009   if (pt->anything)
6010     return true;
6011
6012   if (pt->nonlocal
6013       && is_global_var (decl))
6014     return true;
6015
6016   if (pt->vars
6017       && bitmap_bit_p (pt->vars, DECL_PT_UID (decl)))
6018     return true;
6019
6020   /* If the solution includes ESCAPED, check it.  */
6021   if (pt->escaped
6022       && pt_solution_includes_1 (&cfun->gimple_df->escaped, decl))
6023     return true;
6024
6025   /* If the solution includes ESCAPED, check it.  */
6026   if (pt->ipa_escaped
6027       && pt_solution_includes_1 (&ipa_escaped_pt, decl))
6028     return true;
6029
6030   return false;
6031 }
6032
6033 bool
6034 pt_solution_includes (struct pt_solution *pt, const_tree decl)
6035 {
6036   bool res = pt_solution_includes_1 (pt, decl);
6037   if (res)
6038     ++pta_stats.pt_solution_includes_may_alias;
6039   else
6040     ++pta_stats.pt_solution_includes_no_alias;
6041   return res;
6042 }
6043
6044 /* Return true if both points-to solutions PT1 and PT2 have a non-empty
6045    intersection.  */
6046
6047 static bool
6048 pt_solutions_intersect_1 (struct pt_solution *pt1, struct pt_solution *pt2)
6049 {
6050   if (pt1->anything || pt2->anything)
6051     return true;
6052
6053   /* If either points to unknown global memory and the other points to
6054      any global memory they alias.  */
6055   if ((pt1->nonlocal
6056        && (pt2->nonlocal
6057            || pt2->vars_contains_global))
6058       || (pt2->nonlocal
6059           && pt1->vars_contains_global))
6060     return true;
6061
6062   /* Check the escaped solution if required.  */
6063   if ((pt1->escaped || pt2->escaped)
6064       && !pt_solution_empty_p (&cfun->gimple_df->escaped))
6065     {
6066       /* If both point to escaped memory and that solution
6067          is not empty they alias.  */
6068       if (pt1->escaped && pt2->escaped)
6069         return true;
6070
6071       /* If either points to escaped memory see if the escaped solution
6072          intersects with the other.  */
6073       if ((pt1->escaped
6074            && pt_solutions_intersect_1 (&cfun->gimple_df->escaped, pt2))
6075           || (pt2->escaped
6076               && pt_solutions_intersect_1 (&cfun->gimple_df->escaped, pt1)))
6077         return true;
6078     }
6079
6080   /* Check the escaped solution if required.
6081      ???  Do we need to check the local against the IPA escaped sets?  */
6082   if ((pt1->ipa_escaped || pt2->ipa_escaped)
6083       && !pt_solution_empty_p (&ipa_escaped_pt))
6084     {
6085       /* If both point to escaped memory and that solution
6086          is not empty they alias.  */
6087       if (pt1->ipa_escaped && pt2->ipa_escaped)
6088         return true;
6089
6090       /* If either points to escaped memory see if the escaped solution
6091          intersects with the other.  */
6092       if ((pt1->ipa_escaped
6093            && pt_solutions_intersect_1 (&ipa_escaped_pt, pt2))
6094           || (pt2->ipa_escaped
6095               && pt_solutions_intersect_1 (&ipa_escaped_pt, pt1)))
6096         return true;
6097     }
6098
6099   /* Now both pointers alias if their points-to solution intersects.  */
6100   return (pt1->vars
6101           && pt2->vars
6102           && bitmap_intersect_p (pt1->vars, pt2->vars));
6103 }
6104
6105 bool
6106 pt_solutions_intersect (struct pt_solution *pt1, struct pt_solution *pt2)
6107 {
6108   bool res = pt_solutions_intersect_1 (pt1, pt2);
6109   if (res)
6110     ++pta_stats.pt_solutions_intersect_may_alias;
6111   else
6112     ++pta_stats.pt_solutions_intersect_no_alias;
6113   return res;
6114 }
6115
6116 /* Return true if both points-to solutions PT1 and PT2 for two restrict
6117    qualified pointers are possibly based on the same pointer.  */
6118
6119 bool
6120 pt_solutions_same_restrict_base (struct pt_solution *pt1,
6121                                  struct pt_solution *pt2)
6122 {
6123   /* If we deal with points-to solutions of two restrict qualified
6124      pointers solely rely on the pointed-to variable bitmap intersection.
6125      For two pointers that are based on each other the bitmaps will
6126      intersect.  */
6127   if (pt1->vars_contains_restrict
6128       && pt2->vars_contains_restrict)
6129     {
6130       gcc_assert (pt1->vars && pt2->vars);
6131       return bitmap_intersect_p (pt1->vars, pt2->vars);
6132     }
6133
6134   return true;
6135 }
6136
6137
6138 /* Dump points-to information to OUTFILE.  */
6139
6140 static void
6141 dump_sa_points_to_info (FILE *outfile)
6142 {
6143   unsigned int i;
6144
6145   fprintf (outfile, "\nPoints-to sets\n\n");
6146
6147   if (dump_flags & TDF_STATS)
6148     {
6149       fprintf (outfile, "Stats:\n");
6150       fprintf (outfile, "Total vars:               %d\n", stats.total_vars);
6151       fprintf (outfile, "Non-pointer vars:          %d\n",
6152                stats.nonpointer_vars);
6153       fprintf (outfile, "Statically unified vars:  %d\n",
6154                stats.unified_vars_static);
6155       fprintf (outfile, "Dynamically unified vars: %d\n",
6156                stats.unified_vars_dynamic);
6157       fprintf (outfile, "Iterations:               %d\n", stats.iterations);
6158       fprintf (outfile, "Number of edges:          %d\n", stats.num_edges);
6159       fprintf (outfile, "Number of implicit edges: %d\n",
6160                stats.num_implicit_edges);
6161     }
6162
6163   for (i = 0; i < VEC_length (varinfo_t, varmap); i++)
6164     {
6165       varinfo_t vi = get_varinfo (i);
6166       if (!vi->may_have_pointers)
6167         continue;
6168       dump_solution_for_var (outfile, i);
6169     }
6170 }
6171
6172
6173 /* Debug points-to information to stderr.  */
6174
6175 DEBUG_FUNCTION void
6176 debug_sa_points_to_info (void)
6177 {
6178   dump_sa_points_to_info (stderr);
6179 }
6180
6181
6182 /* Initialize the always-existing constraint variables for NULL
6183    ANYTHING, READONLY, and INTEGER */
6184
6185 static void
6186 init_base_vars (void)
6187 {
6188   struct constraint_expr lhs, rhs;
6189   varinfo_t var_anything;
6190   varinfo_t var_nothing;
6191   varinfo_t var_readonly;
6192   varinfo_t var_escaped;
6193   varinfo_t var_nonlocal;
6194   varinfo_t var_storedanything;
6195   varinfo_t var_integer;
6196
6197   /* Create the NULL variable, used to represent that a variable points
6198      to NULL.  */
6199   var_nothing = new_var_info (NULL_TREE, "NULL");
6200   gcc_assert (var_nothing->id == nothing_id);
6201   var_nothing->is_artificial_var = 1;
6202   var_nothing->offset = 0;
6203   var_nothing->size = ~0;
6204   var_nothing->fullsize = ~0;
6205   var_nothing->is_special_var = 1;
6206   var_nothing->may_have_pointers = 0;
6207   var_nothing->is_global_var = 0;
6208
6209   /* Create the ANYTHING variable, used to represent that a variable
6210      points to some unknown piece of memory.  */
6211   var_anything = new_var_info (NULL_TREE, "ANYTHING");
6212   gcc_assert (var_anything->id == anything_id);
6213   var_anything->is_artificial_var = 1;
6214   var_anything->size = ~0;
6215   var_anything->offset = 0;
6216   var_anything->next = NULL;
6217   var_anything->fullsize = ~0;
6218   var_anything->is_special_var = 1;
6219
6220   /* Anything points to anything.  This makes deref constraints just
6221      work in the presence of linked list and other p = *p type loops,
6222      by saying that *ANYTHING = ANYTHING. */
6223   lhs.type = SCALAR;
6224   lhs.var = anything_id;
6225   lhs.offset = 0;
6226   rhs.type = ADDRESSOF;
6227   rhs.var = anything_id;
6228   rhs.offset = 0;
6229
6230   /* This specifically does not use process_constraint because
6231      process_constraint ignores all anything = anything constraints, since all
6232      but this one are redundant.  */
6233   VEC_safe_push (constraint_t, heap, constraints, new_constraint (lhs, rhs));
6234
6235   /* Create the READONLY variable, used to represent that a variable
6236      points to readonly memory.  */
6237   var_readonly = new_var_info (NULL_TREE, "READONLY");
6238   gcc_assert (var_readonly->id == readonly_id);
6239   var_readonly->is_artificial_var = 1;
6240   var_readonly->offset = 0;
6241   var_readonly->size = ~0;
6242   var_readonly->fullsize = ~0;
6243   var_readonly->next = NULL;
6244   var_readonly->is_special_var = 1;
6245
6246   /* readonly memory points to anything, in order to make deref
6247      easier.  In reality, it points to anything the particular
6248      readonly variable can point to, but we don't track this
6249      separately. */
6250   lhs.type = SCALAR;
6251   lhs.var = readonly_id;
6252   lhs.offset = 0;
6253   rhs.type = ADDRESSOF;
6254   rhs.var = readonly_id;  /* FIXME */
6255   rhs.offset = 0;
6256   process_constraint (new_constraint (lhs, rhs));
6257
6258   /* Create the ESCAPED variable, used to represent the set of escaped
6259      memory.  */
6260   var_escaped = new_var_info (NULL_TREE, "ESCAPED");
6261   gcc_assert (var_escaped->id == escaped_id);
6262   var_escaped->is_artificial_var = 1;
6263   var_escaped->offset = 0;
6264   var_escaped->size = ~0;
6265   var_escaped->fullsize = ~0;
6266   var_escaped->is_special_var = 0;
6267
6268   /* Create the NONLOCAL variable, used to represent the set of nonlocal
6269      memory.  */
6270   var_nonlocal = new_var_info (NULL_TREE, "NONLOCAL");
6271   gcc_assert (var_nonlocal->id == nonlocal_id);
6272   var_nonlocal->is_artificial_var = 1;
6273   var_nonlocal->offset = 0;
6274   var_nonlocal->size = ~0;
6275   var_nonlocal->fullsize = ~0;
6276   var_nonlocal->is_special_var = 1;
6277
6278   /* ESCAPED = *ESCAPED, because escaped is may-deref'd at calls, etc.  */
6279   lhs.type = SCALAR;
6280   lhs.var = escaped_id;
6281   lhs.offset = 0;
6282   rhs.type = DEREF;
6283   rhs.var = escaped_id;
6284   rhs.offset = 0;
6285   process_constraint (new_constraint (lhs, rhs));
6286
6287   /* ESCAPED = ESCAPED + UNKNOWN_OFFSET, because if a sub-field escapes the
6288      whole variable escapes.  */
6289   lhs.type = SCALAR;
6290   lhs.var = escaped_id;
6291   lhs.offset = 0;
6292   rhs.type = SCALAR;
6293   rhs.var = escaped_id;
6294   rhs.offset = UNKNOWN_OFFSET;
6295   process_constraint (new_constraint (lhs, rhs));
6296
6297   /* *ESCAPED = NONLOCAL.  This is true because we have to assume
6298      everything pointed to by escaped points to what global memory can
6299      point to.  */
6300   lhs.type = DEREF;
6301   lhs.var = escaped_id;
6302   lhs.offset = 0;
6303   rhs.type = SCALAR;
6304   rhs.var = nonlocal_id;
6305   rhs.offset = 0;
6306   process_constraint (new_constraint (lhs, rhs));
6307
6308   /* NONLOCAL = &NONLOCAL, NONLOCAL = &ESCAPED.  This is true because
6309      global memory may point to global memory and escaped memory.  */
6310   lhs.type = SCALAR;
6311   lhs.var = nonlocal_id;
6312   lhs.offset = 0;
6313   rhs.type = ADDRESSOF;
6314   rhs.var = nonlocal_id;
6315   rhs.offset = 0;
6316   process_constraint (new_constraint (lhs, rhs));
6317   rhs.type = ADDRESSOF;
6318   rhs.var = escaped_id;
6319   rhs.offset = 0;
6320   process_constraint (new_constraint (lhs, rhs));
6321
6322   /* Create the STOREDANYTHING variable, used to represent the set of
6323      variables stored to *ANYTHING.  */
6324   var_storedanything = new_var_info (NULL_TREE, "STOREDANYTHING");
6325   gcc_assert (var_storedanything->id == storedanything_id);
6326   var_storedanything->is_artificial_var = 1;
6327   var_storedanything->offset = 0;
6328   var_storedanything->size = ~0;
6329   var_storedanything->fullsize = ~0;
6330   var_storedanything->is_special_var = 0;
6331
6332   /* Create the INTEGER variable, used to represent that a variable points
6333      to what an INTEGER "points to".  */
6334   var_integer = new_var_info (NULL_TREE, "INTEGER");
6335   gcc_assert (var_integer->id == integer_id);
6336   var_integer->is_artificial_var = 1;
6337   var_integer->size = ~0;
6338   var_integer->fullsize = ~0;
6339   var_integer->offset = 0;
6340   var_integer->next = NULL;
6341   var_integer->is_special_var = 1;
6342
6343   /* INTEGER = ANYTHING, because we don't know where a dereference of
6344      a random integer will point to.  */
6345   lhs.type = SCALAR;
6346   lhs.var = integer_id;
6347   lhs.offset = 0;
6348   rhs.type = ADDRESSOF;
6349   rhs.var = anything_id;
6350   rhs.offset = 0;
6351   process_constraint (new_constraint (lhs, rhs));
6352 }
6353
6354 /* Initialize things necessary to perform PTA */
6355
6356 static void
6357 init_alias_vars (void)
6358 {
6359   use_field_sensitive = (MAX_FIELDS_FOR_FIELD_SENSITIVE > 1);
6360
6361   bitmap_obstack_initialize (&pta_obstack);
6362   bitmap_obstack_initialize (&oldpta_obstack);
6363   bitmap_obstack_initialize (&predbitmap_obstack);
6364
6365   constraint_pool = create_alloc_pool ("Constraint pool",
6366                                        sizeof (struct constraint), 30);
6367   variable_info_pool = create_alloc_pool ("Variable info pool",
6368                                           sizeof (struct variable_info), 30);
6369   constraints = VEC_alloc (constraint_t, heap, 8);
6370   varmap = VEC_alloc (varinfo_t, heap, 8);
6371   vi_for_tree = pointer_map_create ();
6372   call_stmt_vars = pointer_map_create ();
6373
6374   memset (&stats, 0, sizeof (stats));
6375   shared_bitmap_table = htab_create (511, shared_bitmap_hash,
6376                                      shared_bitmap_eq, free);
6377   init_base_vars ();
6378 }
6379
6380 /* Remove the REF and ADDRESS edges from GRAPH, as well as all the
6381    predecessor edges.  */
6382
6383 static void
6384 remove_preds_and_fake_succs (constraint_graph_t graph)
6385 {
6386   unsigned int i;
6387
6388   /* Clear the implicit ref and address nodes from the successor
6389      lists.  */
6390   for (i = 0; i < FIRST_REF_NODE; i++)
6391     {
6392       if (graph->succs[i])
6393         bitmap_clear_range (graph->succs[i], FIRST_REF_NODE,
6394                             FIRST_REF_NODE * 2);
6395     }
6396
6397   /* Free the successor list for the non-ref nodes.  */
6398   for (i = FIRST_REF_NODE; i < graph->size; i++)
6399     {
6400       if (graph->succs[i])
6401         BITMAP_FREE (graph->succs[i]);
6402     }
6403
6404   /* Now reallocate the size of the successor list as, and blow away
6405      the predecessor bitmaps.  */
6406   graph->size = VEC_length (varinfo_t, varmap);
6407   graph->succs = XRESIZEVEC (bitmap, graph->succs, graph->size);
6408
6409   free (graph->implicit_preds);
6410   graph->implicit_preds = NULL;
6411   free (graph->preds);
6412   graph->preds = NULL;
6413   bitmap_obstack_release (&predbitmap_obstack);
6414 }
6415
6416 /* Initialize the heapvar for statement mapping.  */
6417
6418 static void
6419 init_alias_heapvars (void)
6420 {
6421   if (!heapvar_for_stmt)
6422     heapvar_for_stmt = htab_create_ggc (11, tree_map_hash, heapvar_map_eq,
6423                                         NULL);
6424 }
6425
6426 /* Delete the heapvar for statement mapping.  */
6427
6428 void
6429 delete_alias_heapvars (void)
6430 {
6431   if (heapvar_for_stmt)
6432     htab_delete (heapvar_for_stmt);
6433   heapvar_for_stmt = NULL;
6434 }
6435
6436 /* Solve the constraint set.  */
6437
6438 static void
6439 solve_constraints (void)
6440 {
6441   struct scc_info *si;
6442
6443   if (dump_file)
6444     fprintf (dump_file,
6445              "\nCollapsing static cycles and doing variable "
6446              "substitution\n");
6447
6448   init_graph (VEC_length (varinfo_t, varmap) * 2);
6449
6450   if (dump_file)
6451     fprintf (dump_file, "Building predecessor graph\n");
6452   build_pred_graph ();
6453
6454   if (dump_file)
6455     fprintf (dump_file, "Detecting pointer and location "
6456              "equivalences\n");
6457   si = perform_var_substitution (graph);
6458
6459   if (dump_file)
6460     fprintf (dump_file, "Rewriting constraints and unifying "
6461              "variables\n");
6462   rewrite_constraints (graph, si);
6463
6464   build_succ_graph ();
6465   free_var_substitution_info (si);
6466
6467   if (dump_file && (dump_flags & TDF_GRAPH))
6468     dump_constraint_graph (dump_file);
6469
6470   move_complex_constraints (graph);
6471
6472   if (dump_file)
6473     fprintf (dump_file, "Uniting pointer but not location equivalent "
6474              "variables\n");
6475   unite_pointer_equivalences (graph);
6476
6477   if (dump_file)
6478     fprintf (dump_file, "Finding indirect cycles\n");
6479   find_indirect_cycles (graph);
6480
6481   /* Implicit nodes and predecessors are no longer necessary at this
6482      point. */
6483   remove_preds_and_fake_succs (graph);
6484
6485   if (dump_file)
6486     fprintf (dump_file, "Solving graph\n");
6487
6488   solve_graph (graph);
6489
6490   if (dump_file)
6491     dump_sa_points_to_info (dump_file);
6492 }
6493
6494 /* Create points-to sets for the current function.  See the comments
6495    at the start of the file for an algorithmic overview.  */
6496
6497 static void
6498 compute_points_to_sets (void)
6499 {
6500   basic_block bb;
6501   unsigned i;
6502   varinfo_t vi;
6503
6504   timevar_push (TV_TREE_PTA);
6505
6506   init_alias_vars ();
6507   init_alias_heapvars ();
6508
6509   intra_create_variable_infos ();
6510
6511   /* Now walk all statements and build the constraint set.  */
6512   FOR_EACH_BB (bb)
6513     {
6514       gimple_stmt_iterator gsi;
6515
6516       for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6517         {
6518           gimple phi = gsi_stmt (gsi);
6519
6520           if (is_gimple_reg (gimple_phi_result (phi)))
6521             find_func_aliases (phi);
6522         }
6523
6524       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6525         {
6526           gimple stmt = gsi_stmt (gsi);
6527
6528           find_func_aliases (stmt);
6529         }
6530     }
6531
6532   if (dump_file)
6533     {
6534       fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
6535       dump_constraints (dump_file, 0);
6536     }
6537
6538   /* From the constraints compute the points-to sets.  */
6539   solve_constraints ();
6540
6541   /* Compute the points-to set for ESCAPED used for call-clobber analysis.  */
6542   find_what_var_points_to (get_varinfo (escaped_id),
6543                            &cfun->gimple_df->escaped);
6544
6545   /* Make sure the ESCAPED solution (which is used as placeholder in
6546      other solutions) does not reference itself.  This simplifies
6547      points-to solution queries.  */
6548   cfun->gimple_df->escaped.escaped = 0;
6549
6550   /* Mark escaped HEAP variables as global.  */
6551   FOR_EACH_VEC_ELT (varinfo_t, varmap, i, vi)
6552     if (vi->is_heap_var
6553         && !vi->is_restrict_var
6554         && !vi->is_global_var)
6555       DECL_EXTERNAL (vi->decl) = vi->is_global_var
6556         = pt_solution_includes (&cfun->gimple_df->escaped, vi->decl);
6557
6558   /* Compute the points-to sets for pointer SSA_NAMEs.  */
6559   for (i = 0; i < num_ssa_names; ++i)
6560     {
6561       tree ptr = ssa_name (i);
6562       if (ptr
6563           && POINTER_TYPE_P (TREE_TYPE (ptr)))
6564         find_what_p_points_to (ptr);
6565     }
6566
6567   /* Compute the call-used/clobbered sets.  */
6568   FOR_EACH_BB (bb)
6569     {
6570       gimple_stmt_iterator gsi;
6571
6572       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6573         {
6574           gimple stmt = gsi_stmt (gsi);
6575           struct pt_solution *pt;
6576           if (!is_gimple_call (stmt))
6577             continue;
6578
6579           pt = gimple_call_use_set (stmt);
6580           if (gimple_call_flags (stmt) & ECF_CONST)
6581             memset (pt, 0, sizeof (struct pt_solution));
6582           else if ((vi = lookup_call_use_vi (stmt)) != NULL)
6583             {
6584               find_what_var_points_to (vi, pt);
6585               /* Escaped (and thus nonlocal) variables are always
6586                  implicitly used by calls.  */
6587               /* ???  ESCAPED can be empty even though NONLOCAL
6588                  always escaped.  */
6589               pt->nonlocal = 1;
6590               pt->escaped = 1;
6591             }
6592           else
6593             {
6594               /* If there is nothing special about this call then
6595                  we have made everything that is used also escape.  */
6596               *pt = cfun->gimple_df->escaped;
6597               pt->nonlocal = 1;
6598             }
6599
6600           pt = gimple_call_clobber_set (stmt);
6601           if (gimple_call_flags (stmt) & (ECF_CONST|ECF_PURE|ECF_NOVOPS))
6602             memset (pt, 0, sizeof (struct pt_solution));
6603           else if ((vi = lookup_call_clobber_vi (stmt)) != NULL)
6604             {
6605               find_what_var_points_to (vi, pt);
6606               /* Escaped (and thus nonlocal) variables are always
6607                  implicitly clobbered by calls.  */
6608               /* ???  ESCAPED can be empty even though NONLOCAL
6609                  always escaped.  */
6610               pt->nonlocal = 1;
6611               pt->escaped = 1;
6612             }
6613           else
6614             {
6615               /* If there is nothing special about this call then
6616                  we have made everything that is used also escape.  */
6617               *pt = cfun->gimple_df->escaped;
6618               pt->nonlocal = 1;
6619             }
6620         }
6621     }
6622
6623   timevar_pop (TV_TREE_PTA);
6624 }
6625
6626
6627 /* Delete created points-to sets.  */
6628
6629 static void
6630 delete_points_to_sets (void)
6631 {
6632   unsigned int i;
6633
6634   htab_delete (shared_bitmap_table);
6635   if (dump_file && (dump_flags & TDF_STATS))
6636     fprintf (dump_file, "Points to sets created:%d\n",
6637              stats.points_to_sets_created);
6638
6639   pointer_map_destroy (vi_for_tree);
6640   pointer_map_destroy (call_stmt_vars);
6641   bitmap_obstack_release (&pta_obstack);
6642   VEC_free (constraint_t, heap, constraints);
6643
6644   for (i = 0; i < graph->size; i++)
6645     VEC_free (constraint_t, heap, graph->complex[i]);
6646   free (graph->complex);
6647
6648   free (graph->rep);
6649   free (graph->succs);
6650   free (graph->pe);
6651   free (graph->pe_rep);
6652   free (graph->indirect_cycles);
6653   free (graph);
6654
6655   VEC_free (varinfo_t, heap, varmap);
6656   free_alloc_pool (variable_info_pool);
6657   free_alloc_pool (constraint_pool);
6658 }
6659
6660
6661 /* Compute points-to information for every SSA_NAME pointer in the
6662    current function and compute the transitive closure of escaped
6663    variables to re-initialize the call-clobber states of local variables.  */
6664
6665 unsigned int
6666 compute_may_aliases (void)
6667 {
6668   if (cfun->gimple_df->ipa_pta)
6669     {
6670       if (dump_file)
6671         {
6672           fprintf (dump_file, "\nNot re-computing points-to information "
6673                    "because IPA points-to information is available.\n\n");
6674
6675           /* But still dump what we have remaining it.  */
6676           dump_alias_info (dump_file);
6677
6678           if (dump_flags & TDF_DETAILS)
6679             dump_referenced_vars (dump_file);
6680         }
6681
6682       return 0;
6683     }
6684
6685   /* For each pointer P_i, determine the sets of variables that P_i may
6686      point-to.  Compute the reachability set of escaped and call-used
6687      variables.  */
6688   compute_points_to_sets ();
6689
6690   /* Debugging dumps.  */
6691   if (dump_file)
6692     {
6693       dump_alias_info (dump_file);
6694
6695       if (dump_flags & TDF_DETAILS)
6696         dump_referenced_vars (dump_file);
6697     }
6698
6699   /* Deallocate memory used by aliasing data structures and the internal
6700      points-to solution.  */
6701   delete_points_to_sets ();
6702
6703   gcc_assert (!need_ssa_update_p (cfun));
6704
6705   return 0;
6706 }
6707
6708 static bool
6709 gate_tree_pta (void)
6710 {
6711   return flag_tree_pta;
6712 }
6713
6714 /* A dummy pass to cause points-to information to be computed via
6715    TODO_rebuild_alias.  */
6716
6717 struct gimple_opt_pass pass_build_alias =
6718 {
6719  {
6720   GIMPLE_PASS,
6721   "alias",                  /* name */
6722   gate_tree_pta,            /* gate */
6723   NULL,                     /* execute */
6724   NULL,                     /* sub */
6725   NULL,                     /* next */
6726   0,                        /* static_pass_number */
6727   TV_NONE,                  /* tv_id */
6728   PROP_cfg | PROP_ssa,      /* properties_required */
6729   0,                        /* properties_provided */
6730   0,                        /* properties_destroyed */
6731   0,                        /* todo_flags_start */
6732   TODO_rebuild_alias | TODO_dump_func  /* todo_flags_finish */
6733  }
6734 };
6735
6736 /* A dummy pass to cause points-to information to be computed via
6737    TODO_rebuild_alias.  */
6738
6739 struct gimple_opt_pass pass_build_ealias =
6740 {
6741  {
6742   GIMPLE_PASS,
6743   "ealias",                 /* name */
6744   gate_tree_pta,            /* gate */
6745   NULL,                     /* execute */
6746   NULL,                     /* sub */
6747   NULL,                     /* next */
6748   0,                        /* static_pass_number */
6749   TV_NONE,                  /* tv_id */
6750   PROP_cfg | PROP_ssa,      /* properties_required */
6751   0,                        /* properties_provided */
6752   0,                        /* properties_destroyed */
6753   0,                        /* todo_flags_start */
6754   TODO_rebuild_alias | TODO_dump_func  /* todo_flags_finish */
6755  }
6756 };
6757
6758
6759 /* Return true if we should execute IPA PTA.  */
6760 static bool
6761 gate_ipa_pta (void)
6762 {
6763   return (optimize
6764           && flag_ipa_pta
6765           /* Don't bother doing anything if the program has errors.  */
6766           && !seen_error ());
6767 }
6768
6769 /* IPA PTA solutions for ESCAPED.  */
6770 struct pt_solution ipa_escaped_pt
6771   = { true, false, false, false, false, false, false, NULL };
6772
6773 /* Execute the driver for IPA PTA.  */
6774 static unsigned int
6775 ipa_pta_execute (void)
6776 {
6777   struct cgraph_node *node;
6778   struct varpool_node *var;
6779   int from;
6780
6781   in_ipa_mode = 1;
6782
6783   init_alias_heapvars ();
6784   init_alias_vars ();
6785
6786   /* Build the constraints.  */
6787   for (node = cgraph_nodes; node; node = node->next)
6788     {
6789       struct cgraph_node *alias;
6790       varinfo_t vi;
6791
6792       /* Nodes without a body are not interesting.  Especially do not
6793          visit clones at this point for now - we get duplicate decls
6794          there for inline clones at least.  */
6795       if (!gimple_has_body_p (node->decl)
6796           || node->clone_of)
6797         continue;
6798
6799       vi = create_function_info_for (node->decl,
6800                                      alias_get_name (node->decl));
6801
6802       /* Associate the varinfo node with all aliases.  */
6803       for (alias = node->same_body; alias; alias = alias->next)
6804         insert_vi_for_tree (alias->decl, vi);
6805     }
6806
6807   /* Create constraints for global variables and their initializers.  */
6808   for (var = varpool_nodes; var; var = var->next)
6809     {
6810       struct varpool_node *alias;
6811       varinfo_t vi;
6812
6813       vi = get_vi_for_tree (var->decl);
6814
6815       /* Associate the varinfo node with all aliases.  */
6816       for (alias = var->extra_name; alias; alias = alias->next)
6817         insert_vi_for_tree (alias->decl, vi);
6818     }
6819
6820   if (dump_file)
6821     {
6822       fprintf (dump_file,
6823                "Generating constraints for global initializers\n\n");
6824       dump_constraints (dump_file, 0);
6825       fprintf (dump_file, "\n");
6826     }
6827   from = VEC_length (constraint_t, constraints);
6828
6829   for (node = cgraph_nodes; node; node = node->next)
6830     {
6831       struct function *func;
6832       basic_block bb;
6833       tree old_func_decl;
6834
6835       /* Nodes without a body are not interesting.  */
6836       if (!gimple_has_body_p (node->decl)
6837           || node->clone_of)
6838         continue;
6839
6840       if (dump_file)
6841         {
6842           fprintf (dump_file,
6843                    "Generating constraints for %s", cgraph_node_name (node));
6844           if (DECL_ASSEMBLER_NAME_SET_P (node->decl))
6845             fprintf (dump_file, " (%s)",
6846                      IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (node->decl)));
6847           fprintf (dump_file, "\n");
6848         }
6849
6850       func = DECL_STRUCT_FUNCTION (node->decl);
6851       old_func_decl = current_function_decl;
6852       push_cfun (func);
6853       current_function_decl = node->decl;
6854
6855       if (node->local.externally_visible)
6856         {
6857           /* For externally visible functions use local constraints for
6858              their arguments.  For local functions we see all callers
6859              and thus do not need initial constraints for parameters.  */
6860           intra_create_variable_infos ();
6861
6862           /* We also need to make function return values escape.  Nothing
6863              escapes by returning from main though.  */
6864           if (!MAIN_NAME_P (DECL_NAME (node->decl)))
6865             {
6866               varinfo_t fi, rvi;
6867               fi = lookup_vi_for_tree (node->decl);
6868               rvi = first_vi_for_offset (fi, fi_result);
6869               if (rvi && rvi->offset == fi_result)
6870                 {
6871                   struct constraint_expr includes;
6872                   struct constraint_expr var;
6873                   includes.var = escaped_id;
6874                   includes.offset = 0;
6875                   includes.type = SCALAR;
6876                   var.var = rvi->id;
6877                   var.offset = 0;
6878                   var.type = SCALAR;
6879                   process_constraint (new_constraint (includes, var));
6880                 }
6881             }
6882         }
6883
6884       /* Build constriants for the function body.  */
6885       FOR_EACH_BB_FN (bb, func)
6886         {
6887           gimple_stmt_iterator gsi;
6888
6889           for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
6890                gsi_next (&gsi))
6891             {
6892               gimple phi = gsi_stmt (gsi);
6893
6894               if (is_gimple_reg (gimple_phi_result (phi)))
6895                 find_func_aliases (phi);
6896             }
6897
6898           for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6899             {
6900               gimple stmt = gsi_stmt (gsi);
6901
6902               find_func_aliases (stmt);
6903               find_func_clobbers (stmt);
6904             }
6905         }
6906
6907       current_function_decl = old_func_decl;
6908       pop_cfun ();
6909
6910       if (dump_file)
6911         {
6912           fprintf (dump_file, "\n");
6913           dump_constraints (dump_file, from);
6914           fprintf (dump_file, "\n");
6915         }
6916       from = VEC_length (constraint_t, constraints);
6917     }
6918
6919   /* From the constraints compute the points-to sets.  */
6920   solve_constraints ();
6921
6922   /* Compute the global points-to sets for ESCAPED.
6923      ???  Note that the computed escape set is not correct
6924      for the whole unit as we fail to consider graph edges to
6925      externally visible functions.  */
6926   find_what_var_points_to (get_varinfo (escaped_id), &ipa_escaped_pt);
6927
6928   /* Make sure the ESCAPED solution (which is used as placeholder in
6929      other solutions) does not reference itself.  This simplifies
6930      points-to solution queries.  */
6931   ipa_escaped_pt.ipa_escaped = 0;
6932
6933   /* Assign the points-to sets to the SSA names in the unit.  */
6934   for (node = cgraph_nodes; node; node = node->next)
6935     {
6936       tree ptr;
6937       struct function *fn;
6938       unsigned i;
6939       varinfo_t fi;
6940       basic_block bb;
6941       struct pt_solution uses, clobbers;
6942       struct cgraph_edge *e;
6943
6944       /* Nodes without a body are not interesting.  */
6945       if (!gimple_has_body_p (node->decl)
6946           || node->clone_of)
6947         continue;
6948
6949       fn = DECL_STRUCT_FUNCTION (node->decl);
6950
6951       /* Compute the points-to sets for pointer SSA_NAMEs.  */
6952       FOR_EACH_VEC_ELT (tree, fn->gimple_df->ssa_names, i, ptr)
6953         {
6954           if (ptr
6955               && POINTER_TYPE_P (TREE_TYPE (ptr)))
6956             find_what_p_points_to (ptr);
6957         }
6958
6959       /* Compute the call-use and call-clobber sets for all direct calls.  */
6960       fi = lookup_vi_for_tree (node->decl);
6961       gcc_assert (fi->is_fn_info);
6962       find_what_var_points_to (first_vi_for_offset (fi, fi_clobbers),
6963                                &clobbers);
6964       find_what_var_points_to (first_vi_for_offset (fi, fi_uses), &uses);
6965       for (e = node->callers; e; e = e->next_caller)
6966         {
6967           if (!e->call_stmt)
6968             continue;
6969
6970           *gimple_call_clobber_set (e->call_stmt) = clobbers;
6971           *gimple_call_use_set (e->call_stmt) = uses;
6972         }
6973
6974       /* Compute the call-use and call-clobber sets for indirect calls
6975          and calls to external functions.  */
6976       FOR_EACH_BB_FN (bb, fn)
6977         {
6978           gimple_stmt_iterator gsi;
6979
6980           for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6981             {
6982               gimple stmt = gsi_stmt (gsi);
6983               struct pt_solution *pt;
6984               varinfo_t vi;
6985               tree decl;
6986
6987               if (!is_gimple_call (stmt))
6988                 continue;
6989
6990               /* Handle direct calls to external functions.  */
6991               decl = gimple_call_fndecl (stmt);
6992               if (decl
6993                   && (!(fi = lookup_vi_for_tree (decl))
6994                       || !fi->is_fn_info))
6995                 {
6996                   pt = gimple_call_use_set (stmt);
6997                   if (gimple_call_flags (stmt) & ECF_CONST)
6998                     memset (pt, 0, sizeof (struct pt_solution));
6999                   else if ((vi = lookup_call_use_vi (stmt)) != NULL)
7000                     {
7001                       find_what_var_points_to (vi, pt);
7002                       /* Escaped (and thus nonlocal) variables are always
7003                          implicitly used by calls.  */
7004                       /* ???  ESCAPED can be empty even though NONLOCAL
7005                          always escaped.  */
7006                       pt->nonlocal = 1;
7007                       pt->ipa_escaped = 1;
7008                     }
7009                   else
7010                     {
7011                       /* If there is nothing special about this call then
7012                          we have made everything that is used also escape.  */
7013                       *pt = ipa_escaped_pt;
7014                       pt->nonlocal = 1;
7015                     }
7016
7017                   pt = gimple_call_clobber_set (stmt);
7018                   if (gimple_call_flags (stmt) & (ECF_CONST|ECF_PURE|ECF_NOVOPS))
7019                     memset (pt, 0, sizeof (struct pt_solution));
7020                   else if ((vi = lookup_call_clobber_vi (stmt)) != NULL)
7021                     {
7022                       find_what_var_points_to (vi, pt);
7023                       /* Escaped (and thus nonlocal) variables are always
7024                          implicitly clobbered by calls.  */
7025                       /* ???  ESCAPED can be empty even though NONLOCAL
7026                          always escaped.  */
7027                       pt->nonlocal = 1;
7028                       pt->ipa_escaped = 1;
7029                     }
7030                   else
7031                     {
7032                       /* If there is nothing special about this call then
7033                          we have made everything that is used also escape.  */
7034                       *pt = ipa_escaped_pt;
7035                       pt->nonlocal = 1;
7036                     }
7037                 }
7038
7039               /* Handle indirect calls.  */
7040               if (!decl
7041                   && (fi = get_fi_for_callee (stmt)))
7042                 {
7043                   /* We need to accumulate all clobbers/uses of all possible
7044                      callees.  */
7045                   fi = get_varinfo (find (fi->id));
7046                   /* If we cannot constrain the set of functions we'll end up
7047                      calling we end up using/clobbering everything.  */
7048                   if (bitmap_bit_p (fi->solution, anything_id)
7049                       || bitmap_bit_p (fi->solution, nonlocal_id)
7050                       || bitmap_bit_p (fi->solution, escaped_id))
7051                     {
7052                       pt_solution_reset (gimple_call_clobber_set (stmt));
7053                       pt_solution_reset (gimple_call_use_set (stmt));
7054                     }
7055                   else
7056                     {
7057                       bitmap_iterator bi;
7058                       unsigned i;
7059                       struct pt_solution *uses, *clobbers;
7060
7061                       uses = gimple_call_use_set (stmt);
7062                       clobbers = gimple_call_clobber_set (stmt);
7063                       memset (uses, 0, sizeof (struct pt_solution));
7064                       memset (clobbers, 0, sizeof (struct pt_solution));
7065                       EXECUTE_IF_SET_IN_BITMAP (fi->solution, 0, i, bi)
7066                         {
7067                           struct pt_solution sol;
7068
7069                           vi = get_varinfo (i);
7070                           if (!vi->is_fn_info)
7071                             {
7072                               /* ???  We could be more precise here?  */
7073                               uses->nonlocal = 1;
7074                               uses->ipa_escaped = 1;
7075                               clobbers->nonlocal = 1;
7076                               clobbers->ipa_escaped = 1;
7077                               continue;
7078                             }
7079
7080                           if (!uses->anything)
7081                             {
7082                               find_what_var_points_to
7083                                   (first_vi_for_offset (vi, fi_uses), &sol);
7084                               pt_solution_ior_into (uses, &sol);
7085                             }
7086                           if (!clobbers->anything)
7087                             {
7088                               find_what_var_points_to
7089                                   (first_vi_for_offset (vi, fi_clobbers), &sol);
7090                               pt_solution_ior_into (clobbers, &sol);
7091                             }
7092                         }
7093                     }
7094                 }
7095             }
7096         }
7097
7098       fn->gimple_df->ipa_pta = true;
7099     }
7100
7101   delete_points_to_sets ();
7102
7103   in_ipa_mode = 0;
7104
7105   return 0;
7106 }
7107
7108 struct simple_ipa_opt_pass pass_ipa_pta =
7109 {
7110  {
7111   SIMPLE_IPA_PASS,
7112   "pta",                                /* name */
7113   gate_ipa_pta,                 /* gate */
7114   ipa_pta_execute,                      /* execute */
7115   NULL,                                 /* sub */
7116   NULL,                                 /* next */
7117   0,                                    /* static_pass_number */
7118   TV_IPA_PTA,                   /* tv_id */
7119   0,                                    /* properties_required */
7120   0,                                    /* properties_provided */
7121   0,                                    /* properties_destroyed */
7122   0,                                    /* todo_flags_start */
7123   TODO_update_ssa                       /* todo_flags_finish */
7124  }
7125 };
7126
7127
7128 #include "gt-tree-ssa-structalias.h"