OSDN Git Service

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