2010-04-19 Richard Guenther <rguenther@suse.de>
[official-gcc.git] / gcc / tree-ssa-structalias.c
blob1ea7afca39bae4e0d366f2d672bd2b46e1005da5
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>
6 This file is part of GCC.
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.
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.
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/>. */
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 "rtl.h"
31 #include "tm_p.h"
32 #include "hard-reg-set.h"
33 #include "basic-block.h"
34 #include "output.h"
35 #include "tree.h"
36 #include "tree-flow.h"
37 #include "tree-inline.h"
38 #include "varray.h"
39 #include "diagnostic.h"
40 #include "toplev.h"
41 #include "gimple.h"
42 #include "hashtab.h"
43 #include "function.h"
44 #include "cgraph.h"
45 #include "tree-pass.h"
46 #include "timevar.h"
47 #include "alloc-pool.h"
48 #include "splay-tree.h"
49 #include "params.h"
50 #include "cgraph.h"
51 #include "alias.h"
52 #include "pointer-set.h"
54 /* The idea behind this analyzer is to generate set constraints from the
55 program, then solve the resulting constraints in order to generate the
56 points-to sets.
58 Set constraints are a way of modeling program analysis problems that
59 involve sets. They consist of an inclusion constraint language,
60 describing the variables (each variable is a set) and operations that
61 are involved on the variables, and a set of rules that derive facts
62 from these operations. To solve a system of set constraints, you derive
63 all possible facts under the rules, which gives you the correct sets
64 as a consequence.
66 See "Efficient Field-sensitive pointer analysis for C" by "David
67 J. Pearce and Paul H. J. Kelly and Chris Hankin, at
68 http://citeseer.ist.psu.edu/pearce04efficient.html
70 Also see "Ultra-fast Aliasing Analysis using CLA: A Million Lines
71 of C Code in a Second" by ""Nevin Heintze and Olivier Tardieu" at
72 http://citeseer.ist.psu.edu/heintze01ultrafast.html
74 There are three types of real constraint expressions, DEREF,
75 ADDRESSOF, and SCALAR. Each constraint expression consists
76 of a constraint type, a variable, and an offset.
78 SCALAR is a constraint expression type used to represent x, whether
79 it appears on the LHS or the RHS of a statement.
80 DEREF is a constraint expression type used to represent *x, whether
81 it appears on the LHS or the RHS of a statement.
82 ADDRESSOF is a constraint expression used to represent &x, whether
83 it appears on the LHS or the RHS of a statement.
85 Each pointer variable in the program is assigned an integer id, and
86 each field of a structure variable is assigned an integer id as well.
88 Structure variables are linked to their list of fields through a "next
89 field" in each variable that points to the next field in offset
90 order.
91 Each variable for a structure field has
93 1. "size", that tells the size in bits of that field.
94 2. "fullsize, that tells the size in bits of the entire structure.
95 3. "offset", that tells the offset in bits from the beginning of the
96 structure to this field.
98 Thus,
99 struct f
101 int a;
102 int b;
103 } foo;
104 int *bar;
106 looks like
108 foo.a -> id 1, size 32, offset 0, fullsize 64, next foo.b
109 foo.b -> id 2, size 32, offset 32, fullsize 64, next NULL
110 bar -> id 3, size 32, offset 0, fullsize 32, next NULL
113 In order to solve the system of set constraints, the following is
114 done:
116 1. Each constraint variable x has a solution set associated with it,
117 Sol(x).
119 2. Constraints are separated into direct, copy, and complex.
120 Direct constraints are ADDRESSOF constraints that require no extra
121 processing, such as P = &Q
122 Copy constraints are those of the form P = Q.
123 Complex constraints are all the constraints involving dereferences
124 and offsets (including offsetted copies).
126 3. All direct constraints of the form P = &Q are processed, such
127 that Q is added to Sol(P)
129 4. All complex constraints for a given constraint variable are stored in a
130 linked list attached to that variable's node.
132 5. A directed graph is built out of the copy constraints. Each
133 constraint variable is a node in the graph, and an edge from
134 Q to P is added for each copy constraint of the form P = Q
136 6. The graph is then walked, and solution sets are
137 propagated along the copy edges, such that an edge from Q to P
138 causes Sol(P) <- Sol(P) union Sol(Q).
140 7. As we visit each node, all complex constraints associated with
141 that node are processed by adding appropriate copy edges to the graph, or the
142 appropriate variables to the solution set.
144 8. The process of walking the graph is iterated until no solution
145 sets change.
147 Prior to walking the graph in steps 6 and 7, We perform static
148 cycle elimination on the constraint graph, as well
149 as off-line variable substitution.
151 TODO: Adding offsets to pointer-to-structures can be handled (IE not punted
152 on and turned into anything), but isn't. You can just see what offset
153 inside the pointed-to struct it's going to access.
155 TODO: Constant bounded arrays can be handled as if they were structs of the
156 same number of elements.
158 TODO: Modeling heap and incoming pointers becomes much better if we
159 add fields to them as we discover them, which we could do.
161 TODO: We could handle unions, but to be honest, it's probably not
162 worth the pain or slowdown. */
164 static GTY ((if_marked ("tree_map_marked_p"), param_is (struct tree_map)))
165 htab_t heapvar_for_stmt;
167 static bool use_field_sensitive = true;
168 static int in_ipa_mode = 0;
170 /* Used for predecessor bitmaps. */
171 static bitmap_obstack predbitmap_obstack;
173 /* Used for points-to sets. */
174 static bitmap_obstack pta_obstack;
176 /* Used for oldsolution members of variables. */
177 static bitmap_obstack oldpta_obstack;
179 /* Used for per-solver-iteration bitmaps. */
180 static bitmap_obstack iteration_obstack;
182 static unsigned int create_variable_info_for (tree, const char *);
183 typedef struct constraint_graph *constraint_graph_t;
184 static void unify_nodes (constraint_graph_t, unsigned int, unsigned int, bool);
186 struct constraint;
187 typedef struct constraint *constraint_t;
189 DEF_VEC_P(constraint_t);
190 DEF_VEC_ALLOC_P(constraint_t,heap);
192 #define EXECUTE_IF_IN_NONNULL_BITMAP(a, b, c, d) \
193 if (a) \
194 EXECUTE_IF_SET_IN_BITMAP (a, b, c, d)
196 static struct constraint_stats
198 unsigned int total_vars;
199 unsigned int nonpointer_vars;
200 unsigned int unified_vars_static;
201 unsigned int unified_vars_dynamic;
202 unsigned int iterations;
203 unsigned int num_edges;
204 unsigned int num_implicit_edges;
205 unsigned int points_to_sets_created;
206 } stats;
208 struct variable_info
210 /* ID of this variable */
211 unsigned int id;
213 /* True if this is a variable created by the constraint analysis, such as
214 heap variables and constraints we had to break up. */
215 unsigned int is_artificial_var : 1;
217 /* True if this is a special variable whose solution set should not be
218 changed. */
219 unsigned int is_special_var : 1;
221 /* True for variables whose size is not known or variable. */
222 unsigned int is_unknown_size_var : 1;
224 /* True for (sub-)fields that represent a whole variable. */
225 unsigned int is_full_var : 1;
227 /* True if this is a heap variable. */
228 unsigned int is_heap_var : 1;
230 /* True if this is a variable tracking a restrict pointer source. */
231 unsigned int is_restrict_var : 1;
233 /* True if this field may contain pointers. */
234 unsigned int may_have_pointers : 1;
236 /* True if this represents a global variable. */
237 unsigned int is_global_var : 1;
239 /* A link to the variable for the next field in this structure. */
240 struct variable_info *next;
242 /* Offset of this variable, in bits, from the base variable */
243 unsigned HOST_WIDE_INT offset;
245 /* Size of the variable, in bits. */
246 unsigned HOST_WIDE_INT size;
248 /* Full size of the base variable, in bits. */
249 unsigned HOST_WIDE_INT fullsize;
251 /* Name of this variable */
252 const char *name;
254 /* Tree that this variable is associated with. */
255 tree decl;
257 /* Points-to set for this variable. */
258 bitmap solution;
260 /* Old points-to set for this variable. */
261 bitmap oldsolution;
263 typedef struct variable_info *varinfo_t;
265 static varinfo_t first_vi_for_offset (varinfo_t, unsigned HOST_WIDE_INT);
266 static varinfo_t first_or_preceding_vi_for_offset (varinfo_t,
267 unsigned HOST_WIDE_INT);
268 static varinfo_t lookup_vi_for_tree (tree);
270 /* Pool of variable info structures. */
271 static alloc_pool variable_info_pool;
273 DEF_VEC_P(varinfo_t);
275 DEF_VEC_ALLOC_P(varinfo_t, heap);
277 /* Table of variable info structures for constraint variables.
278 Indexed directly by variable info id. */
279 static VEC(varinfo_t,heap) *varmap;
281 /* Return the varmap element N */
283 static inline varinfo_t
284 get_varinfo (unsigned int n)
286 return VEC_index (varinfo_t, varmap, n);
289 /* Static IDs for the special variables. */
290 enum { nothing_id = 0, anything_id = 1, readonly_id = 2,
291 escaped_id = 3, nonlocal_id = 4, callused_id = 5,
292 storedanything_id = 6, integer_id = 7 };
294 struct GTY(()) heapvar_map {
295 struct tree_map map;
296 unsigned HOST_WIDE_INT offset;
299 static int
300 heapvar_map_eq (const void *p1, const void *p2)
302 const struct heapvar_map *h1 = (const struct heapvar_map *)p1;
303 const struct heapvar_map *h2 = (const struct heapvar_map *)p2;
304 return (h1->map.base.from == h2->map.base.from
305 && h1->offset == h2->offset);
308 static unsigned int
309 heapvar_map_hash (struct heapvar_map *h)
311 return iterative_hash_host_wide_int (h->offset,
312 htab_hash_pointer (h->map.base.from));
315 /* Lookup a heap var for FROM, and return it if we find one. */
317 static tree
318 heapvar_lookup (tree from, unsigned HOST_WIDE_INT offset)
320 struct heapvar_map *h, in;
321 in.map.base.from = from;
322 in.offset = offset;
323 h = (struct heapvar_map *) htab_find_with_hash (heapvar_for_stmt, &in,
324 heapvar_map_hash (&in));
325 if (h)
326 return h->map.to;
327 return NULL_TREE;
330 /* Insert a mapping FROM->TO in the heap var for statement
331 hashtable. */
333 static void
334 heapvar_insert (tree from, unsigned HOST_WIDE_INT offset, tree to)
336 struct heapvar_map *h;
337 void **loc;
339 h = GGC_NEW (struct heapvar_map);
340 h->map.base.from = from;
341 h->offset = offset;
342 h->map.hash = heapvar_map_hash (h);
343 h->map.to = to;
344 loc = htab_find_slot_with_hash (heapvar_for_stmt, h, h->map.hash, INSERT);
345 gcc_assert (*loc == NULL);
346 *(struct heapvar_map **) loc = h;
349 /* Return a new variable info structure consisting for a variable
350 named NAME, and using constraint graph node NODE. Append it
351 to the vector of variable info structures. */
353 static varinfo_t
354 new_var_info (tree t, const char *name)
356 unsigned index = VEC_length (varinfo_t, varmap);
357 varinfo_t ret = (varinfo_t) pool_alloc (variable_info_pool);
359 ret->id = index;
360 ret->name = name;
361 ret->decl = t;
362 /* Vars without decl are artificial and do not have sub-variables. */
363 ret->is_artificial_var = (t == NULL_TREE);
364 ret->is_special_var = false;
365 ret->is_unknown_size_var = false;
366 ret->is_full_var = (t == NULL_TREE);
367 ret->is_heap_var = false;
368 ret->is_restrict_var = false;
369 ret->may_have_pointers = true;
370 ret->is_global_var = (t == NULL_TREE);
371 if (t && DECL_P (t))
372 ret->is_global_var = is_global_var (t);
373 ret->solution = BITMAP_ALLOC (&pta_obstack);
374 ret->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
375 ret->next = NULL;
377 VEC_safe_push (varinfo_t, heap, varmap, ret);
379 return ret;
382 typedef enum {SCALAR, DEREF, ADDRESSOF} constraint_expr_type;
384 /* An expression that appears in a constraint. */
386 struct constraint_expr
388 /* Constraint type. */
389 constraint_expr_type type;
391 /* Variable we are referring to in the constraint. */
392 unsigned int var;
394 /* Offset, in bits, of this constraint from the beginning of
395 variables it ends up referring to.
397 IOW, in a deref constraint, we would deref, get the result set,
398 then add OFFSET to each member. */
399 HOST_WIDE_INT offset;
402 /* Use 0x8000... as special unknown offset. */
403 #define UNKNOWN_OFFSET ((HOST_WIDE_INT)-1 << (HOST_BITS_PER_WIDE_INT-1))
405 typedef struct constraint_expr ce_s;
406 DEF_VEC_O(ce_s);
407 DEF_VEC_ALLOC_O(ce_s, heap);
408 static void get_constraint_for_1 (tree, VEC(ce_s, heap) **, bool);
409 static void get_constraint_for (tree, VEC(ce_s, heap) **);
410 static void do_deref (VEC (ce_s, heap) **);
412 /* Our set constraints are made up of two constraint expressions, one
413 LHS, and one RHS.
415 As described in the introduction, our set constraints each represent an
416 operation between set valued variables.
418 struct constraint
420 struct constraint_expr lhs;
421 struct constraint_expr rhs;
424 /* List of constraints that we use to build the constraint graph from. */
426 static VEC(constraint_t,heap) *constraints;
427 static alloc_pool constraint_pool;
429 /* The constraint graph is represented as an array of bitmaps
430 containing successor nodes. */
432 struct constraint_graph
434 /* Size of this graph, which may be different than the number of
435 nodes in the variable map. */
436 unsigned int size;
438 /* Explicit successors of each node. */
439 bitmap *succs;
441 /* Implicit predecessors of each node (Used for variable
442 substitution). */
443 bitmap *implicit_preds;
445 /* Explicit predecessors of each node (Used for variable substitution). */
446 bitmap *preds;
448 /* Indirect cycle representatives, or -1 if the node has no indirect
449 cycles. */
450 int *indirect_cycles;
452 /* Representative node for a node. rep[a] == a unless the node has
453 been unified. */
454 unsigned int *rep;
456 /* Equivalence class representative for a label. This is used for
457 variable substitution. */
458 int *eq_rep;
460 /* Pointer equivalence label for a node. All nodes with the same
461 pointer equivalence label can be unified together at some point
462 (either during constraint optimization or after the constraint
463 graph is built). */
464 unsigned int *pe;
466 /* Pointer equivalence representative for a label. This is used to
467 handle nodes that are pointer equivalent but not location
468 equivalent. We can unite these once the addressof constraints
469 are transformed into initial points-to sets. */
470 int *pe_rep;
472 /* Pointer equivalence label for each node, used during variable
473 substitution. */
474 unsigned int *pointer_label;
476 /* Location equivalence label for each node, used during location
477 equivalence finding. */
478 unsigned int *loc_label;
480 /* Pointed-by set for each node, used during location equivalence
481 finding. This is pointed-by rather than pointed-to, because it
482 is constructed using the predecessor graph. */
483 bitmap *pointed_by;
485 /* Points to sets for pointer equivalence. This is *not* the actual
486 points-to sets for nodes. */
487 bitmap *points_to;
489 /* Bitmap of nodes where the bit is set if the node is a direct
490 node. Used for variable substitution. */
491 sbitmap direct_nodes;
493 /* Bitmap of nodes where the bit is set if the node is address
494 taken. Used for variable substitution. */
495 bitmap address_taken;
497 /* Vector of complex constraints for each graph node. Complex
498 constraints are those involving dereferences or offsets that are
499 not 0. */
500 VEC(constraint_t,heap) **complex;
503 static constraint_graph_t graph;
505 /* During variable substitution and the offline version of indirect
506 cycle finding, we create nodes to represent dereferences and
507 address taken constraints. These represent where these start and
508 end. */
509 #define FIRST_REF_NODE (VEC_length (varinfo_t, varmap))
510 #define LAST_REF_NODE (FIRST_REF_NODE + (FIRST_REF_NODE - 1))
512 /* Return the representative node for NODE, if NODE has been unioned
513 with another NODE.
514 This function performs path compression along the way to finding
515 the representative. */
517 static unsigned int
518 find (unsigned int node)
520 gcc_assert (node < graph->size);
521 if (graph->rep[node] != node)
522 return graph->rep[node] = find (graph->rep[node]);
523 return node;
526 /* Union the TO and FROM nodes to the TO nodes.
527 Note that at some point in the future, we may want to do
528 union-by-rank, in which case we are going to have to return the
529 node we unified to. */
531 static bool
532 unite (unsigned int to, unsigned int from)
534 gcc_assert (to < graph->size && from < graph->size);
535 if (to != from && graph->rep[from] != to)
537 graph->rep[from] = to;
538 return true;
540 return false;
543 /* Create a new constraint consisting of LHS and RHS expressions. */
545 static constraint_t
546 new_constraint (const struct constraint_expr lhs,
547 const struct constraint_expr rhs)
549 constraint_t ret = (constraint_t) pool_alloc (constraint_pool);
550 ret->lhs = lhs;
551 ret->rhs = rhs;
552 return ret;
555 /* Print out constraint C to FILE. */
557 static void
558 dump_constraint (FILE *file, constraint_t c)
560 if (c->lhs.type == ADDRESSOF)
561 fprintf (file, "&");
562 else if (c->lhs.type == DEREF)
563 fprintf (file, "*");
564 fprintf (file, "%s", get_varinfo (c->lhs.var)->name);
565 if (c->lhs.offset == UNKNOWN_OFFSET)
566 fprintf (file, " + UNKNOWN");
567 else if (c->lhs.offset != 0)
568 fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->lhs.offset);
569 fprintf (file, " = ");
570 if (c->rhs.type == ADDRESSOF)
571 fprintf (file, "&");
572 else if (c->rhs.type == DEREF)
573 fprintf (file, "*");
574 fprintf (file, "%s", get_varinfo (c->rhs.var)->name);
575 if (c->rhs.offset == UNKNOWN_OFFSET)
576 fprintf (file, " + UNKNOWN");
577 else if (c->rhs.offset != 0)
578 fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->rhs.offset);
579 fprintf (file, "\n");
583 void debug_constraint (constraint_t);
584 void debug_constraints (void);
585 void debug_constraint_graph (void);
586 void debug_solution_for_var (unsigned int);
587 void debug_sa_points_to_info (void);
589 /* Print out constraint C to stderr. */
591 void
592 debug_constraint (constraint_t c)
594 dump_constraint (stderr, c);
597 /* Print out all constraints to FILE */
599 static void
600 dump_constraints (FILE *file)
602 int i;
603 constraint_t c;
604 for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
605 dump_constraint (file, c);
608 /* Print out all constraints to stderr. */
610 void
611 debug_constraints (void)
613 dump_constraints (stderr);
616 /* Print out to FILE the edge in the constraint graph that is created by
617 constraint c. The edge may have a label, depending on the type of
618 constraint that it represents. If complex1, e.g: a = *b, then the label
619 is "=*", if complex2, e.g: *a = b, then the label is "*=", if
620 complex with an offset, e.g: a = b + 8, then the label is "+".
621 Otherwise the edge has no label. */
623 static void
624 dump_constraint_edge (FILE *file, constraint_t c)
626 if (c->rhs.type != ADDRESSOF)
628 const char *src = get_varinfo (c->rhs.var)->name;
629 const char *dst = get_varinfo (c->lhs.var)->name;
630 fprintf (file, " \"%s\" -> \"%s\" ", src, dst);
631 /* Due to preprocessing of constraints, instructions like *a = *b are
632 illegal; thus, we do not have to handle such cases. */
633 if (c->lhs.type == DEREF)
634 fprintf (file, " [ label=\"*=\" ] ;\n");
635 else if (c->rhs.type == DEREF)
636 fprintf (file, " [ label=\"=*\" ] ;\n");
637 else
639 /* We must check the case where the constraint is an offset.
640 In this case, it is treated as a complex constraint. */
641 if (c->rhs.offset != c->lhs.offset)
642 fprintf (file, " [ label=\"+\" ] ;\n");
643 else
644 fprintf (file, " ;\n");
649 /* Print the constraint graph in dot format. */
651 static void
652 dump_constraint_graph (FILE *file)
654 unsigned int i=0, size;
655 constraint_t c;
657 /* Only print the graph if it has already been initialized: */
658 if (!graph)
659 return;
661 /* Print the constraints used to produce the constraint graph. The
662 constraints will be printed as comments in the dot file: */
663 fprintf (file, "\n\n/* Constraints used in the constraint graph:\n");
664 dump_constraints (file);
665 fprintf (file, "*/\n");
667 /* Prints the header of the dot file: */
668 fprintf (file, "\n\n// The constraint graph in dot format:\n");
669 fprintf (file, "strict digraph {\n");
670 fprintf (file, " node [\n shape = box\n ]\n");
671 fprintf (file, " edge [\n fontsize = \"12\"\n ]\n");
672 fprintf (file, "\n // List of nodes in the constraint graph:\n");
674 /* The next lines print the nodes in the graph. In order to get the
675 number of nodes in the graph, we must choose the minimum between the
676 vector VEC (varinfo_t, varmap) and graph->size. If the graph has not
677 yet been initialized, then graph->size == 0, otherwise we must only
678 read nodes that have an entry in VEC (varinfo_t, varmap). */
679 size = VEC_length (varinfo_t, varmap);
680 size = size < graph->size ? size : graph->size;
681 for (i = 0; i < size; i++)
683 const char *name = get_varinfo (graph->rep[i])->name;
684 fprintf (file, " \"%s\" ;\n", name);
687 /* Go over the list of constraints printing the edges in the constraint
688 graph. */
689 fprintf (file, "\n // The constraint edges:\n");
690 for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
691 if (c)
692 dump_constraint_edge (file, c);
694 /* Prints the tail of the dot file. By now, only the closing bracket. */
695 fprintf (file, "}\n\n\n");
698 /* Print out the constraint graph to stderr. */
700 void
701 debug_constraint_graph (void)
703 dump_constraint_graph (stderr);
706 /* SOLVER FUNCTIONS
708 The solver is a simple worklist solver, that works on the following
709 algorithm:
711 sbitmap changed_nodes = all zeroes;
712 changed_count = 0;
713 For each node that is not already collapsed:
714 changed_count++;
715 set bit in changed nodes
717 while (changed_count > 0)
719 compute topological ordering for constraint graph
721 find and collapse cycles in the constraint graph (updating
722 changed if necessary)
724 for each node (n) in the graph in topological order:
725 changed_count--;
727 Process each complex constraint associated with the node,
728 updating changed if necessary.
730 For each outgoing edge from n, propagate the solution from n to
731 the destination of the edge, updating changed as necessary.
733 } */
735 /* Return true if two constraint expressions A and B are equal. */
737 static bool
738 constraint_expr_equal (struct constraint_expr a, struct constraint_expr b)
740 return a.type == b.type && a.var == b.var && a.offset == b.offset;
743 /* Return true if constraint expression A is less than constraint expression
744 B. This is just arbitrary, but consistent, in order to give them an
745 ordering. */
747 static bool
748 constraint_expr_less (struct constraint_expr a, struct constraint_expr b)
750 if (a.type == b.type)
752 if (a.var == b.var)
753 return a.offset < b.offset;
754 else
755 return a.var < b.var;
757 else
758 return a.type < b.type;
761 /* Return true if constraint A is less than constraint B. This is just
762 arbitrary, but consistent, in order to give them an ordering. */
764 static bool
765 constraint_less (const constraint_t a, const constraint_t b)
767 if (constraint_expr_less (a->lhs, b->lhs))
768 return true;
769 else if (constraint_expr_less (b->lhs, a->lhs))
770 return false;
771 else
772 return constraint_expr_less (a->rhs, b->rhs);
775 /* Return true if two constraints A and B are equal. */
777 static bool
778 constraint_equal (struct constraint a, struct constraint b)
780 return constraint_expr_equal (a.lhs, b.lhs)
781 && constraint_expr_equal (a.rhs, b.rhs);
785 /* Find a constraint LOOKFOR in the sorted constraint vector VEC */
787 static constraint_t
788 constraint_vec_find (VEC(constraint_t,heap) *vec,
789 struct constraint lookfor)
791 unsigned int place;
792 constraint_t found;
794 if (vec == NULL)
795 return NULL;
797 place = VEC_lower_bound (constraint_t, vec, &lookfor, constraint_less);
798 if (place >= VEC_length (constraint_t, vec))
799 return NULL;
800 found = VEC_index (constraint_t, vec, place);
801 if (!constraint_equal (*found, lookfor))
802 return NULL;
803 return found;
806 /* Union two constraint vectors, TO and FROM. Put the result in TO. */
808 static void
809 constraint_set_union (VEC(constraint_t,heap) **to,
810 VEC(constraint_t,heap) **from)
812 int i;
813 constraint_t c;
815 for (i = 0; VEC_iterate (constraint_t, *from, i, c); i++)
817 if (constraint_vec_find (*to, *c) == NULL)
819 unsigned int place = VEC_lower_bound (constraint_t, *to, c,
820 constraint_less);
821 VEC_safe_insert (constraint_t, heap, *to, place, c);
826 /* Expands the solution in SET to all sub-fields of variables included.
827 Union the expanded result into RESULT. */
829 static void
830 solution_set_expand (bitmap result, bitmap set)
832 bitmap_iterator bi;
833 bitmap vars = NULL;
834 unsigned j;
836 /* In a first pass record all variables we need to add all
837 sub-fields off. This avoids quadratic behavior. */
838 EXECUTE_IF_SET_IN_BITMAP (set, 0, j, bi)
840 varinfo_t v = get_varinfo (j);
841 if (v->is_artificial_var
842 || v->is_full_var)
843 continue;
844 v = lookup_vi_for_tree (v->decl);
845 if (vars == NULL)
846 vars = BITMAP_ALLOC (NULL);
847 bitmap_set_bit (vars, v->id);
850 /* In the second pass now do the addition to the solution and
851 to speed up solving add it to the delta as well. */
852 if (vars != NULL)
854 EXECUTE_IF_SET_IN_BITMAP (vars, 0, j, bi)
856 varinfo_t v = get_varinfo (j);
857 for (; v != NULL; v = v->next)
858 bitmap_set_bit (result, v->id);
860 BITMAP_FREE (vars);
864 /* Take a solution set SET, add OFFSET to each member of the set, and
865 overwrite SET with the result when done. */
867 static void
868 solution_set_add (bitmap set, HOST_WIDE_INT offset)
870 bitmap result = BITMAP_ALLOC (&iteration_obstack);
871 unsigned int i;
872 bitmap_iterator bi;
874 /* If the offset is unknown we have to expand the solution to
875 all subfields. */
876 if (offset == UNKNOWN_OFFSET)
878 solution_set_expand (set, set);
879 return;
882 EXECUTE_IF_SET_IN_BITMAP (set, 0, i, bi)
884 varinfo_t vi = get_varinfo (i);
886 /* If this is a variable with just one field just set its bit
887 in the result. */
888 if (vi->is_artificial_var
889 || vi->is_unknown_size_var
890 || vi->is_full_var)
891 bitmap_set_bit (result, i);
892 else
894 unsigned HOST_WIDE_INT fieldoffset = vi->offset + offset;
896 /* If the offset makes the pointer point to before the
897 variable use offset zero for the field lookup. */
898 if (offset < 0
899 && fieldoffset > vi->offset)
900 fieldoffset = 0;
902 if (offset != 0)
903 vi = first_or_preceding_vi_for_offset (vi, fieldoffset);
905 bitmap_set_bit (result, vi->id);
906 /* If the result is not exactly at fieldoffset include the next
907 field as well. See get_constraint_for_ptr_offset for more
908 rationale. */
909 if (vi->offset != fieldoffset
910 && vi->next != NULL)
911 bitmap_set_bit (result, vi->next->id);
915 bitmap_copy (set, result);
916 BITMAP_FREE (result);
919 /* Union solution sets TO and FROM, and add INC to each member of FROM in the
920 process. */
922 static bool
923 set_union_with_increment (bitmap to, bitmap from, HOST_WIDE_INT inc)
925 if (inc == 0)
926 return bitmap_ior_into (to, from);
927 else
929 bitmap tmp;
930 bool res;
932 tmp = BITMAP_ALLOC (&iteration_obstack);
933 bitmap_copy (tmp, from);
934 solution_set_add (tmp, inc);
935 res = bitmap_ior_into (to, tmp);
936 BITMAP_FREE (tmp);
937 return res;
941 /* Insert constraint C into the list of complex constraints for graph
942 node VAR. */
944 static void
945 insert_into_complex (constraint_graph_t graph,
946 unsigned int var, constraint_t c)
948 VEC (constraint_t, heap) *complex = graph->complex[var];
949 unsigned int place = VEC_lower_bound (constraint_t, complex, c,
950 constraint_less);
952 /* Only insert constraints that do not already exist. */
953 if (place >= VEC_length (constraint_t, complex)
954 || !constraint_equal (*c, *VEC_index (constraint_t, complex, place)))
955 VEC_safe_insert (constraint_t, heap, graph->complex[var], place, c);
959 /* Condense two variable nodes into a single variable node, by moving
960 all associated info from SRC to TO. */
962 static void
963 merge_node_constraints (constraint_graph_t graph, unsigned int to,
964 unsigned int from)
966 unsigned int i;
967 constraint_t c;
969 gcc_assert (find (from) == to);
971 /* Move all complex constraints from src node into to node */
972 for (i = 0; VEC_iterate (constraint_t, graph->complex[from], i, c); i++)
974 /* In complex constraints for node src, we may have either
975 a = *src, and *src = a, or an offseted constraint which are
976 always added to the rhs node's constraints. */
978 if (c->rhs.type == DEREF)
979 c->rhs.var = to;
980 else if (c->lhs.type == DEREF)
981 c->lhs.var = to;
982 else
983 c->rhs.var = to;
985 constraint_set_union (&graph->complex[to], &graph->complex[from]);
986 VEC_free (constraint_t, heap, graph->complex[from]);
987 graph->complex[from] = NULL;
991 /* Remove edges involving NODE from GRAPH. */
993 static void
994 clear_edges_for_node (constraint_graph_t graph, unsigned int node)
996 if (graph->succs[node])
997 BITMAP_FREE (graph->succs[node]);
1000 /* Merge GRAPH nodes FROM and TO into node TO. */
1002 static void
1003 merge_graph_nodes (constraint_graph_t graph, unsigned int to,
1004 unsigned int from)
1006 if (graph->indirect_cycles[from] != -1)
1008 /* If we have indirect cycles with the from node, and we have
1009 none on the to node, the to node has indirect cycles from the
1010 from node now that they are unified.
1011 If indirect cycles exist on both, unify the nodes that they
1012 are in a cycle with, since we know they are in a cycle with
1013 each other. */
1014 if (graph->indirect_cycles[to] == -1)
1015 graph->indirect_cycles[to] = graph->indirect_cycles[from];
1018 /* Merge all the successor edges. */
1019 if (graph->succs[from])
1021 if (!graph->succs[to])
1022 graph->succs[to] = BITMAP_ALLOC (&pta_obstack);
1023 bitmap_ior_into (graph->succs[to],
1024 graph->succs[from]);
1027 clear_edges_for_node (graph, from);
1031 /* Add an indirect graph edge to GRAPH, going from TO to FROM if
1032 it doesn't exist in the graph already. */
1034 static void
1035 add_implicit_graph_edge (constraint_graph_t graph, unsigned int to,
1036 unsigned int from)
1038 if (to == from)
1039 return;
1041 if (!graph->implicit_preds[to])
1042 graph->implicit_preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1044 if (bitmap_set_bit (graph->implicit_preds[to], from))
1045 stats.num_implicit_edges++;
1048 /* Add a predecessor graph edge to GRAPH, going from TO to FROM if
1049 it doesn't exist in the graph already.
1050 Return false if the edge already existed, true otherwise. */
1052 static void
1053 add_pred_graph_edge (constraint_graph_t graph, unsigned int to,
1054 unsigned int from)
1056 if (!graph->preds[to])
1057 graph->preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1058 bitmap_set_bit (graph->preds[to], from);
1061 /* Add a graph edge to GRAPH, going from FROM to TO if
1062 it doesn't exist in the graph already.
1063 Return false if the edge already existed, true otherwise. */
1065 static bool
1066 add_graph_edge (constraint_graph_t graph, unsigned int to,
1067 unsigned int from)
1069 if (to == from)
1071 return false;
1073 else
1075 bool r = false;
1077 if (!graph->succs[from])
1078 graph->succs[from] = BITMAP_ALLOC (&pta_obstack);
1079 if (bitmap_set_bit (graph->succs[from], to))
1081 r = true;
1082 if (to < FIRST_REF_NODE && from < FIRST_REF_NODE)
1083 stats.num_edges++;
1085 return r;
1090 /* Return true if {DEST.SRC} is an existing graph edge in GRAPH. */
1092 static bool
1093 valid_graph_edge (constraint_graph_t graph, unsigned int src,
1094 unsigned int dest)
1096 return (graph->succs[dest]
1097 && bitmap_bit_p (graph->succs[dest], src));
1100 /* Initialize the constraint graph structure to contain SIZE nodes. */
1102 static void
1103 init_graph (unsigned int size)
1105 unsigned int j;
1107 graph = XCNEW (struct constraint_graph);
1108 graph->size = size;
1109 graph->succs = XCNEWVEC (bitmap, graph->size);
1110 graph->indirect_cycles = XNEWVEC (int, graph->size);
1111 graph->rep = XNEWVEC (unsigned int, graph->size);
1112 graph->complex = XCNEWVEC (VEC(constraint_t, heap) *, size);
1113 graph->pe = XCNEWVEC (unsigned int, graph->size);
1114 graph->pe_rep = XNEWVEC (int, graph->size);
1116 for (j = 0; j < graph->size; j++)
1118 graph->rep[j] = j;
1119 graph->pe_rep[j] = -1;
1120 graph->indirect_cycles[j] = -1;
1124 /* Build the constraint graph, adding only predecessor edges right now. */
1126 static void
1127 build_pred_graph (void)
1129 int i;
1130 constraint_t c;
1131 unsigned int j;
1133 graph->implicit_preds = XCNEWVEC (bitmap, graph->size);
1134 graph->preds = XCNEWVEC (bitmap, graph->size);
1135 graph->pointer_label = XCNEWVEC (unsigned int, graph->size);
1136 graph->loc_label = XCNEWVEC (unsigned int, graph->size);
1137 graph->pointed_by = XCNEWVEC (bitmap, graph->size);
1138 graph->points_to = XCNEWVEC (bitmap, graph->size);
1139 graph->eq_rep = XNEWVEC (int, graph->size);
1140 graph->direct_nodes = sbitmap_alloc (graph->size);
1141 graph->address_taken = BITMAP_ALLOC (&predbitmap_obstack);
1142 sbitmap_zero (graph->direct_nodes);
1144 for (j = 0; j < FIRST_REF_NODE; j++)
1146 if (!get_varinfo (j)->is_special_var)
1147 SET_BIT (graph->direct_nodes, j);
1150 for (j = 0; j < graph->size; j++)
1151 graph->eq_rep[j] = -1;
1153 for (j = 0; j < VEC_length (varinfo_t, varmap); j++)
1154 graph->indirect_cycles[j] = -1;
1156 for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
1158 struct constraint_expr lhs = c->lhs;
1159 struct constraint_expr rhs = c->rhs;
1160 unsigned int lhsvar = lhs.var;
1161 unsigned int rhsvar = rhs.var;
1163 if (lhs.type == DEREF)
1165 /* *x = y. */
1166 if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1167 add_pred_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1169 else if (rhs.type == DEREF)
1171 /* x = *y */
1172 if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1173 add_pred_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1174 else
1175 RESET_BIT (graph->direct_nodes, lhsvar);
1177 else if (rhs.type == ADDRESSOF)
1179 varinfo_t v;
1181 /* x = &y */
1182 if (graph->points_to[lhsvar] == NULL)
1183 graph->points_to[lhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1184 bitmap_set_bit (graph->points_to[lhsvar], rhsvar);
1186 if (graph->pointed_by[rhsvar] == NULL)
1187 graph->pointed_by[rhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1188 bitmap_set_bit (graph->pointed_by[rhsvar], lhsvar);
1190 /* Implicitly, *x = y */
1191 add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1193 /* All related variables are no longer direct nodes. */
1194 RESET_BIT (graph->direct_nodes, rhsvar);
1195 v = get_varinfo (rhsvar);
1196 if (!v->is_full_var)
1198 v = lookup_vi_for_tree (v->decl);
1201 RESET_BIT (graph->direct_nodes, v->id);
1202 v = v->next;
1204 while (v != NULL);
1206 bitmap_set_bit (graph->address_taken, rhsvar);
1208 else if (lhsvar > anything_id
1209 && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1211 /* x = y */
1212 add_pred_graph_edge (graph, lhsvar, rhsvar);
1213 /* Implicitly, *x = *y */
1214 add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar,
1215 FIRST_REF_NODE + rhsvar);
1217 else if (lhs.offset != 0 || rhs.offset != 0)
1219 if (rhs.offset != 0)
1220 RESET_BIT (graph->direct_nodes, lhs.var);
1221 else if (lhs.offset != 0)
1222 RESET_BIT (graph->direct_nodes, rhs.var);
1227 /* Build the constraint graph, adding successor edges. */
1229 static void
1230 build_succ_graph (void)
1232 unsigned i, t;
1233 constraint_t c;
1235 for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
1237 struct constraint_expr lhs;
1238 struct constraint_expr rhs;
1239 unsigned int lhsvar;
1240 unsigned int rhsvar;
1242 if (!c)
1243 continue;
1245 lhs = c->lhs;
1246 rhs = c->rhs;
1247 lhsvar = find (lhs.var);
1248 rhsvar = find (rhs.var);
1250 if (lhs.type == DEREF)
1252 if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1253 add_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1255 else if (rhs.type == DEREF)
1257 if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1258 add_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1260 else if (rhs.type == ADDRESSOF)
1262 /* x = &y */
1263 gcc_assert (find (rhs.var) == rhs.var);
1264 bitmap_set_bit (get_varinfo (lhsvar)->solution, rhsvar);
1266 else if (lhsvar > anything_id
1267 && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1269 add_graph_edge (graph, lhsvar, rhsvar);
1273 /* Add edges from STOREDANYTHING to all non-direct nodes that can
1274 receive pointers. */
1275 t = find (storedanything_id);
1276 for (i = integer_id + 1; i < FIRST_REF_NODE; ++i)
1278 if (!TEST_BIT (graph->direct_nodes, i)
1279 && get_varinfo (i)->may_have_pointers)
1280 add_graph_edge (graph, find (i), t);
1283 /* Everything stored to ANYTHING also potentially escapes. */
1284 add_graph_edge (graph, find (escaped_id), t);
1288 /* Changed variables on the last iteration. */
1289 static unsigned int changed_count;
1290 static sbitmap changed;
1292 /* Strongly Connected Component visitation info. */
1294 struct scc_info
1296 sbitmap visited;
1297 sbitmap deleted;
1298 unsigned int *dfs;
1299 unsigned int *node_mapping;
1300 int current_index;
1301 VEC(unsigned,heap) *scc_stack;
1305 /* Recursive routine to find strongly connected components in GRAPH.
1306 SI is the SCC info to store the information in, and N is the id of current
1307 graph node we are processing.
1309 This is Tarjan's strongly connected component finding algorithm, as
1310 modified by Nuutila to keep only non-root nodes on the stack.
1311 The algorithm can be found in "On finding the strongly connected
1312 connected components in a directed graph" by Esko Nuutila and Eljas
1313 Soisalon-Soininen, in Information Processing Letters volume 49,
1314 number 1, pages 9-14. */
1316 static void
1317 scc_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1319 unsigned int i;
1320 bitmap_iterator bi;
1321 unsigned int my_dfs;
1323 SET_BIT (si->visited, n);
1324 si->dfs[n] = si->current_index ++;
1325 my_dfs = si->dfs[n];
1327 /* Visit all the successors. */
1328 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[n], 0, i, bi)
1330 unsigned int w;
1332 if (i > LAST_REF_NODE)
1333 break;
1335 w = find (i);
1336 if (TEST_BIT (si->deleted, w))
1337 continue;
1339 if (!TEST_BIT (si->visited, w))
1340 scc_visit (graph, si, w);
1342 unsigned int t = find (w);
1343 unsigned int nnode = find (n);
1344 gcc_assert (nnode == n);
1346 if (si->dfs[t] < si->dfs[nnode])
1347 si->dfs[n] = si->dfs[t];
1351 /* See if any components have been identified. */
1352 if (si->dfs[n] == my_dfs)
1354 if (VEC_length (unsigned, si->scc_stack) > 0
1355 && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
1357 bitmap scc = BITMAP_ALLOC (NULL);
1358 unsigned int lowest_node;
1359 bitmap_iterator bi;
1361 bitmap_set_bit (scc, n);
1363 while (VEC_length (unsigned, si->scc_stack) != 0
1364 && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
1366 unsigned int w = VEC_pop (unsigned, si->scc_stack);
1368 bitmap_set_bit (scc, w);
1371 lowest_node = bitmap_first_set_bit (scc);
1372 gcc_assert (lowest_node < FIRST_REF_NODE);
1374 /* Collapse the SCC nodes into a single node, and mark the
1375 indirect cycles. */
1376 EXECUTE_IF_SET_IN_BITMAP (scc, 0, i, bi)
1378 if (i < FIRST_REF_NODE)
1380 if (unite (lowest_node, i))
1381 unify_nodes (graph, lowest_node, i, false);
1383 else
1385 unite (lowest_node, i);
1386 graph->indirect_cycles[i - FIRST_REF_NODE] = lowest_node;
1390 SET_BIT (si->deleted, n);
1392 else
1393 VEC_safe_push (unsigned, heap, si->scc_stack, n);
1396 /* Unify node FROM into node TO, updating the changed count if
1397 necessary when UPDATE_CHANGED is true. */
1399 static void
1400 unify_nodes (constraint_graph_t graph, unsigned int to, unsigned int from,
1401 bool update_changed)
1404 gcc_assert (to != from && find (to) == to);
1405 if (dump_file && (dump_flags & TDF_DETAILS))
1406 fprintf (dump_file, "Unifying %s to %s\n",
1407 get_varinfo (from)->name,
1408 get_varinfo (to)->name);
1410 if (update_changed)
1411 stats.unified_vars_dynamic++;
1412 else
1413 stats.unified_vars_static++;
1415 merge_graph_nodes (graph, to, from);
1416 merge_node_constraints (graph, to, from);
1418 /* Mark TO as changed if FROM was changed. If TO was already marked
1419 as changed, decrease the changed count. */
1421 if (update_changed && TEST_BIT (changed, from))
1423 RESET_BIT (changed, from);
1424 if (!TEST_BIT (changed, to))
1425 SET_BIT (changed, to);
1426 else
1428 gcc_assert (changed_count > 0);
1429 changed_count--;
1432 if (get_varinfo (from)->solution)
1434 /* If the solution changes because of the merging, we need to mark
1435 the variable as changed. */
1436 if (bitmap_ior_into (get_varinfo (to)->solution,
1437 get_varinfo (from)->solution))
1439 if (update_changed && !TEST_BIT (changed, to))
1441 SET_BIT (changed, to);
1442 changed_count++;
1446 BITMAP_FREE (get_varinfo (from)->solution);
1447 BITMAP_FREE (get_varinfo (from)->oldsolution);
1449 if (stats.iterations > 0)
1451 BITMAP_FREE (get_varinfo (to)->oldsolution);
1452 get_varinfo (to)->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
1455 if (valid_graph_edge (graph, to, to))
1457 if (graph->succs[to])
1458 bitmap_clear_bit (graph->succs[to], to);
1462 /* Information needed to compute the topological ordering of a graph. */
1464 struct topo_info
1466 /* sbitmap of visited nodes. */
1467 sbitmap visited;
1468 /* Array that stores the topological order of the graph, *in
1469 reverse*. */
1470 VEC(unsigned,heap) *topo_order;
1474 /* Initialize and return a topological info structure. */
1476 static struct topo_info *
1477 init_topo_info (void)
1479 size_t size = graph->size;
1480 struct topo_info *ti = XNEW (struct topo_info);
1481 ti->visited = sbitmap_alloc (size);
1482 sbitmap_zero (ti->visited);
1483 ti->topo_order = VEC_alloc (unsigned, heap, 1);
1484 return ti;
1488 /* Free the topological sort info pointed to by TI. */
1490 static void
1491 free_topo_info (struct topo_info *ti)
1493 sbitmap_free (ti->visited);
1494 VEC_free (unsigned, heap, ti->topo_order);
1495 free (ti);
1498 /* Visit the graph in topological order, and store the order in the
1499 topo_info structure. */
1501 static void
1502 topo_visit (constraint_graph_t graph, struct topo_info *ti,
1503 unsigned int n)
1505 bitmap_iterator bi;
1506 unsigned int j;
1508 SET_BIT (ti->visited, n);
1510 if (graph->succs[n])
1511 EXECUTE_IF_SET_IN_BITMAP (graph->succs[n], 0, j, bi)
1513 if (!TEST_BIT (ti->visited, j))
1514 topo_visit (graph, ti, j);
1517 VEC_safe_push (unsigned, heap, ti->topo_order, n);
1520 /* Process a constraint C that represents x = *(y + off), using DELTA as the
1521 starting solution for y. */
1523 static void
1524 do_sd_constraint (constraint_graph_t graph, constraint_t c,
1525 bitmap delta)
1527 unsigned int lhs = c->lhs.var;
1528 bool flag = false;
1529 bitmap sol = get_varinfo (lhs)->solution;
1530 unsigned int j;
1531 bitmap_iterator bi;
1532 HOST_WIDE_INT roffset = c->rhs.offset;
1534 /* Our IL does not allow this. */
1535 gcc_assert (c->lhs.offset == 0);
1537 /* If the solution of Y contains anything it is good enough to transfer
1538 this to the LHS. */
1539 if (bitmap_bit_p (delta, anything_id))
1541 flag |= bitmap_set_bit (sol, anything_id);
1542 goto done;
1545 /* If we do not know at with offset the rhs is dereferenced compute
1546 the reachability set of DELTA, conservatively assuming it is
1547 dereferenced at all valid offsets. */
1548 if (roffset == UNKNOWN_OFFSET)
1550 solution_set_expand (delta, delta);
1551 /* No further offset processing is necessary. */
1552 roffset = 0;
1555 /* For each variable j in delta (Sol(y)), add
1556 an edge in the graph from j to x, and union Sol(j) into Sol(x). */
1557 EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1559 varinfo_t v = get_varinfo (j);
1560 HOST_WIDE_INT fieldoffset = v->offset + roffset;
1561 unsigned int t;
1563 if (v->is_full_var)
1564 fieldoffset = v->offset;
1565 else if (roffset != 0)
1566 v = first_vi_for_offset (v, fieldoffset);
1567 /* If the access is outside of the variable we can ignore it. */
1568 if (!v)
1569 continue;
1573 t = find (v->id);
1575 /* Adding edges from the special vars is pointless.
1576 They don't have sets that can change. */
1577 if (get_varinfo (t)->is_special_var)
1578 flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1579 /* Merging the solution from ESCAPED needlessly increases
1580 the set. Use ESCAPED as representative instead. */
1581 else if (v->id == escaped_id)
1582 flag |= bitmap_set_bit (sol, escaped_id);
1583 else if (add_graph_edge (graph, lhs, t))
1584 flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1586 /* If the variable is not exactly at the requested offset
1587 we have to include the next one. */
1588 if (v->offset == (unsigned HOST_WIDE_INT)fieldoffset
1589 || v->next == NULL)
1590 break;
1592 v = v->next;
1593 fieldoffset = v->offset;
1595 while (1);
1598 done:
1599 /* If the LHS solution changed, mark the var as changed. */
1600 if (flag)
1602 get_varinfo (lhs)->solution = sol;
1603 if (!TEST_BIT (changed, lhs))
1605 SET_BIT (changed, lhs);
1606 changed_count++;
1611 /* Process a constraint C that represents *(x + off) = y using DELTA
1612 as the starting solution for x. */
1614 static void
1615 do_ds_constraint (constraint_t c, bitmap delta)
1617 unsigned int rhs = c->rhs.var;
1618 bitmap sol = get_varinfo (rhs)->solution;
1619 unsigned int j;
1620 bitmap_iterator bi;
1621 HOST_WIDE_INT loff = c->lhs.offset;
1623 /* Our IL does not allow this. */
1624 gcc_assert (c->rhs.offset == 0);
1626 /* If the solution of y contains ANYTHING simply use the ANYTHING
1627 solution. This avoids needlessly increasing the points-to sets. */
1628 if (bitmap_bit_p (sol, anything_id))
1629 sol = get_varinfo (find (anything_id))->solution;
1631 /* If the solution for x contains ANYTHING we have to merge the
1632 solution of y into all pointer variables which we do via
1633 STOREDANYTHING. */
1634 if (bitmap_bit_p (delta, anything_id))
1636 unsigned t = find (storedanything_id);
1637 if (add_graph_edge (graph, t, rhs))
1639 if (bitmap_ior_into (get_varinfo (t)->solution, sol))
1641 if (!TEST_BIT (changed, t))
1643 SET_BIT (changed, t);
1644 changed_count++;
1648 return;
1651 /* If we do not know at with offset the rhs is dereferenced compute
1652 the reachability set of DELTA, conservatively assuming it is
1653 dereferenced at all valid offsets. */
1654 if (loff == UNKNOWN_OFFSET)
1656 solution_set_expand (delta, delta);
1657 loff = 0;
1660 /* For each member j of delta (Sol(x)), add an edge from y to j and
1661 union Sol(y) into Sol(j) */
1662 EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1664 varinfo_t v = get_varinfo (j);
1665 unsigned int t;
1666 HOST_WIDE_INT fieldoffset = v->offset + loff;
1668 /* If v is a global variable then this is an escape point. */
1669 if (v->is_global_var)
1671 t = find (escaped_id);
1672 if (add_graph_edge (graph, t, rhs)
1673 && bitmap_ior_into (get_varinfo (t)->solution, sol)
1674 && !TEST_BIT (changed, t))
1676 SET_BIT (changed, t);
1677 changed_count++;
1681 if (v->is_special_var)
1682 continue;
1684 if (v->is_full_var)
1685 fieldoffset = v->offset;
1686 else if (loff != 0)
1687 v = first_vi_for_offset (v, fieldoffset);
1688 /* If the access is outside of the variable we can ignore it. */
1689 if (!v)
1690 continue;
1694 if (v->may_have_pointers)
1696 t = find (v->id);
1697 if (add_graph_edge (graph, t, rhs)
1698 && bitmap_ior_into (get_varinfo (t)->solution, sol)
1699 && !TEST_BIT (changed, t))
1701 SET_BIT (changed, t);
1702 changed_count++;
1706 /* If the variable is not exactly at the requested offset
1707 we have to include the next one. */
1708 if (v->offset == (unsigned HOST_WIDE_INT)fieldoffset
1709 || v->next == NULL)
1710 break;
1712 v = v->next;
1713 fieldoffset = v->offset;
1715 while (1);
1719 /* Handle a non-simple (simple meaning requires no iteration),
1720 constraint (IE *x = &y, x = *y, *x = y, and x = y with offsets involved). */
1722 static void
1723 do_complex_constraint (constraint_graph_t graph, constraint_t c, bitmap delta)
1725 if (c->lhs.type == DEREF)
1727 if (c->rhs.type == ADDRESSOF)
1729 gcc_unreachable();
1731 else
1733 /* *x = y */
1734 do_ds_constraint (c, delta);
1737 else if (c->rhs.type == DEREF)
1739 /* x = *y */
1740 if (!(get_varinfo (c->lhs.var)->is_special_var))
1741 do_sd_constraint (graph, c, delta);
1743 else
1745 bitmap tmp;
1746 bitmap solution;
1747 bool flag = false;
1749 gcc_assert (c->rhs.type == SCALAR && c->lhs.type == SCALAR);
1750 solution = get_varinfo (c->rhs.var)->solution;
1751 tmp = get_varinfo (c->lhs.var)->solution;
1753 flag = set_union_with_increment (tmp, solution, c->rhs.offset);
1755 if (flag)
1757 get_varinfo (c->lhs.var)->solution = tmp;
1758 if (!TEST_BIT (changed, c->lhs.var))
1760 SET_BIT (changed, c->lhs.var);
1761 changed_count++;
1767 /* Initialize and return a new SCC info structure. */
1769 static struct scc_info *
1770 init_scc_info (size_t size)
1772 struct scc_info *si = XNEW (struct scc_info);
1773 size_t i;
1775 si->current_index = 0;
1776 si->visited = sbitmap_alloc (size);
1777 sbitmap_zero (si->visited);
1778 si->deleted = sbitmap_alloc (size);
1779 sbitmap_zero (si->deleted);
1780 si->node_mapping = XNEWVEC (unsigned int, size);
1781 si->dfs = XCNEWVEC (unsigned int, size);
1783 for (i = 0; i < size; i++)
1784 si->node_mapping[i] = i;
1786 si->scc_stack = VEC_alloc (unsigned, heap, 1);
1787 return si;
1790 /* Free an SCC info structure pointed to by SI */
1792 static void
1793 free_scc_info (struct scc_info *si)
1795 sbitmap_free (si->visited);
1796 sbitmap_free (si->deleted);
1797 free (si->node_mapping);
1798 free (si->dfs);
1799 VEC_free (unsigned, heap, si->scc_stack);
1800 free (si);
1804 /* Find indirect cycles in GRAPH that occur, using strongly connected
1805 components, and note them in the indirect cycles map.
1807 This technique comes from Ben Hardekopf and Calvin Lin,
1808 "It Pays to be Lazy: Fast and Accurate Pointer Analysis for Millions of
1809 Lines of Code", submitted to PLDI 2007. */
1811 static void
1812 find_indirect_cycles (constraint_graph_t graph)
1814 unsigned int i;
1815 unsigned int size = graph->size;
1816 struct scc_info *si = init_scc_info (size);
1818 for (i = 0; i < MIN (LAST_REF_NODE, size); i ++ )
1819 if (!TEST_BIT (si->visited, i) && find (i) == i)
1820 scc_visit (graph, si, i);
1822 free_scc_info (si);
1825 /* Compute a topological ordering for GRAPH, and store the result in the
1826 topo_info structure TI. */
1828 static void
1829 compute_topo_order (constraint_graph_t graph,
1830 struct topo_info *ti)
1832 unsigned int i;
1833 unsigned int size = graph->size;
1835 for (i = 0; i != size; ++i)
1836 if (!TEST_BIT (ti->visited, i) && find (i) == i)
1837 topo_visit (graph, ti, i);
1840 /* Structure used to for hash value numbering of pointer equivalence
1841 classes. */
1843 typedef struct equiv_class_label
1845 hashval_t hashcode;
1846 unsigned int equivalence_class;
1847 bitmap labels;
1848 } *equiv_class_label_t;
1849 typedef const struct equiv_class_label *const_equiv_class_label_t;
1851 /* A hashtable for mapping a bitmap of labels->pointer equivalence
1852 classes. */
1853 static htab_t pointer_equiv_class_table;
1855 /* A hashtable for mapping a bitmap of labels->location equivalence
1856 classes. */
1857 static htab_t location_equiv_class_table;
1859 /* Hash function for a equiv_class_label_t */
1861 static hashval_t
1862 equiv_class_label_hash (const void *p)
1864 const_equiv_class_label_t const ecl = (const_equiv_class_label_t) p;
1865 return ecl->hashcode;
1868 /* Equality function for two equiv_class_label_t's. */
1870 static int
1871 equiv_class_label_eq (const void *p1, const void *p2)
1873 const_equiv_class_label_t const eql1 = (const_equiv_class_label_t) p1;
1874 const_equiv_class_label_t const eql2 = (const_equiv_class_label_t) p2;
1875 return (eql1->hashcode == eql2->hashcode
1876 && bitmap_equal_p (eql1->labels, eql2->labels));
1879 /* Lookup a equivalence class in TABLE by the bitmap of LABELS it
1880 contains. */
1882 static unsigned int
1883 equiv_class_lookup (htab_t table, bitmap labels)
1885 void **slot;
1886 struct equiv_class_label ecl;
1888 ecl.labels = labels;
1889 ecl.hashcode = bitmap_hash (labels);
1891 slot = htab_find_slot_with_hash (table, &ecl,
1892 ecl.hashcode, NO_INSERT);
1893 if (!slot)
1894 return 0;
1895 else
1896 return ((equiv_class_label_t) *slot)->equivalence_class;
1900 /* Add an equivalence class named EQUIVALENCE_CLASS with labels LABELS
1901 to TABLE. */
1903 static void
1904 equiv_class_add (htab_t table, unsigned int equivalence_class,
1905 bitmap labels)
1907 void **slot;
1908 equiv_class_label_t ecl = XNEW (struct equiv_class_label);
1910 ecl->labels = labels;
1911 ecl->equivalence_class = equivalence_class;
1912 ecl->hashcode = bitmap_hash (labels);
1914 slot = htab_find_slot_with_hash (table, ecl,
1915 ecl->hashcode, INSERT);
1916 gcc_assert (!*slot);
1917 *slot = (void *) ecl;
1920 /* Perform offline variable substitution.
1922 This is a worst case quadratic time way of identifying variables
1923 that must have equivalent points-to sets, including those caused by
1924 static cycles, and single entry subgraphs, in the constraint graph.
1926 The technique is described in "Exploiting Pointer and Location
1927 Equivalence to Optimize Pointer Analysis. In the 14th International
1928 Static Analysis Symposium (SAS), August 2007." It is known as the
1929 "HU" algorithm, and is equivalent to value numbering the collapsed
1930 constraint graph including evaluating unions.
1932 The general method of finding equivalence classes is as follows:
1933 Add fake nodes (REF nodes) and edges for *a = b and a = *b constraints.
1934 Initialize all non-REF nodes to be direct nodes.
1935 For each constraint a = a U {b}, we set pts(a) = pts(a) u {fresh
1936 variable}
1937 For each constraint containing the dereference, we also do the same
1938 thing.
1940 We then compute SCC's in the graph and unify nodes in the same SCC,
1941 including pts sets.
1943 For each non-collapsed node x:
1944 Visit all unvisited explicit incoming edges.
1945 Ignoring all non-pointers, set pts(x) = Union of pts(a) for y
1946 where y->x.
1947 Lookup the equivalence class for pts(x).
1948 If we found one, equivalence_class(x) = found class.
1949 Otherwise, equivalence_class(x) = new class, and new_class is
1950 added to the lookup table.
1952 All direct nodes with the same equivalence class can be replaced
1953 with a single representative node.
1954 All unlabeled nodes (label == 0) are not pointers and all edges
1955 involving them can be eliminated.
1956 We perform these optimizations during rewrite_constraints
1958 In addition to pointer equivalence class finding, we also perform
1959 location equivalence class finding. This is the set of variables
1960 that always appear together in points-to sets. We use this to
1961 compress the size of the points-to sets. */
1963 /* Current maximum pointer equivalence class id. */
1964 static int pointer_equiv_class;
1966 /* Current maximum location equivalence class id. */
1967 static int location_equiv_class;
1969 /* Recursive routine to find strongly connected components in GRAPH,
1970 and label it's nodes with DFS numbers. */
1972 static void
1973 condense_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1975 unsigned int i;
1976 bitmap_iterator bi;
1977 unsigned int my_dfs;
1979 gcc_assert (si->node_mapping[n] == n);
1980 SET_BIT (si->visited, n);
1981 si->dfs[n] = si->current_index ++;
1982 my_dfs = si->dfs[n];
1984 /* Visit all the successors. */
1985 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
1987 unsigned int w = si->node_mapping[i];
1989 if (TEST_BIT (si->deleted, w))
1990 continue;
1992 if (!TEST_BIT (si->visited, w))
1993 condense_visit (graph, si, w);
1995 unsigned int t = si->node_mapping[w];
1996 unsigned int nnode = si->node_mapping[n];
1997 gcc_assert (nnode == n);
1999 if (si->dfs[t] < si->dfs[nnode])
2000 si->dfs[n] = si->dfs[t];
2004 /* Visit all the implicit predecessors. */
2005 EXECUTE_IF_IN_NONNULL_BITMAP (graph->implicit_preds[n], 0, i, bi)
2007 unsigned int w = si->node_mapping[i];
2009 if (TEST_BIT (si->deleted, w))
2010 continue;
2012 if (!TEST_BIT (si->visited, w))
2013 condense_visit (graph, si, w);
2015 unsigned int t = si->node_mapping[w];
2016 unsigned int nnode = si->node_mapping[n];
2017 gcc_assert (nnode == n);
2019 if (si->dfs[t] < si->dfs[nnode])
2020 si->dfs[n] = si->dfs[t];
2024 /* See if any components have been identified. */
2025 if (si->dfs[n] == my_dfs)
2027 while (VEC_length (unsigned, si->scc_stack) != 0
2028 && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
2030 unsigned int w = VEC_pop (unsigned, si->scc_stack);
2031 si->node_mapping[w] = n;
2033 if (!TEST_BIT (graph->direct_nodes, w))
2034 RESET_BIT (graph->direct_nodes, n);
2036 /* Unify our nodes. */
2037 if (graph->preds[w])
2039 if (!graph->preds[n])
2040 graph->preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2041 bitmap_ior_into (graph->preds[n], graph->preds[w]);
2043 if (graph->implicit_preds[w])
2045 if (!graph->implicit_preds[n])
2046 graph->implicit_preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2047 bitmap_ior_into (graph->implicit_preds[n],
2048 graph->implicit_preds[w]);
2050 if (graph->points_to[w])
2052 if (!graph->points_to[n])
2053 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2054 bitmap_ior_into (graph->points_to[n],
2055 graph->points_to[w]);
2058 SET_BIT (si->deleted, n);
2060 else
2061 VEC_safe_push (unsigned, heap, si->scc_stack, n);
2064 /* Label pointer equivalences. */
2066 static void
2067 label_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
2069 unsigned int i;
2070 bitmap_iterator bi;
2071 SET_BIT (si->visited, n);
2073 if (!graph->points_to[n])
2074 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2076 /* Label and union our incoming edges's points to sets. */
2077 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
2079 unsigned int w = si->node_mapping[i];
2080 if (!TEST_BIT (si->visited, w))
2081 label_visit (graph, si, w);
2083 /* Skip unused edges */
2084 if (w == n || graph->pointer_label[w] == 0)
2085 continue;
2087 if (graph->points_to[w])
2088 bitmap_ior_into(graph->points_to[n], graph->points_to[w]);
2090 /* Indirect nodes get fresh variables. */
2091 if (!TEST_BIT (graph->direct_nodes, n))
2092 bitmap_set_bit (graph->points_to[n], FIRST_REF_NODE + n);
2094 if (!bitmap_empty_p (graph->points_to[n]))
2096 unsigned int label = equiv_class_lookup (pointer_equiv_class_table,
2097 graph->points_to[n]);
2098 if (!label)
2100 label = pointer_equiv_class++;
2101 equiv_class_add (pointer_equiv_class_table,
2102 label, graph->points_to[n]);
2104 graph->pointer_label[n] = label;
2108 /* Perform offline variable substitution, discovering equivalence
2109 classes, and eliminating non-pointer variables. */
2111 static struct scc_info *
2112 perform_var_substitution (constraint_graph_t graph)
2114 unsigned int i;
2115 unsigned int size = graph->size;
2116 struct scc_info *si = init_scc_info (size);
2118 bitmap_obstack_initialize (&iteration_obstack);
2119 pointer_equiv_class_table = htab_create (511, equiv_class_label_hash,
2120 equiv_class_label_eq, free);
2121 location_equiv_class_table = htab_create (511, equiv_class_label_hash,
2122 equiv_class_label_eq, free);
2123 pointer_equiv_class = 1;
2124 location_equiv_class = 1;
2126 /* Condense the nodes, which means to find SCC's, count incoming
2127 predecessors, and unite nodes in SCC's. */
2128 for (i = 0; i < FIRST_REF_NODE; i++)
2129 if (!TEST_BIT (si->visited, si->node_mapping[i]))
2130 condense_visit (graph, si, si->node_mapping[i]);
2132 sbitmap_zero (si->visited);
2133 /* Actually the label the nodes for pointer equivalences */
2134 for (i = 0; i < FIRST_REF_NODE; i++)
2135 if (!TEST_BIT (si->visited, si->node_mapping[i]))
2136 label_visit (graph, si, si->node_mapping[i]);
2138 /* Calculate location equivalence labels. */
2139 for (i = 0; i < FIRST_REF_NODE; i++)
2141 bitmap pointed_by;
2142 bitmap_iterator bi;
2143 unsigned int j;
2144 unsigned int label;
2146 if (!graph->pointed_by[i])
2147 continue;
2148 pointed_by = BITMAP_ALLOC (&iteration_obstack);
2150 /* Translate the pointed-by mapping for pointer equivalence
2151 labels. */
2152 EXECUTE_IF_SET_IN_BITMAP (graph->pointed_by[i], 0, j, bi)
2154 bitmap_set_bit (pointed_by,
2155 graph->pointer_label[si->node_mapping[j]]);
2157 /* The original pointed_by is now dead. */
2158 BITMAP_FREE (graph->pointed_by[i]);
2160 /* Look up the location equivalence label if one exists, or make
2161 one otherwise. */
2162 label = equiv_class_lookup (location_equiv_class_table,
2163 pointed_by);
2164 if (label == 0)
2166 label = location_equiv_class++;
2167 equiv_class_add (location_equiv_class_table,
2168 label, pointed_by);
2170 else
2172 if (dump_file && (dump_flags & TDF_DETAILS))
2173 fprintf (dump_file, "Found location equivalence for node %s\n",
2174 get_varinfo (i)->name);
2175 BITMAP_FREE (pointed_by);
2177 graph->loc_label[i] = label;
2181 if (dump_file && (dump_flags & TDF_DETAILS))
2182 for (i = 0; i < FIRST_REF_NODE; i++)
2184 bool direct_node = TEST_BIT (graph->direct_nodes, i);
2185 fprintf (dump_file,
2186 "Equivalence classes for %s node id %d:%s are pointer: %d"
2187 ", location:%d\n",
2188 direct_node ? "Direct node" : "Indirect node", i,
2189 get_varinfo (i)->name,
2190 graph->pointer_label[si->node_mapping[i]],
2191 graph->loc_label[si->node_mapping[i]]);
2194 /* Quickly eliminate our non-pointer variables. */
2196 for (i = 0; i < FIRST_REF_NODE; i++)
2198 unsigned int node = si->node_mapping[i];
2200 if (graph->pointer_label[node] == 0)
2202 if (dump_file && (dump_flags & TDF_DETAILS))
2203 fprintf (dump_file,
2204 "%s is a non-pointer variable, eliminating edges.\n",
2205 get_varinfo (node)->name);
2206 stats.nonpointer_vars++;
2207 clear_edges_for_node (graph, node);
2211 return si;
2214 /* Free information that was only necessary for variable
2215 substitution. */
2217 static void
2218 free_var_substitution_info (struct scc_info *si)
2220 free_scc_info (si);
2221 free (graph->pointer_label);
2222 free (graph->loc_label);
2223 free (graph->pointed_by);
2224 free (graph->points_to);
2225 free (graph->eq_rep);
2226 sbitmap_free (graph->direct_nodes);
2227 htab_delete (pointer_equiv_class_table);
2228 htab_delete (location_equiv_class_table);
2229 bitmap_obstack_release (&iteration_obstack);
2232 /* Return an existing node that is equivalent to NODE, which has
2233 equivalence class LABEL, if one exists. Return NODE otherwise. */
2235 static unsigned int
2236 find_equivalent_node (constraint_graph_t graph,
2237 unsigned int node, unsigned int label)
2239 /* If the address version of this variable is unused, we can
2240 substitute it for anything else with the same label.
2241 Otherwise, we know the pointers are equivalent, but not the
2242 locations, and we can unite them later. */
2244 if (!bitmap_bit_p (graph->address_taken, node))
2246 gcc_assert (label < graph->size);
2248 if (graph->eq_rep[label] != -1)
2250 /* Unify the two variables since we know they are equivalent. */
2251 if (unite (graph->eq_rep[label], node))
2252 unify_nodes (graph, graph->eq_rep[label], node, false);
2253 return graph->eq_rep[label];
2255 else
2257 graph->eq_rep[label] = node;
2258 graph->pe_rep[label] = node;
2261 else
2263 gcc_assert (label < graph->size);
2264 graph->pe[node] = label;
2265 if (graph->pe_rep[label] == -1)
2266 graph->pe_rep[label] = node;
2269 return node;
2272 /* Unite pointer equivalent but not location equivalent nodes in
2273 GRAPH. This may only be performed once variable substitution is
2274 finished. */
2276 static void
2277 unite_pointer_equivalences (constraint_graph_t graph)
2279 unsigned int i;
2281 /* Go through the pointer equivalences and unite them to their
2282 representative, if they aren't already. */
2283 for (i = 0; i < FIRST_REF_NODE; i++)
2285 unsigned int label = graph->pe[i];
2286 if (label)
2288 int label_rep = graph->pe_rep[label];
2290 if (label_rep == -1)
2291 continue;
2293 label_rep = find (label_rep);
2294 if (label_rep >= 0 && unite (label_rep, find (i)))
2295 unify_nodes (graph, label_rep, i, false);
2300 /* Move complex constraints to the GRAPH nodes they belong to. */
2302 static void
2303 move_complex_constraints (constraint_graph_t graph)
2305 int i;
2306 constraint_t c;
2308 for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
2310 if (c)
2312 struct constraint_expr lhs = c->lhs;
2313 struct constraint_expr rhs = c->rhs;
2315 if (lhs.type == DEREF)
2317 insert_into_complex (graph, lhs.var, c);
2319 else if (rhs.type == DEREF)
2321 if (!(get_varinfo (lhs.var)->is_special_var))
2322 insert_into_complex (graph, rhs.var, c);
2324 else if (rhs.type != ADDRESSOF && lhs.var > anything_id
2325 && (lhs.offset != 0 || rhs.offset != 0))
2327 insert_into_complex (graph, rhs.var, c);
2334 /* Optimize and rewrite complex constraints while performing
2335 collapsing of equivalent nodes. SI is the SCC_INFO that is the
2336 result of perform_variable_substitution. */
2338 static void
2339 rewrite_constraints (constraint_graph_t graph,
2340 struct scc_info *si)
2342 int i;
2343 unsigned int j;
2344 constraint_t c;
2346 for (j = 0; j < graph->size; j++)
2347 gcc_assert (find (j) == j);
2349 for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
2351 struct constraint_expr lhs = c->lhs;
2352 struct constraint_expr rhs = c->rhs;
2353 unsigned int lhsvar = find (lhs.var);
2354 unsigned int rhsvar = find (rhs.var);
2355 unsigned int lhsnode, rhsnode;
2356 unsigned int lhslabel, rhslabel;
2358 lhsnode = si->node_mapping[lhsvar];
2359 rhsnode = si->node_mapping[rhsvar];
2360 lhslabel = graph->pointer_label[lhsnode];
2361 rhslabel = graph->pointer_label[rhsnode];
2363 /* See if it is really a non-pointer variable, and if so, ignore
2364 the constraint. */
2365 if (lhslabel == 0)
2367 if (dump_file && (dump_flags & TDF_DETAILS))
2370 fprintf (dump_file, "%s is a non-pointer variable,"
2371 "ignoring constraint:",
2372 get_varinfo (lhs.var)->name);
2373 dump_constraint (dump_file, c);
2375 VEC_replace (constraint_t, constraints, i, NULL);
2376 continue;
2379 if (rhslabel == 0)
2381 if (dump_file && (dump_flags & TDF_DETAILS))
2384 fprintf (dump_file, "%s is a non-pointer variable,"
2385 "ignoring constraint:",
2386 get_varinfo (rhs.var)->name);
2387 dump_constraint (dump_file, c);
2389 VEC_replace (constraint_t, constraints, i, NULL);
2390 continue;
2393 lhsvar = find_equivalent_node (graph, lhsvar, lhslabel);
2394 rhsvar = find_equivalent_node (graph, rhsvar, rhslabel);
2395 c->lhs.var = lhsvar;
2396 c->rhs.var = rhsvar;
2401 /* Eliminate indirect cycles involving NODE. Return true if NODE was
2402 part of an SCC, false otherwise. */
2404 static bool
2405 eliminate_indirect_cycles (unsigned int node)
2407 if (graph->indirect_cycles[node] != -1
2408 && !bitmap_empty_p (get_varinfo (node)->solution))
2410 unsigned int i;
2411 VEC(unsigned,heap) *queue = NULL;
2412 int queuepos;
2413 unsigned int to = find (graph->indirect_cycles[node]);
2414 bitmap_iterator bi;
2416 /* We can't touch the solution set and call unify_nodes
2417 at the same time, because unify_nodes is going to do
2418 bitmap unions into it. */
2420 EXECUTE_IF_SET_IN_BITMAP (get_varinfo (node)->solution, 0, i, bi)
2422 if (find (i) == i && i != to)
2424 if (unite (to, i))
2425 VEC_safe_push (unsigned, heap, queue, i);
2429 for (queuepos = 0;
2430 VEC_iterate (unsigned, queue, queuepos, i);
2431 queuepos++)
2433 unify_nodes (graph, to, i, true);
2435 VEC_free (unsigned, heap, queue);
2436 return true;
2438 return false;
2441 /* Solve the constraint graph GRAPH using our worklist solver.
2442 This is based on the PW* family of solvers from the "Efficient Field
2443 Sensitive Pointer Analysis for C" paper.
2444 It works by iterating over all the graph nodes, processing the complex
2445 constraints and propagating the copy constraints, until everything stops
2446 changed. This corresponds to steps 6-8 in the solving list given above. */
2448 static void
2449 solve_graph (constraint_graph_t graph)
2451 unsigned int size = graph->size;
2452 unsigned int i;
2453 bitmap pts;
2455 changed_count = 0;
2456 changed = sbitmap_alloc (size);
2457 sbitmap_zero (changed);
2459 /* Mark all initial non-collapsed nodes as changed. */
2460 for (i = 0; i < size; i++)
2462 varinfo_t ivi = get_varinfo (i);
2463 if (find (i) == i && !bitmap_empty_p (ivi->solution)
2464 && ((graph->succs[i] && !bitmap_empty_p (graph->succs[i]))
2465 || VEC_length (constraint_t, graph->complex[i]) > 0))
2467 SET_BIT (changed, i);
2468 changed_count++;
2472 /* Allocate a bitmap to be used to store the changed bits. */
2473 pts = BITMAP_ALLOC (&pta_obstack);
2475 while (changed_count > 0)
2477 unsigned int i;
2478 struct topo_info *ti = init_topo_info ();
2479 stats.iterations++;
2481 bitmap_obstack_initialize (&iteration_obstack);
2483 compute_topo_order (graph, ti);
2485 while (VEC_length (unsigned, ti->topo_order) != 0)
2488 i = VEC_pop (unsigned, ti->topo_order);
2490 /* If this variable is not a representative, skip it. */
2491 if (find (i) != i)
2492 continue;
2494 /* In certain indirect cycle cases, we may merge this
2495 variable to another. */
2496 if (eliminate_indirect_cycles (i) && find (i) != i)
2497 continue;
2499 /* If the node has changed, we need to process the
2500 complex constraints and outgoing edges again. */
2501 if (TEST_BIT (changed, i))
2503 unsigned int j;
2504 constraint_t c;
2505 bitmap solution;
2506 VEC(constraint_t,heap) *complex = graph->complex[i];
2507 bool solution_empty;
2509 RESET_BIT (changed, i);
2510 changed_count--;
2512 /* Compute the changed set of solution bits. */
2513 bitmap_and_compl (pts, get_varinfo (i)->solution,
2514 get_varinfo (i)->oldsolution);
2516 if (bitmap_empty_p (pts))
2517 continue;
2519 bitmap_ior_into (get_varinfo (i)->oldsolution, pts);
2521 solution = get_varinfo (i)->solution;
2522 solution_empty = bitmap_empty_p (solution);
2524 /* Process the complex constraints */
2525 for (j = 0; VEC_iterate (constraint_t, complex, j, c); j++)
2527 /* XXX: This is going to unsort the constraints in
2528 some cases, which will occasionally add duplicate
2529 constraints during unification. This does not
2530 affect correctness. */
2531 c->lhs.var = find (c->lhs.var);
2532 c->rhs.var = find (c->rhs.var);
2534 /* The only complex constraint that can change our
2535 solution to non-empty, given an empty solution,
2536 is a constraint where the lhs side is receiving
2537 some set from elsewhere. */
2538 if (!solution_empty || c->lhs.type != DEREF)
2539 do_complex_constraint (graph, c, pts);
2542 solution_empty = bitmap_empty_p (solution);
2544 if (!solution_empty)
2546 bitmap_iterator bi;
2547 unsigned eff_escaped_id = find (escaped_id);
2549 /* Propagate solution to all successors. */
2550 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i],
2551 0, j, bi)
2553 bitmap tmp;
2554 bool flag;
2556 unsigned int to = find (j);
2557 tmp = get_varinfo (to)->solution;
2558 flag = false;
2560 /* Don't try to propagate to ourselves. */
2561 if (to == i)
2562 continue;
2564 /* If we propagate from ESCAPED use ESCAPED as
2565 placeholder. */
2566 if (i == eff_escaped_id)
2567 flag = bitmap_set_bit (tmp, escaped_id);
2568 else
2569 flag = set_union_with_increment (tmp, pts, 0);
2571 if (flag)
2573 get_varinfo (to)->solution = tmp;
2574 if (!TEST_BIT (changed, to))
2576 SET_BIT (changed, to);
2577 changed_count++;
2584 free_topo_info (ti);
2585 bitmap_obstack_release (&iteration_obstack);
2588 BITMAP_FREE (pts);
2589 sbitmap_free (changed);
2590 bitmap_obstack_release (&oldpta_obstack);
2593 /* Map from trees to variable infos. */
2594 static struct pointer_map_t *vi_for_tree;
2597 /* Insert ID as the variable id for tree T in the vi_for_tree map. */
2599 static void
2600 insert_vi_for_tree (tree t, varinfo_t vi)
2602 void **slot = pointer_map_insert (vi_for_tree, t);
2603 gcc_assert (vi);
2604 gcc_assert (*slot == NULL);
2605 *slot = vi;
2608 /* Find the variable info for tree T in VI_FOR_TREE. If T does not
2609 exist in the map, return NULL, otherwise, return the varinfo we found. */
2611 static varinfo_t
2612 lookup_vi_for_tree (tree t)
2614 void **slot = pointer_map_contains (vi_for_tree, t);
2615 if (slot == NULL)
2616 return NULL;
2618 return (varinfo_t) *slot;
2621 /* Return a printable name for DECL */
2623 static const char *
2624 alias_get_name (tree decl)
2626 const char *res = get_name (decl);
2627 char *temp;
2628 int num_printed = 0;
2630 if (res != NULL)
2631 return res;
2633 res = "NULL";
2634 if (!dump_file)
2635 return res;
2637 if (TREE_CODE (decl) == SSA_NAME)
2639 num_printed = asprintf (&temp, "%s_%u",
2640 alias_get_name (SSA_NAME_VAR (decl)),
2641 SSA_NAME_VERSION (decl));
2643 else if (DECL_P (decl))
2645 num_printed = asprintf (&temp, "D.%u", DECL_UID (decl));
2647 if (num_printed > 0)
2649 res = ggc_strdup (temp);
2650 free (temp);
2652 return res;
2655 /* Find the variable id for tree T in the map.
2656 If T doesn't exist in the map, create an entry for it and return it. */
2658 static varinfo_t
2659 get_vi_for_tree (tree t)
2661 void **slot = pointer_map_contains (vi_for_tree, t);
2662 if (slot == NULL)
2663 return get_varinfo (create_variable_info_for (t, alias_get_name (t)));
2665 return (varinfo_t) *slot;
2668 /* Get a scalar constraint expression for a new temporary variable. */
2670 static struct constraint_expr
2671 new_scalar_tmp_constraint_exp (const char *name)
2673 struct constraint_expr tmp;
2674 varinfo_t vi;
2676 vi = new_var_info (NULL_TREE, name);
2677 vi->offset = 0;
2678 vi->size = -1;
2679 vi->fullsize = -1;
2680 vi->is_full_var = 1;
2682 tmp.var = vi->id;
2683 tmp.type = SCALAR;
2684 tmp.offset = 0;
2686 return tmp;
2689 /* Get a constraint expression vector from an SSA_VAR_P node.
2690 If address_p is true, the result will be taken its address of. */
2692 static void
2693 get_constraint_for_ssa_var (tree t, VEC(ce_s, heap) **results, bool address_p)
2695 struct constraint_expr cexpr;
2696 varinfo_t vi;
2698 /* We allow FUNCTION_DECLs here even though it doesn't make much sense. */
2699 gcc_assert (SSA_VAR_P (t) || DECL_P (t));
2701 /* For parameters, get at the points-to set for the actual parm
2702 decl. */
2703 if (TREE_CODE (t) == SSA_NAME
2704 && TREE_CODE (SSA_NAME_VAR (t)) == PARM_DECL
2705 && SSA_NAME_IS_DEFAULT_DEF (t))
2707 get_constraint_for_ssa_var (SSA_NAME_VAR (t), results, address_p);
2708 return;
2711 vi = get_vi_for_tree (t);
2712 cexpr.var = vi->id;
2713 cexpr.type = SCALAR;
2714 cexpr.offset = 0;
2715 /* If we determine the result is "anything", and we know this is readonly,
2716 say it points to readonly memory instead. */
2717 if (cexpr.var == anything_id && TREE_READONLY (t))
2719 gcc_unreachable ();
2720 cexpr.type = ADDRESSOF;
2721 cexpr.var = readonly_id;
2724 /* If we are not taking the address of the constraint expr, add all
2725 sub-fiels of the variable as well. */
2726 if (!address_p
2727 && !vi->is_full_var)
2729 for (; vi; vi = vi->next)
2731 cexpr.var = vi->id;
2732 VEC_safe_push (ce_s, heap, *results, &cexpr);
2734 return;
2737 VEC_safe_push (ce_s, heap, *results, &cexpr);
2740 /* Process constraint T, performing various simplifications and then
2741 adding it to our list of overall constraints. */
2743 static void
2744 process_constraint (constraint_t t)
2746 struct constraint_expr rhs = t->rhs;
2747 struct constraint_expr lhs = t->lhs;
2749 gcc_assert (rhs.var < VEC_length (varinfo_t, varmap));
2750 gcc_assert (lhs.var < VEC_length (varinfo_t, varmap));
2752 /* If we didn't get any useful constraint from the lhs we get
2753 &ANYTHING as fallback from get_constraint_for. Deal with
2754 it here by turning it into *ANYTHING. */
2755 if (lhs.type == ADDRESSOF
2756 && lhs.var == anything_id)
2757 lhs.type = DEREF;
2759 /* ADDRESSOF on the lhs is invalid. */
2760 gcc_assert (lhs.type != ADDRESSOF);
2762 /* This can happen in our IR with things like n->a = *p */
2763 if (rhs.type == DEREF && lhs.type == DEREF && rhs.var != anything_id)
2765 /* Split into tmp = *rhs, *lhs = tmp */
2766 struct constraint_expr tmplhs;
2767 tmplhs = new_scalar_tmp_constraint_exp ("doubledereftmp");
2768 process_constraint (new_constraint (tmplhs, rhs));
2769 process_constraint (new_constraint (lhs, tmplhs));
2771 else if (rhs.type == ADDRESSOF && lhs.type == DEREF)
2773 /* Split into tmp = &rhs, *lhs = tmp */
2774 struct constraint_expr tmplhs;
2775 tmplhs = new_scalar_tmp_constraint_exp ("derefaddrtmp");
2776 process_constraint (new_constraint (tmplhs, rhs));
2777 process_constraint (new_constraint (lhs, tmplhs));
2779 else
2781 gcc_assert (rhs.type != ADDRESSOF || rhs.offset == 0);
2782 VEC_safe_push (constraint_t, heap, constraints, t);
2786 /* Return true if T is a type that could contain pointers. */
2788 static bool
2789 type_could_have_pointers (tree type)
2791 if (POINTER_TYPE_P (type))
2792 return true;
2794 if (TREE_CODE (type) == ARRAY_TYPE)
2795 return type_could_have_pointers (TREE_TYPE (type));
2797 return AGGREGATE_TYPE_P (type);
2800 /* Return true if T is a variable of a type that could contain
2801 pointers. */
2803 static bool
2804 could_have_pointers (tree t)
2806 return type_could_have_pointers (TREE_TYPE (t));
2809 /* Return the position, in bits, of FIELD_DECL from the beginning of its
2810 structure. */
2812 static HOST_WIDE_INT
2813 bitpos_of_field (const tree fdecl)
2816 if (!host_integerp (DECL_FIELD_OFFSET (fdecl), 0)
2817 || !host_integerp (DECL_FIELD_BIT_OFFSET (fdecl), 0))
2818 return -1;
2820 return (TREE_INT_CST_LOW (DECL_FIELD_OFFSET (fdecl)) * 8
2821 + TREE_INT_CST_LOW (DECL_FIELD_BIT_OFFSET (fdecl)));
2825 /* Get constraint expressions for offsetting PTR by OFFSET. Stores the
2826 resulting constraint expressions in *RESULTS. */
2828 static void
2829 get_constraint_for_ptr_offset (tree ptr, tree offset,
2830 VEC (ce_s, heap) **results)
2832 struct constraint_expr c;
2833 unsigned int j, n;
2834 HOST_WIDE_INT rhsunitoffset, rhsoffset;
2836 /* If we do not do field-sensitive PTA adding offsets to pointers
2837 does not change the points-to solution. */
2838 if (!use_field_sensitive)
2840 get_constraint_for (ptr, results);
2841 return;
2844 /* If the offset is not a non-negative integer constant that fits
2845 in a HOST_WIDE_INT, we have to fall back to a conservative
2846 solution which includes all sub-fields of all pointed-to
2847 variables of ptr. */
2848 if (offset == NULL_TREE
2849 || !host_integerp (offset, 0))
2850 rhsoffset = UNKNOWN_OFFSET;
2851 else
2853 /* Make sure the bit-offset also fits. */
2854 rhsunitoffset = TREE_INT_CST_LOW (offset);
2855 rhsoffset = rhsunitoffset * BITS_PER_UNIT;
2856 if (rhsunitoffset != rhsoffset / BITS_PER_UNIT)
2857 rhsoffset = UNKNOWN_OFFSET;
2860 get_constraint_for (ptr, results);
2861 if (rhsoffset == 0)
2862 return;
2864 /* As we are eventually appending to the solution do not use
2865 VEC_iterate here. */
2866 n = VEC_length (ce_s, *results);
2867 for (j = 0; j < n; j++)
2869 varinfo_t curr;
2870 c = *VEC_index (ce_s, *results, j);
2871 curr = get_varinfo (c.var);
2873 if (c.type == ADDRESSOF
2874 /* If this varinfo represents a full variable just use it. */
2875 && curr->is_full_var)
2876 c.offset = 0;
2877 else if (c.type == ADDRESSOF
2878 /* If we do not know the offset add all subfields. */
2879 && rhsoffset == UNKNOWN_OFFSET)
2881 varinfo_t temp = lookup_vi_for_tree (curr->decl);
2884 struct constraint_expr c2;
2885 c2.var = temp->id;
2886 c2.type = ADDRESSOF;
2887 c2.offset = 0;
2888 if (c2.var != c.var)
2889 VEC_safe_push (ce_s, heap, *results, &c2);
2890 temp = temp->next;
2892 while (temp);
2894 else if (c.type == ADDRESSOF)
2896 varinfo_t temp;
2897 unsigned HOST_WIDE_INT offset = curr->offset + rhsoffset;
2899 /* Search the sub-field which overlaps with the
2900 pointed-to offset. If the result is outside of the variable
2901 we have to provide a conservative result, as the variable is
2902 still reachable from the resulting pointer (even though it
2903 technically cannot point to anything). The last and first
2904 sub-fields are such conservative results.
2905 ??? If we always had a sub-field for &object + 1 then
2906 we could represent this in a more precise way. */
2907 if (rhsoffset < 0
2908 && curr->offset < offset)
2909 offset = 0;
2910 temp = first_or_preceding_vi_for_offset (curr, offset);
2912 /* If the found variable is not exactly at the pointed to
2913 result, we have to include the next variable in the
2914 solution as well. Otherwise two increments by offset / 2
2915 do not result in the same or a conservative superset
2916 solution. */
2917 if (temp->offset != offset
2918 && temp->next != NULL)
2920 struct constraint_expr c2;
2921 c2.var = temp->next->id;
2922 c2.type = ADDRESSOF;
2923 c2.offset = 0;
2924 VEC_safe_push (ce_s, heap, *results, &c2);
2926 c.var = temp->id;
2927 c.offset = 0;
2929 else
2930 c.offset = rhsoffset;
2932 VEC_replace (ce_s, *results, j, &c);
2937 /* Given a COMPONENT_REF T, return the constraint_expr vector for it.
2938 If address_p is true the result will be taken its address of. */
2940 static void
2941 get_constraint_for_component_ref (tree t, VEC(ce_s, heap) **results,
2942 bool address_p)
2944 tree orig_t = t;
2945 HOST_WIDE_INT bitsize = -1;
2946 HOST_WIDE_INT bitmaxsize = -1;
2947 HOST_WIDE_INT bitpos;
2948 tree forzero;
2949 struct constraint_expr *result;
2951 /* Some people like to do cute things like take the address of
2952 &0->a.b */
2953 forzero = t;
2954 while (!SSA_VAR_P (forzero) && !CONSTANT_CLASS_P (forzero))
2955 forzero = TREE_OPERAND (forzero, 0);
2957 if (CONSTANT_CLASS_P (forzero) && integer_zerop (forzero))
2959 struct constraint_expr temp;
2961 temp.offset = 0;
2962 temp.var = integer_id;
2963 temp.type = SCALAR;
2964 VEC_safe_push (ce_s, heap, *results, &temp);
2965 return;
2968 t = get_ref_base_and_extent (t, &bitpos, &bitsize, &bitmaxsize);
2970 /* Pretend to take the address of the base, we'll take care of
2971 adding the required subset of sub-fields below. */
2972 get_constraint_for_1 (t, results, true);
2973 gcc_assert (VEC_length (ce_s, *results) == 1);
2974 result = VEC_last (ce_s, *results);
2976 if (result->type == SCALAR
2977 && get_varinfo (result->var)->is_full_var)
2978 /* For single-field vars do not bother about the offset. */
2979 result->offset = 0;
2980 else if (result->type == SCALAR)
2982 /* In languages like C, you can access one past the end of an
2983 array. You aren't allowed to dereference it, so we can
2984 ignore this constraint. When we handle pointer subtraction,
2985 we may have to do something cute here. */
2987 if ((unsigned HOST_WIDE_INT)bitpos < get_varinfo (result->var)->fullsize
2988 && bitmaxsize != 0)
2990 /* It's also not true that the constraint will actually start at the
2991 right offset, it may start in some padding. We only care about
2992 setting the constraint to the first actual field it touches, so
2993 walk to find it. */
2994 struct constraint_expr cexpr = *result;
2995 varinfo_t curr;
2996 VEC_pop (ce_s, *results);
2997 cexpr.offset = 0;
2998 for (curr = get_varinfo (cexpr.var); curr; curr = curr->next)
3000 if (ranges_overlap_p (curr->offset, curr->size,
3001 bitpos, bitmaxsize))
3003 cexpr.var = curr->id;
3004 VEC_safe_push (ce_s, heap, *results, &cexpr);
3005 if (address_p)
3006 break;
3009 /* If we are going to take the address of this field then
3010 to be able to compute reachability correctly add at least
3011 the last field of the variable. */
3012 if (address_p
3013 && VEC_length (ce_s, *results) == 0)
3015 curr = get_varinfo (cexpr.var);
3016 while (curr->next != NULL)
3017 curr = curr->next;
3018 cexpr.var = curr->id;
3019 VEC_safe_push (ce_s, heap, *results, &cexpr);
3021 else
3022 /* Assert that we found *some* field there. The user couldn't be
3023 accessing *only* padding. */
3024 /* Still the user could access one past the end of an array
3025 embedded in a struct resulting in accessing *only* padding. */
3026 gcc_assert (VEC_length (ce_s, *results) >= 1
3027 || ref_contains_array_ref (orig_t));
3029 else if (bitmaxsize == 0)
3031 if (dump_file && (dump_flags & TDF_DETAILS))
3032 fprintf (dump_file, "Access to zero-sized part of variable,"
3033 "ignoring\n");
3035 else
3036 if (dump_file && (dump_flags & TDF_DETAILS))
3037 fprintf (dump_file, "Access to past the end of variable, ignoring\n");
3039 else if (result->type == DEREF)
3041 /* If we do not know exactly where the access goes say so. Note
3042 that only for non-structure accesses we know that we access
3043 at most one subfiled of any variable. */
3044 if (bitpos == -1
3045 || bitsize != bitmaxsize
3046 || AGGREGATE_TYPE_P (TREE_TYPE (orig_t)))
3047 result->offset = UNKNOWN_OFFSET;
3048 else
3049 result->offset = bitpos;
3051 else if (result->type == ADDRESSOF)
3053 /* We can end up here for component references on a
3054 VIEW_CONVERT_EXPR <>(&foobar). */
3055 result->type = SCALAR;
3056 result->var = anything_id;
3057 result->offset = 0;
3059 else
3060 gcc_unreachable ();
3064 /* Dereference the constraint expression CONS, and return the result.
3065 DEREF (ADDRESSOF) = SCALAR
3066 DEREF (SCALAR) = DEREF
3067 DEREF (DEREF) = (temp = DEREF1; result = DEREF(temp))
3068 This is needed so that we can handle dereferencing DEREF constraints. */
3070 static void
3071 do_deref (VEC (ce_s, heap) **constraints)
3073 struct constraint_expr *c;
3074 unsigned int i = 0;
3076 for (i = 0; VEC_iterate (ce_s, *constraints, i, c); i++)
3078 if (c->type == SCALAR)
3079 c->type = DEREF;
3080 else if (c->type == ADDRESSOF)
3081 c->type = SCALAR;
3082 else if (c->type == DEREF)
3084 struct constraint_expr tmplhs;
3085 tmplhs = new_scalar_tmp_constraint_exp ("dereftmp");
3086 process_constraint (new_constraint (tmplhs, *c));
3087 c->var = tmplhs.var;
3089 else
3090 gcc_unreachable ();
3094 static void get_constraint_for_1 (tree, VEC (ce_s, heap) **, bool);
3096 /* Given a tree T, return the constraint expression for taking the
3097 address of it. */
3099 static void
3100 get_constraint_for_address_of (tree t, VEC (ce_s, heap) **results)
3102 struct constraint_expr *c;
3103 unsigned int i;
3105 get_constraint_for_1 (t, results, true);
3107 for (i = 0; VEC_iterate (ce_s, *results, i, c); i++)
3109 if (c->type == DEREF)
3110 c->type = SCALAR;
3111 else
3112 c->type = ADDRESSOF;
3116 /* Given a tree T, return the constraint expression for it. */
3118 static void
3119 get_constraint_for_1 (tree t, VEC (ce_s, heap) **results, bool address_p)
3121 struct constraint_expr temp;
3123 /* x = integer is all glommed to a single variable, which doesn't
3124 point to anything by itself. That is, of course, unless it is an
3125 integer constant being treated as a pointer, in which case, we
3126 will return that this is really the addressof anything. This
3127 happens below, since it will fall into the default case. The only
3128 case we know something about an integer treated like a pointer is
3129 when it is the NULL pointer, and then we just say it points to
3130 NULL.
3132 Do not do that if -fno-delete-null-pointer-checks though, because
3133 in that case *NULL does not fail, so it _should_ alias *anything.
3134 It is not worth adding a new option or renaming the existing one,
3135 since this case is relatively obscure. */
3136 if (flag_delete_null_pointer_checks
3137 && ((TREE_CODE (t) == INTEGER_CST
3138 && integer_zerop (t))
3139 /* The only valid CONSTRUCTORs in gimple with pointer typed
3140 elements are zero-initializer. */
3141 || TREE_CODE (t) == CONSTRUCTOR))
3143 temp.var = nothing_id;
3144 temp.type = ADDRESSOF;
3145 temp.offset = 0;
3146 VEC_safe_push (ce_s, heap, *results, &temp);
3147 return;
3150 /* String constants are read-only. */
3151 if (TREE_CODE (t) == STRING_CST)
3153 temp.var = readonly_id;
3154 temp.type = SCALAR;
3155 temp.offset = 0;
3156 VEC_safe_push (ce_s, heap, *results, &temp);
3157 return;
3160 switch (TREE_CODE_CLASS (TREE_CODE (t)))
3162 case tcc_expression:
3164 switch (TREE_CODE (t))
3166 case ADDR_EXPR:
3167 get_constraint_for_address_of (TREE_OPERAND (t, 0), results);
3168 return;
3169 default:;
3171 break;
3173 case tcc_reference:
3175 switch (TREE_CODE (t))
3177 case INDIRECT_REF:
3179 get_constraint_for_1 (TREE_OPERAND (t, 0), results, address_p);
3180 do_deref (results);
3181 return;
3183 case ARRAY_REF:
3184 case ARRAY_RANGE_REF:
3185 case COMPONENT_REF:
3186 get_constraint_for_component_ref (t, results, address_p);
3187 return;
3188 case VIEW_CONVERT_EXPR:
3189 get_constraint_for_1 (TREE_OPERAND (t, 0), results, address_p);
3190 return;
3191 /* We are missing handling for TARGET_MEM_REF here. */
3192 default:;
3194 break;
3196 case tcc_exceptional:
3198 switch (TREE_CODE (t))
3200 case SSA_NAME:
3202 get_constraint_for_ssa_var (t, results, address_p);
3203 return;
3205 default:;
3207 break;
3209 case tcc_declaration:
3211 get_constraint_for_ssa_var (t, results, address_p);
3212 return;
3214 default:;
3217 /* The default fallback is a constraint from anything. */
3218 temp.type = ADDRESSOF;
3219 temp.var = anything_id;
3220 temp.offset = 0;
3221 VEC_safe_push (ce_s, heap, *results, &temp);
3224 /* Given a gimple tree T, return the constraint expression vector for it. */
3226 static void
3227 get_constraint_for (tree t, VEC (ce_s, heap) **results)
3229 gcc_assert (VEC_length (ce_s, *results) == 0);
3231 get_constraint_for_1 (t, results, false);
3235 /* Efficiently generates constraints from all entries in *RHSC to all
3236 entries in *LHSC. */
3238 static void
3239 process_all_all_constraints (VEC (ce_s, heap) *lhsc, VEC (ce_s, heap) *rhsc)
3241 struct constraint_expr *lhsp, *rhsp;
3242 unsigned i, j;
3244 if (VEC_length (ce_s, lhsc) <= 1
3245 || VEC_length (ce_s, rhsc) <= 1)
3247 for (i = 0; VEC_iterate (ce_s, lhsc, i, lhsp); ++i)
3248 for (j = 0; VEC_iterate (ce_s, rhsc, j, rhsp); ++j)
3249 process_constraint (new_constraint (*lhsp, *rhsp));
3251 else
3253 struct constraint_expr tmp;
3254 tmp = new_scalar_tmp_constraint_exp ("allalltmp");
3255 for (i = 0; VEC_iterate (ce_s, rhsc, i, rhsp); ++i)
3256 process_constraint (new_constraint (tmp, *rhsp));
3257 for (i = 0; VEC_iterate (ce_s, lhsc, i, lhsp); ++i)
3258 process_constraint (new_constraint (*lhsp, tmp));
3262 /* Handle aggregate copies by expanding into copies of the respective
3263 fields of the structures. */
3265 static void
3266 do_structure_copy (tree lhsop, tree rhsop)
3268 struct constraint_expr *lhsp, *rhsp;
3269 VEC (ce_s, heap) *lhsc = NULL, *rhsc = NULL;
3270 unsigned j;
3272 get_constraint_for (lhsop, &lhsc);
3273 get_constraint_for (rhsop, &rhsc);
3274 lhsp = VEC_index (ce_s, lhsc, 0);
3275 rhsp = VEC_index (ce_s, rhsc, 0);
3276 if (lhsp->type == DEREF
3277 || (lhsp->type == ADDRESSOF && lhsp->var == anything_id)
3278 || rhsp->type == DEREF)
3279 process_all_all_constraints (lhsc, rhsc);
3280 else if (lhsp->type == SCALAR
3281 && (rhsp->type == SCALAR
3282 || rhsp->type == ADDRESSOF))
3284 HOST_WIDE_INT lhssize, lhsmaxsize, lhsoffset;
3285 HOST_WIDE_INT rhssize, rhsmaxsize, rhsoffset;
3286 unsigned k = 0;
3287 get_ref_base_and_extent (lhsop, &lhsoffset, &lhssize, &lhsmaxsize);
3288 get_ref_base_and_extent (rhsop, &rhsoffset, &rhssize, &rhsmaxsize);
3289 for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp);)
3291 varinfo_t lhsv, rhsv;
3292 rhsp = VEC_index (ce_s, rhsc, k);
3293 lhsv = get_varinfo (lhsp->var);
3294 rhsv = get_varinfo (rhsp->var);
3295 if (lhsv->may_have_pointers
3296 && ranges_overlap_p (lhsv->offset + rhsoffset, lhsv->size,
3297 rhsv->offset + lhsoffset, rhsv->size))
3298 process_constraint (new_constraint (*lhsp, *rhsp));
3299 if (lhsv->offset + rhsoffset + lhsv->size
3300 > rhsv->offset + lhsoffset + rhsv->size)
3302 ++k;
3303 if (k >= VEC_length (ce_s, rhsc))
3304 break;
3306 else
3307 ++j;
3310 else
3311 gcc_unreachable ();
3313 VEC_free (ce_s, heap, lhsc);
3314 VEC_free (ce_s, heap, rhsc);
3317 /* Create a constraint ID = OP. */
3319 static void
3320 make_constraint_to (unsigned id, tree op)
3322 VEC(ce_s, heap) *rhsc = NULL;
3323 struct constraint_expr *c;
3324 struct constraint_expr includes;
3325 unsigned int j;
3327 includes.var = id;
3328 includes.offset = 0;
3329 includes.type = SCALAR;
3331 get_constraint_for (op, &rhsc);
3332 for (j = 0; VEC_iterate (ce_s, rhsc, j, c); j++)
3333 process_constraint (new_constraint (includes, *c));
3334 VEC_free (ce_s, heap, rhsc);
3337 /* Create a constraint ID = &FROM. */
3339 static void
3340 make_constraint_from (varinfo_t vi, int from)
3342 struct constraint_expr lhs, rhs;
3344 lhs.var = vi->id;
3345 lhs.offset = 0;
3346 lhs.type = SCALAR;
3348 rhs.var = from;
3349 rhs.offset = 0;
3350 rhs.type = ADDRESSOF;
3351 process_constraint (new_constraint (lhs, rhs));
3354 /* Create a constraint ID = FROM. */
3356 static void
3357 make_copy_constraint (varinfo_t vi, int from)
3359 struct constraint_expr lhs, rhs;
3361 lhs.var = vi->id;
3362 lhs.offset = 0;
3363 lhs.type = SCALAR;
3365 rhs.var = from;
3366 rhs.offset = 0;
3367 rhs.type = SCALAR;
3368 process_constraint (new_constraint (lhs, rhs));
3371 /* Make constraints necessary to make OP escape. */
3373 static void
3374 make_escape_constraint (tree op)
3376 make_constraint_to (escaped_id, op);
3379 /* Create a new artificial heap variable with NAME and make a
3380 constraint from it to LHS. Return the created variable. */
3382 static varinfo_t
3383 make_constraint_from_heapvar (varinfo_t lhs, const char *name)
3385 varinfo_t vi;
3386 tree heapvar = heapvar_lookup (lhs->decl, lhs->offset);
3388 if (heapvar == NULL_TREE)
3390 var_ann_t ann;
3391 heapvar = create_tmp_var_raw (ptr_type_node, name);
3392 DECL_EXTERNAL (heapvar) = 1;
3394 heapvar_insert (lhs->decl, lhs->offset, heapvar);
3396 ann = get_var_ann (heapvar);
3397 ann->is_heapvar = 1;
3400 /* For global vars we need to add a heapvar to the list of referenced
3401 vars of a different function than it was created for originally. */
3402 if (gimple_referenced_vars (cfun))
3403 add_referenced_var (heapvar);
3405 vi = new_var_info (heapvar, name);
3406 vi->is_artificial_var = true;
3407 vi->is_heap_var = true;
3408 vi->is_unknown_size_var = true;
3409 vi->offset = 0;
3410 vi->fullsize = ~0;
3411 vi->size = ~0;
3412 vi->is_full_var = true;
3413 insert_vi_for_tree (heapvar, vi);
3415 make_constraint_from (lhs, vi->id);
3417 return vi;
3420 /* Create a new artificial heap variable with NAME and make a
3421 constraint from it to LHS. Set flags according to a tag used
3422 for tracking restrict pointers. */
3424 static void
3425 make_constraint_from_restrict (varinfo_t lhs, const char *name)
3427 varinfo_t vi;
3428 vi = make_constraint_from_heapvar (lhs, name);
3429 vi->is_restrict_var = 1;
3430 vi->is_global_var = 0;
3431 vi->is_special_var = 1;
3432 vi->may_have_pointers = 0;
3435 /* For non-IPA mode, generate constraints necessary for a call on the
3436 RHS. */
3438 static void
3439 handle_rhs_call (gimple stmt, VEC(ce_s, heap) **results)
3441 struct constraint_expr rhsc;
3442 unsigned i;
3444 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3446 tree arg = gimple_call_arg (stmt, i);
3448 /* Find those pointers being passed, and make sure they end up
3449 pointing to anything. */
3450 if (could_have_pointers (arg))
3451 make_escape_constraint (arg);
3454 /* The static chain escapes as well. */
3455 if (gimple_call_chain (stmt))
3456 make_escape_constraint (gimple_call_chain (stmt));
3458 /* And if we applied NRV the address of the return slot escapes as well. */
3459 if (gimple_call_return_slot_opt_p (stmt)
3460 && gimple_call_lhs (stmt) != NULL_TREE
3461 && TREE_ADDRESSABLE (TREE_TYPE (gimple_call_lhs (stmt))))
3463 VEC(ce_s, heap) *tmpc = NULL;
3464 struct constraint_expr lhsc, *c;
3465 get_constraint_for_address_of (gimple_call_lhs (stmt), &tmpc);
3466 lhsc.var = escaped_id;
3467 lhsc.offset = 0;
3468 lhsc.type = SCALAR;
3469 for (i = 0; VEC_iterate (ce_s, tmpc, i, c); ++i)
3470 process_constraint (new_constraint (lhsc, *c));
3471 VEC_free(ce_s, heap, tmpc);
3474 /* Regular functions return nonlocal memory. */
3475 rhsc.var = nonlocal_id;
3476 rhsc.offset = 0;
3477 rhsc.type = SCALAR;
3478 VEC_safe_push (ce_s, heap, *results, &rhsc);
3481 /* For non-IPA mode, generate constraints necessary for a call
3482 that returns a pointer and assigns it to LHS. This simply makes
3483 the LHS point to global and escaped variables. */
3485 static void
3486 handle_lhs_call (tree lhs, int flags, VEC(ce_s, heap) *rhsc, tree fndecl)
3488 VEC(ce_s, heap) *lhsc = NULL;
3490 get_constraint_for (lhs, &lhsc);
3492 if (flags & ECF_MALLOC)
3494 varinfo_t vi;
3495 vi = make_constraint_from_heapvar (get_vi_for_tree (lhs), "HEAP");
3496 /* We delay marking allocated storage global until we know if
3497 it escapes. */
3498 DECL_EXTERNAL (vi->decl) = 0;
3499 vi->is_global_var = 0;
3500 /* If this is not a real malloc call assume the memory was
3501 initialized and thus may point to global memory. All
3502 builtin functions with the malloc attribute behave in a sane way. */
3503 if (!fndecl
3504 || DECL_BUILT_IN_CLASS (fndecl) != BUILT_IN_NORMAL)
3505 make_constraint_from (vi, nonlocal_id);
3507 else if (VEC_length (ce_s, rhsc) > 0)
3509 /* If the store is to a global decl make sure to
3510 add proper escape constraints. */
3511 lhs = get_base_address (lhs);
3512 if (lhs
3513 && DECL_P (lhs)
3514 && is_global_var (lhs))
3516 struct constraint_expr tmpc;
3517 tmpc.var = escaped_id;
3518 tmpc.offset = 0;
3519 tmpc.type = SCALAR;
3520 VEC_safe_push (ce_s, heap, lhsc, &tmpc);
3522 process_all_all_constraints (lhsc, rhsc);
3524 VEC_free (ce_s, heap, lhsc);
3527 /* For non-IPA mode, generate constraints necessary for a call of a
3528 const function that returns a pointer in the statement STMT. */
3530 static void
3531 handle_const_call (gimple stmt, VEC(ce_s, heap) **results)
3533 struct constraint_expr rhsc;
3534 unsigned int k;
3536 /* Treat nested const functions the same as pure functions as far
3537 as the static chain is concerned. */
3538 if (gimple_call_chain (stmt))
3540 make_constraint_to (callused_id, gimple_call_chain (stmt));
3541 rhsc.var = callused_id;
3542 rhsc.offset = 0;
3543 rhsc.type = SCALAR;
3544 VEC_safe_push (ce_s, heap, *results, &rhsc);
3547 /* May return arguments. */
3548 for (k = 0; k < gimple_call_num_args (stmt); ++k)
3550 tree arg = gimple_call_arg (stmt, k);
3552 if (could_have_pointers (arg))
3554 VEC(ce_s, heap) *argc = NULL;
3555 unsigned i;
3556 struct constraint_expr *argp;
3557 get_constraint_for (arg, &argc);
3558 for (i = 0; VEC_iterate (ce_s, argc, i, argp); ++i)
3559 VEC_safe_push (ce_s, heap, *results, argp);
3560 VEC_free(ce_s, heap, argc);
3564 /* May return addresses of globals. */
3565 rhsc.var = nonlocal_id;
3566 rhsc.offset = 0;
3567 rhsc.type = ADDRESSOF;
3568 VEC_safe_push (ce_s, heap, *results, &rhsc);
3571 /* For non-IPA mode, generate constraints necessary for a call to a
3572 pure function in statement STMT. */
3574 static void
3575 handle_pure_call (gimple stmt, VEC(ce_s, heap) **results)
3577 struct constraint_expr rhsc;
3578 unsigned i;
3579 bool need_callused = false;
3581 /* Memory reached from pointer arguments is call-used. */
3582 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3584 tree arg = gimple_call_arg (stmt, i);
3586 if (could_have_pointers (arg))
3588 make_constraint_to (callused_id, arg);
3589 need_callused = true;
3593 /* The static chain is used as well. */
3594 if (gimple_call_chain (stmt))
3596 make_constraint_to (callused_id, gimple_call_chain (stmt));
3597 need_callused = true;
3600 /* Pure functions may return callused and nonlocal memory. */
3601 if (need_callused)
3603 rhsc.var = callused_id;
3604 rhsc.offset = 0;
3605 rhsc.type = SCALAR;
3606 VEC_safe_push (ce_s, heap, *results, &rhsc);
3608 rhsc.var = nonlocal_id;
3609 rhsc.offset = 0;
3610 rhsc.type = SCALAR;
3611 VEC_safe_push (ce_s, heap, *results, &rhsc);
3614 /* Walk statement T setting up aliasing constraints according to the
3615 references found in T. This function is the main part of the
3616 constraint builder. AI points to auxiliary alias information used
3617 when building alias sets and computing alias grouping heuristics. */
3619 static void
3620 find_func_aliases (gimple origt)
3622 gimple t = origt;
3623 VEC(ce_s, heap) *lhsc = NULL;
3624 VEC(ce_s, heap) *rhsc = NULL;
3625 struct constraint_expr *c;
3627 /* Now build constraints expressions. */
3628 if (gimple_code (t) == GIMPLE_PHI)
3630 gcc_assert (!AGGREGATE_TYPE_P (TREE_TYPE (gimple_phi_result (t))));
3632 /* Only care about pointers and structures containing
3633 pointers. */
3634 if (could_have_pointers (gimple_phi_result (t)))
3636 size_t i;
3637 unsigned int j;
3639 /* For a phi node, assign all the arguments to
3640 the result. */
3641 get_constraint_for (gimple_phi_result (t), &lhsc);
3642 for (i = 0; i < gimple_phi_num_args (t); i++)
3644 tree strippedrhs = PHI_ARG_DEF (t, i);
3646 STRIP_NOPS (strippedrhs);
3647 get_constraint_for (gimple_phi_arg_def (t, i), &rhsc);
3649 for (j = 0; VEC_iterate (ce_s, lhsc, j, c); j++)
3651 struct constraint_expr *c2;
3652 while (VEC_length (ce_s, rhsc) > 0)
3654 c2 = VEC_last (ce_s, rhsc);
3655 process_constraint (new_constraint (*c, *c2));
3656 VEC_pop (ce_s, rhsc);
3662 /* In IPA mode, we need to generate constraints to pass call
3663 arguments through their calls. There are two cases,
3664 either a GIMPLE_CALL returning a value, or just a plain
3665 GIMPLE_CALL when we are not.
3667 In non-ipa mode, we need to generate constraints for each
3668 pointer passed by address. */
3669 else if (is_gimple_call (t))
3671 tree fndecl = gimple_call_fndecl (t);
3672 if (fndecl != NULL_TREE
3673 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
3674 /* ??? All builtins that are handled here need to be handled
3675 in the alias-oracle query functions explicitly! */
3676 switch (DECL_FUNCTION_CODE (fndecl))
3678 /* All the following functions return a pointer to the same object
3679 as their first argument points to. The functions do not add
3680 to the ESCAPED solution. The functions make the first argument
3681 pointed to memory point to what the second argument pointed to
3682 memory points to. */
3683 case BUILT_IN_STRCPY:
3684 case BUILT_IN_STRNCPY:
3685 case BUILT_IN_BCOPY:
3686 case BUILT_IN_MEMCPY:
3687 case BUILT_IN_MEMMOVE:
3688 case BUILT_IN_MEMPCPY:
3689 case BUILT_IN_STPCPY:
3690 case BUILT_IN_STPNCPY:
3691 case BUILT_IN_STRCAT:
3692 case BUILT_IN_STRNCAT:
3694 tree res = gimple_call_lhs (t);
3695 tree dest = gimple_call_arg (t, (DECL_FUNCTION_CODE (fndecl)
3696 == BUILT_IN_BCOPY ? 1 : 0));
3697 tree src = gimple_call_arg (t, (DECL_FUNCTION_CODE (fndecl)
3698 == BUILT_IN_BCOPY ? 0 : 1));
3699 if (res != NULL_TREE)
3701 get_constraint_for (res, &lhsc);
3702 if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_MEMPCPY
3703 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPCPY
3704 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPNCPY)
3705 get_constraint_for_ptr_offset (dest, NULL_TREE, &rhsc);
3706 else
3707 get_constraint_for (dest, &rhsc);
3708 process_all_all_constraints (lhsc, rhsc);
3709 VEC_free (ce_s, heap, lhsc);
3710 VEC_free (ce_s, heap, rhsc);
3712 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
3713 get_constraint_for_ptr_offset (src, NULL_TREE, &rhsc);
3714 do_deref (&lhsc);
3715 do_deref (&rhsc);
3716 process_all_all_constraints (lhsc, rhsc);
3717 VEC_free (ce_s, heap, lhsc);
3718 VEC_free (ce_s, heap, rhsc);
3719 return;
3721 case BUILT_IN_MEMSET:
3723 tree res = gimple_call_lhs (t);
3724 tree dest = gimple_call_arg (t, 0);
3725 unsigned i;
3726 ce_s *lhsp;
3727 struct constraint_expr ac;
3728 if (res != NULL_TREE)
3730 get_constraint_for (res, &lhsc);
3731 get_constraint_for (dest, &rhsc);
3732 process_all_all_constraints (lhsc, rhsc);
3733 VEC_free (ce_s, heap, lhsc);
3734 VEC_free (ce_s, heap, rhsc);
3736 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
3737 do_deref (&lhsc);
3738 if (flag_delete_null_pointer_checks
3739 && integer_zerop (gimple_call_arg (t, 1)))
3741 ac.type = ADDRESSOF;
3742 ac.var = nothing_id;
3744 else
3746 ac.type = SCALAR;
3747 ac.var = integer_id;
3749 ac.offset = 0;
3750 for (i = 0; VEC_iterate (ce_s, lhsc, i, lhsp); ++i)
3751 process_constraint (new_constraint (*lhsp, ac));
3752 VEC_free (ce_s, heap, lhsc);
3753 return;
3755 /* All the following functions do not return pointers, do not
3756 modify the points-to sets of memory reachable from their
3757 arguments and do not add to the ESCAPED solution. */
3758 case BUILT_IN_SINCOS:
3759 case BUILT_IN_SINCOSF:
3760 case BUILT_IN_SINCOSL:
3761 case BUILT_IN_FREXP:
3762 case BUILT_IN_FREXPF:
3763 case BUILT_IN_FREXPL:
3764 case BUILT_IN_GAMMA_R:
3765 case BUILT_IN_GAMMAF_R:
3766 case BUILT_IN_GAMMAL_R:
3767 case BUILT_IN_LGAMMA_R:
3768 case BUILT_IN_LGAMMAF_R:
3769 case BUILT_IN_LGAMMAL_R:
3770 case BUILT_IN_MODF:
3771 case BUILT_IN_MODFF:
3772 case BUILT_IN_MODFL:
3773 case BUILT_IN_REMQUO:
3774 case BUILT_IN_REMQUOF:
3775 case BUILT_IN_REMQUOL:
3776 case BUILT_IN_FREE:
3777 return;
3778 /* printf-style functions may have hooks to set pointers to
3779 point to somewhere into the generated string. Leave them
3780 for a later excercise... */
3781 default:
3782 /* Fallthru to general call handling. */;
3784 if (!in_ipa_mode
3785 || (fndecl
3786 && !lookup_vi_for_tree (fndecl)))
3788 VEC(ce_s, heap) *rhsc = NULL;
3789 int flags = gimple_call_flags (t);
3791 /* Const functions can return their arguments and addresses
3792 of global memory but not of escaped memory. */
3793 if (flags & (ECF_CONST|ECF_NOVOPS))
3795 if (gimple_call_lhs (t)
3796 && could_have_pointers (gimple_call_lhs (t)))
3797 handle_const_call (t, &rhsc);
3799 /* Pure functions can return addresses in and of memory
3800 reachable from their arguments, but they are not an escape
3801 point for reachable memory of their arguments. */
3802 else if (flags & (ECF_PURE|ECF_LOOPING_CONST_OR_PURE))
3803 handle_pure_call (t, &rhsc);
3804 else
3805 handle_rhs_call (t, &rhsc);
3806 if (gimple_call_lhs (t)
3807 && could_have_pointers (gimple_call_lhs (t)))
3808 handle_lhs_call (gimple_call_lhs (t), flags, rhsc, fndecl);
3809 VEC_free (ce_s, heap, rhsc);
3811 else
3813 tree lhsop;
3814 varinfo_t fi;
3815 int i = 1;
3816 size_t j;
3817 tree decl;
3819 lhsop = gimple_call_lhs (t);
3820 decl = gimple_call_fndecl (t);
3822 /* If we can directly resolve the function being called, do so.
3823 Otherwise, it must be some sort of indirect expression that
3824 we should still be able to handle. */
3825 if (decl)
3826 fi = get_vi_for_tree (decl);
3827 else
3829 decl = gimple_call_fn (t);
3830 fi = get_vi_for_tree (decl);
3833 /* Assign all the passed arguments to the appropriate incoming
3834 parameters of the function. */
3835 for (j = 0; j < gimple_call_num_args (t); j++)
3837 struct constraint_expr lhs ;
3838 struct constraint_expr *rhsp;
3839 tree arg = gimple_call_arg (t, j);
3841 get_constraint_for (arg, &rhsc);
3842 if (TREE_CODE (decl) != FUNCTION_DECL)
3844 lhs.type = DEREF;
3845 lhs.var = fi->id;
3846 lhs.offset = i;
3848 else
3850 lhs.type = SCALAR;
3851 lhs.var = first_vi_for_offset (fi, i)->id;
3852 lhs.offset = 0;
3854 while (VEC_length (ce_s, rhsc) != 0)
3856 rhsp = VEC_last (ce_s, rhsc);
3857 process_constraint (new_constraint (lhs, *rhsp));
3858 VEC_pop (ce_s, rhsc);
3860 i++;
3863 /* If we are returning a value, assign it to the result. */
3864 if (lhsop)
3866 struct constraint_expr rhs;
3867 struct constraint_expr *lhsp;
3868 unsigned int j = 0;
3870 get_constraint_for (lhsop, &lhsc);
3871 if (TREE_CODE (decl) != FUNCTION_DECL)
3873 rhs.type = DEREF;
3874 rhs.var = fi->id;
3875 rhs.offset = i;
3877 else
3879 rhs.type = SCALAR;
3880 rhs.var = first_vi_for_offset (fi, i)->id;
3881 rhs.offset = 0;
3883 for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp); j++)
3884 process_constraint (new_constraint (*lhsp, rhs));
3888 /* Otherwise, just a regular assignment statement. Only care about
3889 operations with pointer result, others are dealt with as escape
3890 points if they have pointer operands. */
3891 else if (is_gimple_assign (t)
3892 && could_have_pointers (gimple_assign_lhs (t)))
3894 /* Otherwise, just a regular assignment statement. */
3895 tree lhsop = gimple_assign_lhs (t);
3896 tree rhsop = (gimple_num_ops (t) == 2) ? gimple_assign_rhs1 (t) : NULL;
3898 if (rhsop && AGGREGATE_TYPE_P (TREE_TYPE (lhsop)))
3899 do_structure_copy (lhsop, rhsop);
3900 else
3902 struct constraint_expr temp;
3903 get_constraint_for (lhsop, &lhsc);
3905 if (gimple_assign_rhs_code (t) == POINTER_PLUS_EXPR)
3906 get_constraint_for_ptr_offset (gimple_assign_rhs1 (t),
3907 gimple_assign_rhs2 (t), &rhsc);
3908 else if ((CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (t))
3909 && !(POINTER_TYPE_P (gimple_expr_type (t))
3910 && !POINTER_TYPE_P (TREE_TYPE (rhsop))))
3911 || gimple_assign_single_p (t))
3912 get_constraint_for (rhsop, &rhsc);
3913 else
3915 temp.type = ADDRESSOF;
3916 temp.var = anything_id;
3917 temp.offset = 0;
3918 VEC_safe_push (ce_s, heap, rhsc, &temp);
3920 process_all_all_constraints (lhsc, rhsc);
3922 /* If there is a store to a global variable the rhs escapes. */
3923 if ((lhsop = get_base_address (lhsop)) != NULL_TREE
3924 && DECL_P (lhsop)
3925 && is_global_var (lhsop))
3926 make_escape_constraint (rhsop);
3927 /* If this is a conversion of a non-restrict pointer to a
3928 restrict pointer track it with a new heapvar. */
3929 else if (gimple_assign_cast_p (t)
3930 && POINTER_TYPE_P (TREE_TYPE (rhsop))
3931 && POINTER_TYPE_P (TREE_TYPE (lhsop))
3932 && !TYPE_RESTRICT (TREE_TYPE (rhsop))
3933 && TYPE_RESTRICT (TREE_TYPE (lhsop)))
3934 make_constraint_from_restrict (get_vi_for_tree (lhsop),
3935 "CAST_RESTRICT");
3937 /* For conversions of pointers to non-pointers the pointer escapes. */
3938 else if (gimple_assign_cast_p (t)
3939 && POINTER_TYPE_P (TREE_TYPE (gimple_assign_rhs1 (t)))
3940 && !POINTER_TYPE_P (TREE_TYPE (gimple_assign_lhs (t))))
3942 make_escape_constraint (gimple_assign_rhs1 (t));
3944 /* Handle escapes through return. */
3945 else if (gimple_code (t) == GIMPLE_RETURN
3946 && gimple_return_retval (t) != NULL_TREE
3947 && could_have_pointers (gimple_return_retval (t)))
3949 make_escape_constraint (gimple_return_retval (t));
3951 /* Handle asms conservatively by adding escape constraints to everything. */
3952 else if (gimple_code (t) == GIMPLE_ASM)
3954 unsigned i, noutputs;
3955 const char **oconstraints;
3956 const char *constraint;
3957 bool allows_mem, allows_reg, is_inout;
3959 noutputs = gimple_asm_noutputs (t);
3960 oconstraints = XALLOCAVEC (const char *, noutputs);
3962 for (i = 0; i < noutputs; ++i)
3964 tree link = gimple_asm_output_op (t, i);
3965 tree op = TREE_VALUE (link);
3967 constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
3968 oconstraints[i] = constraint;
3969 parse_output_constraint (&constraint, i, 0, 0, &allows_mem,
3970 &allows_reg, &is_inout);
3972 /* A memory constraint makes the address of the operand escape. */
3973 if (!allows_reg && allows_mem)
3974 make_escape_constraint (build_fold_addr_expr (op));
3976 /* The asm may read global memory, so outputs may point to
3977 any global memory. */
3978 if (op && could_have_pointers (op))
3980 VEC(ce_s, heap) *lhsc = NULL;
3981 struct constraint_expr rhsc, *lhsp;
3982 unsigned j;
3983 get_constraint_for (op, &lhsc);
3984 rhsc.var = nonlocal_id;
3985 rhsc.offset = 0;
3986 rhsc.type = SCALAR;
3987 for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp); j++)
3988 process_constraint (new_constraint (*lhsp, rhsc));
3989 VEC_free (ce_s, heap, lhsc);
3992 for (i = 0; i < gimple_asm_ninputs (t); ++i)
3994 tree link = gimple_asm_input_op (t, i);
3995 tree op = TREE_VALUE (link);
3997 constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
3999 parse_input_constraint (&constraint, 0, 0, noutputs, 0, oconstraints,
4000 &allows_mem, &allows_reg);
4002 /* A memory constraint makes the address of the operand escape. */
4003 if (!allows_reg && allows_mem)
4004 make_escape_constraint (build_fold_addr_expr (op));
4005 /* Strictly we'd only need the constraint to ESCAPED if
4006 the asm clobbers memory, otherwise using CALLUSED
4007 would be enough. */
4008 else if (op && could_have_pointers (op))
4009 make_escape_constraint (op);
4013 VEC_free (ce_s, heap, rhsc);
4014 VEC_free (ce_s, heap, lhsc);
4018 /* Find the first varinfo in the same variable as START that overlaps with
4019 OFFSET. Return NULL if we can't find one. */
4021 static varinfo_t
4022 first_vi_for_offset (varinfo_t start, unsigned HOST_WIDE_INT offset)
4024 /* If the offset is outside of the variable, bail out. */
4025 if (offset >= start->fullsize)
4026 return NULL;
4028 /* If we cannot reach offset from start, lookup the first field
4029 and start from there. */
4030 if (start->offset > offset)
4031 start = lookup_vi_for_tree (start->decl);
4033 while (start)
4035 /* We may not find a variable in the field list with the actual
4036 offset when when we have glommed a structure to a variable.
4037 In that case, however, offset should still be within the size
4038 of the variable. */
4039 if (offset >= start->offset
4040 && (offset - start->offset) < start->size)
4041 return start;
4043 start= start->next;
4046 return NULL;
4049 /* Find the first varinfo in the same variable as START that overlaps with
4050 OFFSET. If there is no such varinfo the varinfo directly preceding
4051 OFFSET is returned. */
4053 static varinfo_t
4054 first_or_preceding_vi_for_offset (varinfo_t start,
4055 unsigned HOST_WIDE_INT offset)
4057 /* If we cannot reach offset from start, lookup the first field
4058 and start from there. */
4059 if (start->offset > offset)
4060 start = lookup_vi_for_tree (start->decl);
4062 /* We may not find a variable in the field list with the actual
4063 offset when when we have glommed a structure to a variable.
4064 In that case, however, offset should still be within the size
4065 of the variable.
4066 If we got beyond the offset we look for return the field
4067 directly preceding offset which may be the last field. */
4068 while (start->next
4069 && offset >= start->offset
4070 && !((offset - start->offset) < start->size))
4071 start = start->next;
4073 return start;
4077 /* Insert the varinfo FIELD into the field list for BASE, at the front
4078 of the list. */
4080 static void
4081 insert_into_field_list (varinfo_t base, varinfo_t field)
4083 varinfo_t prev = base;
4084 varinfo_t curr = base->next;
4086 field->next = curr;
4087 prev->next = field;
4090 /* Insert the varinfo FIELD into the field list for BASE, ordered by
4091 offset. */
4093 static void
4094 insert_into_field_list_sorted (varinfo_t base, varinfo_t field)
4096 varinfo_t prev = base;
4097 varinfo_t curr = base->next;
4099 if (curr == NULL)
4101 prev->next = field;
4102 field->next = NULL;
4104 else
4106 while (curr)
4108 if (field->offset <= curr->offset)
4109 break;
4110 prev = curr;
4111 curr = curr->next;
4113 field->next = prev->next;
4114 prev->next = field;
4118 /* This structure is used during pushing fields onto the fieldstack
4119 to track the offset of the field, since bitpos_of_field gives it
4120 relative to its immediate containing type, and we want it relative
4121 to the ultimate containing object. */
4123 struct fieldoff
4125 /* Offset from the base of the base containing object to this field. */
4126 HOST_WIDE_INT offset;
4128 /* Size, in bits, of the field. */
4129 unsigned HOST_WIDE_INT size;
4131 unsigned has_unknown_size : 1;
4133 unsigned may_have_pointers : 1;
4135 unsigned only_restrict_pointers : 1;
4137 typedef struct fieldoff fieldoff_s;
4139 DEF_VEC_O(fieldoff_s);
4140 DEF_VEC_ALLOC_O(fieldoff_s,heap);
4142 /* qsort comparison function for two fieldoff's PA and PB */
4144 static int
4145 fieldoff_compare (const void *pa, const void *pb)
4147 const fieldoff_s *foa = (const fieldoff_s *)pa;
4148 const fieldoff_s *fob = (const fieldoff_s *)pb;
4149 unsigned HOST_WIDE_INT foasize, fobsize;
4151 if (foa->offset < fob->offset)
4152 return -1;
4153 else if (foa->offset > fob->offset)
4154 return 1;
4156 foasize = foa->size;
4157 fobsize = fob->size;
4158 if (foasize < fobsize)
4159 return -1;
4160 else if (foasize > fobsize)
4161 return 1;
4162 return 0;
4165 /* Sort a fieldstack according to the field offset and sizes. */
4166 static void
4167 sort_fieldstack (VEC(fieldoff_s,heap) *fieldstack)
4169 qsort (VEC_address (fieldoff_s, fieldstack),
4170 VEC_length (fieldoff_s, fieldstack),
4171 sizeof (fieldoff_s),
4172 fieldoff_compare);
4175 /* Return true if V is a tree that we can have subvars for.
4176 Normally, this is any aggregate type. Also complex
4177 types which are not gimple registers can have subvars. */
4179 static inline bool
4180 var_can_have_subvars (const_tree v)
4182 /* Volatile variables should never have subvars. */
4183 if (TREE_THIS_VOLATILE (v))
4184 return false;
4186 /* Non decls or memory tags can never have subvars. */
4187 if (!DECL_P (v))
4188 return false;
4190 /* Aggregates without overlapping fields can have subvars. */
4191 if (TREE_CODE (TREE_TYPE (v)) == RECORD_TYPE)
4192 return true;
4194 return false;
4197 /* Given a TYPE, and a vector of field offsets FIELDSTACK, push all
4198 the fields of TYPE onto fieldstack, recording their offsets along
4199 the way.
4201 OFFSET is used to keep track of the offset in this entire
4202 structure, rather than just the immediately containing structure.
4203 Returns the number of fields pushed. */
4205 static int
4206 push_fields_onto_fieldstack (tree type, VEC(fieldoff_s,heap) **fieldstack,
4207 HOST_WIDE_INT offset)
4209 tree field;
4210 int count = 0;
4212 if (TREE_CODE (type) != RECORD_TYPE)
4213 return 0;
4215 /* If the vector of fields is growing too big, bail out early.
4216 Callers check for VEC_length <= MAX_FIELDS_FOR_FIELD_SENSITIVE, make
4217 sure this fails. */
4218 if (VEC_length (fieldoff_s, *fieldstack) > MAX_FIELDS_FOR_FIELD_SENSITIVE)
4219 return 0;
4221 for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
4222 if (TREE_CODE (field) == FIELD_DECL)
4224 bool push = false;
4225 int pushed = 0;
4226 HOST_WIDE_INT foff = bitpos_of_field (field);
4228 if (!var_can_have_subvars (field)
4229 || TREE_CODE (TREE_TYPE (field)) == QUAL_UNION_TYPE
4230 || TREE_CODE (TREE_TYPE (field)) == UNION_TYPE)
4231 push = true;
4232 else if (!(pushed = push_fields_onto_fieldstack
4233 (TREE_TYPE (field), fieldstack, offset + foff))
4234 && (DECL_SIZE (field)
4235 && !integer_zerop (DECL_SIZE (field))))
4236 /* Empty structures may have actual size, like in C++. So
4237 see if we didn't push any subfields and the size is
4238 nonzero, push the field onto the stack. */
4239 push = true;
4241 if (push)
4243 fieldoff_s *pair = NULL;
4244 bool has_unknown_size = false;
4246 if (!VEC_empty (fieldoff_s, *fieldstack))
4247 pair = VEC_last (fieldoff_s, *fieldstack);
4249 if (!DECL_SIZE (field)
4250 || !host_integerp (DECL_SIZE (field), 1))
4251 has_unknown_size = true;
4253 /* If adjacent fields do not contain pointers merge them. */
4254 if (pair
4255 && !pair->may_have_pointers
4256 && !could_have_pointers (field)
4257 && !pair->has_unknown_size
4258 && !has_unknown_size
4259 && pair->offset + (HOST_WIDE_INT)pair->size == offset + foff)
4261 pair = VEC_last (fieldoff_s, *fieldstack);
4262 pair->size += TREE_INT_CST_LOW (DECL_SIZE (field));
4264 else
4266 pair = VEC_safe_push (fieldoff_s, heap, *fieldstack, NULL);
4267 pair->offset = offset + foff;
4268 pair->has_unknown_size = has_unknown_size;
4269 if (!has_unknown_size)
4270 pair->size = TREE_INT_CST_LOW (DECL_SIZE (field));
4271 else
4272 pair->size = -1;
4273 pair->may_have_pointers = could_have_pointers (field);
4274 pair->only_restrict_pointers
4275 = (!has_unknown_size
4276 && POINTER_TYPE_P (TREE_TYPE (field))
4277 && TYPE_RESTRICT (TREE_TYPE (field)));
4278 count++;
4281 else
4282 count += pushed;
4285 return count;
4288 /* Count the number of arguments DECL has, and set IS_VARARGS to true
4289 if it is a varargs function. */
4291 static unsigned int
4292 count_num_arguments (tree decl, bool *is_varargs)
4294 unsigned int num = 0;
4295 tree t;
4297 /* Capture named arguments for K&R functions. They do not
4298 have a prototype and thus no TYPE_ARG_TYPES. */
4299 for (t = DECL_ARGUMENTS (decl); t; t = TREE_CHAIN (t))
4300 ++num;
4302 /* Check if the function has variadic arguments. */
4303 for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
4304 if (TREE_VALUE (t) == void_type_node)
4305 break;
4306 if (!t)
4307 *is_varargs = true;
4309 return num;
4312 /* Creation function node for DECL, using NAME, and return the index
4313 of the variable we've created for the function. */
4315 static unsigned int
4316 create_function_info_for (tree decl, const char *name)
4318 varinfo_t vi;
4319 tree arg;
4320 unsigned int i;
4321 bool is_varargs = false;
4323 /* Create the variable info. */
4325 vi = new_var_info (decl, name);
4326 vi->offset = 0;
4327 vi->size = 1;
4328 vi->fullsize = count_num_arguments (decl, &is_varargs) + 1;
4329 insert_vi_for_tree (vi->decl, vi);
4331 stats.total_vars++;
4333 /* If it's varargs, we don't know how many arguments it has, so we
4334 can't do much. */
4335 if (is_varargs)
4337 vi->fullsize = ~0;
4338 vi->size = ~0;
4339 vi->is_unknown_size_var = true;
4340 return vi->id;
4343 arg = DECL_ARGUMENTS (decl);
4345 /* Set up variables for each argument. */
4346 for (i = 1; i < vi->fullsize; i++)
4348 varinfo_t argvi;
4349 const char *newname;
4350 char *tempname;
4351 tree argdecl = decl;
4353 if (arg)
4354 argdecl = arg;
4356 asprintf (&tempname, "%s.arg%d", name, i-1);
4357 newname = ggc_strdup (tempname);
4358 free (tempname);
4360 argvi = new_var_info (argdecl, newname);
4361 argvi->offset = i;
4362 argvi->size = 1;
4363 argvi->is_full_var = true;
4364 argvi->fullsize = vi->fullsize;
4365 insert_into_field_list_sorted (vi, argvi);
4366 stats.total_vars ++;
4367 if (arg)
4369 insert_vi_for_tree (arg, argvi);
4370 arg = TREE_CHAIN (arg);
4374 /* Create a variable for the return var. */
4375 if (DECL_RESULT (decl) != NULL
4376 || !VOID_TYPE_P (TREE_TYPE (TREE_TYPE (decl))))
4378 varinfo_t resultvi;
4379 const char *newname;
4380 char *tempname;
4381 tree resultdecl = decl;
4383 vi->fullsize ++;
4385 if (DECL_RESULT (decl))
4386 resultdecl = DECL_RESULT (decl);
4388 asprintf (&tempname, "%s.result", name);
4389 newname = ggc_strdup (tempname);
4390 free (tempname);
4392 resultvi = new_var_info (resultdecl, newname);
4393 resultvi->offset = i;
4394 resultvi->size = 1;
4395 resultvi->fullsize = vi->fullsize;
4396 resultvi->is_full_var = true;
4397 insert_into_field_list_sorted (vi, resultvi);
4398 stats.total_vars ++;
4399 if (DECL_RESULT (decl))
4400 insert_vi_for_tree (DECL_RESULT (decl), resultvi);
4403 return vi->id;
4407 /* Return true if FIELDSTACK contains fields that overlap.
4408 FIELDSTACK is assumed to be sorted by offset. */
4410 static bool
4411 check_for_overlaps (VEC (fieldoff_s,heap) *fieldstack)
4413 fieldoff_s *fo = NULL;
4414 unsigned int i;
4415 HOST_WIDE_INT lastoffset = -1;
4417 for (i = 0; VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
4419 if (fo->offset == lastoffset)
4420 return true;
4421 lastoffset = fo->offset;
4423 return false;
4426 /* Create a varinfo structure for NAME and DECL, and add it to VARMAP.
4427 This will also create any varinfo structures necessary for fields
4428 of DECL. */
4430 static unsigned int
4431 create_variable_info_for (tree decl, const char *name)
4433 varinfo_t vi;
4434 tree decl_type = TREE_TYPE (decl);
4435 tree declsize = DECL_P (decl) ? DECL_SIZE (decl) : TYPE_SIZE (decl_type);
4436 VEC (fieldoff_s,heap) *fieldstack = NULL;
4438 if (var_can_have_subvars (decl) && use_field_sensitive)
4439 push_fields_onto_fieldstack (decl_type, &fieldstack, 0);
4441 /* If the variable doesn't have subvars, we may end up needing to
4442 sort the field list and create fake variables for all the
4443 fields. */
4444 vi = new_var_info (decl, name);
4445 vi->offset = 0;
4446 vi->may_have_pointers = could_have_pointers (decl);
4447 if (!declsize
4448 || !host_integerp (declsize, 1))
4450 vi->is_unknown_size_var = true;
4451 vi->fullsize = ~0;
4452 vi->size = ~0;
4454 else
4456 vi->fullsize = TREE_INT_CST_LOW (declsize);
4457 vi->size = vi->fullsize;
4460 insert_vi_for_tree (vi->decl, vi);
4461 if (vi->is_global_var
4462 && (!flag_whole_program || !in_ipa_mode)
4463 && vi->may_have_pointers)
4465 if (POINTER_TYPE_P (TREE_TYPE (decl))
4466 && TYPE_RESTRICT (TREE_TYPE (decl)))
4467 make_constraint_from_restrict (vi, "GLOBAL_RESTRICT");
4468 make_copy_constraint (vi, nonlocal_id);
4471 stats.total_vars++;
4472 if (use_field_sensitive
4473 && !vi->is_unknown_size_var
4474 && var_can_have_subvars (decl)
4475 && VEC_length (fieldoff_s, fieldstack) > 1
4476 && VEC_length (fieldoff_s, fieldstack) <= MAX_FIELDS_FOR_FIELD_SENSITIVE)
4478 fieldoff_s *fo = NULL;
4479 bool notokay = false;
4480 unsigned int i;
4482 for (i = 0; !notokay && VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
4484 if (fo->has_unknown_size
4485 || fo->offset < 0)
4487 notokay = true;
4488 break;
4492 /* We can't sort them if we have a field with a variable sized type,
4493 which will make notokay = true. In that case, we are going to return
4494 without creating varinfos for the fields anyway, so sorting them is a
4495 waste to boot. */
4496 if (!notokay)
4498 sort_fieldstack (fieldstack);
4499 /* Due to some C++ FE issues, like PR 22488, we might end up
4500 what appear to be overlapping fields even though they,
4501 in reality, do not overlap. Until the C++ FE is fixed,
4502 we will simply disable field-sensitivity for these cases. */
4503 notokay = check_for_overlaps (fieldstack);
4507 if (VEC_length (fieldoff_s, fieldstack) != 0)
4508 fo = VEC_index (fieldoff_s, fieldstack, 0);
4510 if (fo == NULL || notokay)
4512 vi->is_unknown_size_var = 1;
4513 vi->fullsize = ~0;
4514 vi->size = ~0;
4515 vi->is_full_var = true;
4516 VEC_free (fieldoff_s, heap, fieldstack);
4517 return vi->id;
4520 vi->size = fo->size;
4521 vi->offset = fo->offset;
4522 vi->may_have_pointers = fo->may_have_pointers;
4523 if (vi->is_global_var
4524 && (!flag_whole_program || !in_ipa_mode)
4525 && vi->may_have_pointers)
4527 if (fo->only_restrict_pointers)
4528 make_constraint_from_restrict (vi, "GLOBAL_RESTRICT");
4530 for (i = VEC_length (fieldoff_s, fieldstack) - 1;
4531 i >= 1 && VEC_iterate (fieldoff_s, fieldstack, i, fo);
4532 i--)
4534 varinfo_t newvi;
4535 const char *newname = "NULL";
4536 char *tempname;
4538 if (dump_file)
4540 asprintf (&tempname, "%s." HOST_WIDE_INT_PRINT_DEC
4541 "+" HOST_WIDE_INT_PRINT_DEC,
4542 vi->name, fo->offset, fo->size);
4543 newname = ggc_strdup (tempname);
4544 free (tempname);
4546 newvi = new_var_info (decl, newname);
4547 newvi->offset = fo->offset;
4548 newvi->size = fo->size;
4549 newvi->fullsize = vi->fullsize;
4550 newvi->may_have_pointers = fo->may_have_pointers;
4551 insert_into_field_list (vi, newvi);
4552 if ((newvi->is_global_var || TREE_CODE (decl) == PARM_DECL)
4553 && newvi->may_have_pointers)
4555 if (fo->only_restrict_pointers)
4556 make_constraint_from_restrict (newvi, "GLOBAL_RESTRICT");
4557 if (newvi->is_global_var && !in_ipa_mode)
4558 make_copy_constraint (newvi, nonlocal_id);
4561 stats.total_vars++;
4564 else
4565 vi->is_full_var = true;
4567 VEC_free (fieldoff_s, heap, fieldstack);
4569 return vi->id;
4572 /* Print out the points-to solution for VAR to FILE. */
4574 static void
4575 dump_solution_for_var (FILE *file, unsigned int var)
4577 varinfo_t vi = get_varinfo (var);
4578 unsigned int i;
4579 bitmap_iterator bi;
4581 if (find (var) != var)
4583 varinfo_t vipt = get_varinfo (find (var));
4584 fprintf (file, "%s = same as %s\n", vi->name, vipt->name);
4586 else
4588 fprintf (file, "%s = { ", vi->name);
4589 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
4591 fprintf (file, "%s ", get_varinfo (i)->name);
4593 fprintf (file, "}\n");
4597 /* Print the points-to solution for VAR to stdout. */
4599 void
4600 debug_solution_for_var (unsigned int var)
4602 dump_solution_for_var (stdout, var);
4605 /* Create varinfo structures for all of the variables in the
4606 function for intraprocedural mode. */
4608 static void
4609 intra_create_variable_infos (void)
4611 tree t;
4613 /* For each incoming pointer argument arg, create the constraint ARG
4614 = NONLOCAL or a dummy variable if flag_argument_noalias is set. */
4615 for (t = DECL_ARGUMENTS (current_function_decl); t; t = TREE_CHAIN (t))
4617 varinfo_t p;
4619 if (!could_have_pointers (t))
4620 continue;
4622 /* For restrict qualified pointers to objects passed by
4623 reference build a real representative for the pointed-to object. */
4624 if (DECL_BY_REFERENCE (t)
4625 && POINTER_TYPE_P (TREE_TYPE (t))
4626 && TYPE_RESTRICT (TREE_TYPE (t)))
4628 struct constraint_expr lhsc, rhsc;
4629 varinfo_t vi;
4630 tree heapvar = heapvar_lookup (t, 0);
4631 if (heapvar == NULL_TREE)
4633 var_ann_t ann;
4634 heapvar = create_tmp_var_raw (TREE_TYPE (TREE_TYPE (t)),
4635 "PARM_NOALIAS");
4636 DECL_EXTERNAL (heapvar) = 1;
4637 heapvar_insert (t, 0, heapvar);
4638 ann = get_var_ann (heapvar);
4639 ann->is_heapvar = 1;
4641 if (gimple_referenced_vars (cfun))
4642 add_referenced_var (heapvar);
4643 lhsc.var = get_vi_for_tree (t)->id;
4644 lhsc.type = SCALAR;
4645 lhsc.offset = 0;
4646 rhsc.var = (vi = get_vi_for_tree (heapvar))->id;
4647 rhsc.type = ADDRESSOF;
4648 rhsc.offset = 0;
4649 process_constraint (new_constraint (lhsc, rhsc));
4650 vi->is_restrict_var = 1;
4651 continue;
4654 for (p = get_vi_for_tree (t); p; p = p->next)
4655 if (p->may_have_pointers)
4656 make_constraint_from (p, nonlocal_id);
4657 if (POINTER_TYPE_P (TREE_TYPE (t))
4658 && TYPE_RESTRICT (TREE_TYPE (t)))
4659 make_constraint_from_restrict (get_vi_for_tree (t), "PARM_RESTRICT");
4662 /* Add a constraint for a result decl that is passed by reference. */
4663 if (DECL_RESULT (cfun->decl)
4664 && DECL_BY_REFERENCE (DECL_RESULT (cfun->decl)))
4666 varinfo_t p, result_vi = get_vi_for_tree (DECL_RESULT (cfun->decl));
4668 for (p = result_vi; p; p = p->next)
4669 make_constraint_from (p, nonlocal_id);
4672 /* Add a constraint for the incoming static chain parameter. */
4673 if (cfun->static_chain_decl != NULL_TREE)
4675 varinfo_t p, chain_vi = get_vi_for_tree (cfun->static_chain_decl);
4677 for (p = chain_vi; p; p = p->next)
4678 make_constraint_from (p, nonlocal_id);
4682 /* Structure used to put solution bitmaps in a hashtable so they can
4683 be shared among variables with the same points-to set. */
4685 typedef struct shared_bitmap_info
4687 bitmap pt_vars;
4688 hashval_t hashcode;
4689 } *shared_bitmap_info_t;
4690 typedef const struct shared_bitmap_info *const_shared_bitmap_info_t;
4692 static htab_t shared_bitmap_table;
4694 /* Hash function for a shared_bitmap_info_t */
4696 static hashval_t
4697 shared_bitmap_hash (const void *p)
4699 const_shared_bitmap_info_t const bi = (const_shared_bitmap_info_t) p;
4700 return bi->hashcode;
4703 /* Equality function for two shared_bitmap_info_t's. */
4705 static int
4706 shared_bitmap_eq (const void *p1, const void *p2)
4708 const_shared_bitmap_info_t const sbi1 = (const_shared_bitmap_info_t) p1;
4709 const_shared_bitmap_info_t const sbi2 = (const_shared_bitmap_info_t) p2;
4710 return bitmap_equal_p (sbi1->pt_vars, sbi2->pt_vars);
4713 /* Lookup a bitmap in the shared bitmap hashtable, and return an already
4714 existing instance if there is one, NULL otherwise. */
4716 static bitmap
4717 shared_bitmap_lookup (bitmap pt_vars)
4719 void **slot;
4720 struct shared_bitmap_info sbi;
4722 sbi.pt_vars = pt_vars;
4723 sbi.hashcode = bitmap_hash (pt_vars);
4725 slot = htab_find_slot_with_hash (shared_bitmap_table, &sbi,
4726 sbi.hashcode, NO_INSERT);
4727 if (!slot)
4728 return NULL;
4729 else
4730 return ((shared_bitmap_info_t) *slot)->pt_vars;
4734 /* Add a bitmap to the shared bitmap hashtable. */
4736 static void
4737 shared_bitmap_add (bitmap pt_vars)
4739 void **slot;
4740 shared_bitmap_info_t sbi = XNEW (struct shared_bitmap_info);
4742 sbi->pt_vars = pt_vars;
4743 sbi->hashcode = bitmap_hash (pt_vars);
4745 slot = htab_find_slot_with_hash (shared_bitmap_table, sbi,
4746 sbi->hashcode, INSERT);
4747 gcc_assert (!*slot);
4748 *slot = (void *) sbi;
4752 /* Set bits in INTO corresponding to the variable uids in solution set FROM. */
4754 static void
4755 set_uids_in_ptset (bitmap into, bitmap from, struct pt_solution *pt)
4757 unsigned int i;
4758 bitmap_iterator bi;
4760 EXECUTE_IF_SET_IN_BITMAP (from, 0, i, bi)
4762 varinfo_t vi = get_varinfo (i);
4764 /* The only artificial variables that are allowed in a may-alias
4765 set are heap variables. */
4766 if (vi->is_artificial_var && !vi->is_heap_var)
4767 continue;
4769 if (TREE_CODE (vi->decl) == VAR_DECL
4770 || TREE_CODE (vi->decl) == PARM_DECL
4771 || TREE_CODE (vi->decl) == RESULT_DECL)
4773 /* Add the decl to the points-to set. Note that the points-to
4774 set contains global variables. */
4775 bitmap_set_bit (into, DECL_UID (vi->decl));
4776 if (vi->is_global_var)
4777 pt->vars_contains_global = true;
4783 /* Compute the points-to solution *PT for the variable VI. */
4785 static void
4786 find_what_var_points_to (varinfo_t orig_vi, struct pt_solution *pt)
4788 unsigned int i;
4789 bitmap_iterator bi;
4790 bitmap finished_solution;
4791 bitmap result;
4792 varinfo_t vi;
4794 memset (pt, 0, sizeof (struct pt_solution));
4796 /* This variable may have been collapsed, let's get the real
4797 variable. */
4798 vi = get_varinfo (find (orig_vi->id));
4800 /* Translate artificial variables into SSA_NAME_PTR_INFO
4801 attributes. */
4802 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
4804 varinfo_t vi = get_varinfo (i);
4806 if (vi->is_artificial_var)
4808 if (vi->id == nothing_id)
4809 pt->null = 1;
4810 else if (vi->id == escaped_id)
4811 pt->escaped = 1;
4812 else if (vi->id == callused_id)
4813 gcc_unreachable ();
4814 else if (vi->id == nonlocal_id)
4815 pt->nonlocal = 1;
4816 else if (vi->is_heap_var)
4817 /* We represent heapvars in the points-to set properly. */
4819 else if (vi->id == readonly_id)
4820 /* Nobody cares. */
4822 else if (vi->id == anything_id
4823 || vi->id == integer_id)
4824 pt->anything = 1;
4826 if (vi->is_restrict_var)
4827 pt->vars_contains_restrict = true;
4830 /* Instead of doing extra work, simply do not create
4831 elaborate points-to information for pt_anything pointers. */
4832 if (pt->anything
4833 && (orig_vi->is_artificial_var
4834 || !pt->vars_contains_restrict))
4835 return;
4837 /* Share the final set of variables when possible. */
4838 finished_solution = BITMAP_GGC_ALLOC ();
4839 stats.points_to_sets_created++;
4841 set_uids_in_ptset (finished_solution, vi->solution, pt);
4842 result = shared_bitmap_lookup (finished_solution);
4843 if (!result)
4845 shared_bitmap_add (finished_solution);
4846 pt->vars = finished_solution;
4848 else
4850 pt->vars = result;
4851 bitmap_clear (finished_solution);
4855 /* Given a pointer variable P, fill in its points-to set. */
4857 static void
4858 find_what_p_points_to (tree p)
4860 struct ptr_info_def *pi;
4861 tree lookup_p = p;
4862 varinfo_t vi;
4864 /* For parameters, get at the points-to set for the actual parm
4865 decl. */
4866 if (TREE_CODE (p) == SSA_NAME
4867 && TREE_CODE (SSA_NAME_VAR (p)) == PARM_DECL
4868 && SSA_NAME_IS_DEFAULT_DEF (p))
4869 lookup_p = SSA_NAME_VAR (p);
4871 vi = lookup_vi_for_tree (lookup_p);
4872 if (!vi)
4873 return;
4875 pi = get_ptr_info (p);
4876 find_what_var_points_to (vi, &pi->pt);
4880 /* Query statistics for points-to solutions. */
4882 static struct {
4883 unsigned HOST_WIDE_INT pt_solution_includes_may_alias;
4884 unsigned HOST_WIDE_INT pt_solution_includes_no_alias;
4885 unsigned HOST_WIDE_INT pt_solutions_intersect_may_alias;
4886 unsigned HOST_WIDE_INT pt_solutions_intersect_no_alias;
4887 } pta_stats;
4889 void
4890 dump_pta_stats (FILE *s)
4892 fprintf (s, "\nPTA query stats:\n");
4893 fprintf (s, " pt_solution_includes: "
4894 HOST_WIDE_INT_PRINT_DEC" disambiguations, "
4895 HOST_WIDE_INT_PRINT_DEC" queries\n",
4896 pta_stats.pt_solution_includes_no_alias,
4897 pta_stats.pt_solution_includes_no_alias
4898 + pta_stats.pt_solution_includes_may_alias);
4899 fprintf (s, " pt_solutions_intersect: "
4900 HOST_WIDE_INT_PRINT_DEC" disambiguations, "
4901 HOST_WIDE_INT_PRINT_DEC" queries\n",
4902 pta_stats.pt_solutions_intersect_no_alias,
4903 pta_stats.pt_solutions_intersect_no_alias
4904 + pta_stats.pt_solutions_intersect_may_alias);
4908 /* Reset the points-to solution *PT to a conservative default
4909 (point to anything). */
4911 void
4912 pt_solution_reset (struct pt_solution *pt)
4914 memset (pt, 0, sizeof (struct pt_solution));
4915 pt->anything = true;
4918 /* Set the points-to solution *PT to point only to the variables
4919 in VARS. */
4921 void
4922 pt_solution_set (struct pt_solution *pt, bitmap vars)
4924 bitmap_iterator bi;
4925 unsigned i;
4927 memset (pt, 0, sizeof (struct pt_solution));
4928 pt->vars = vars;
4929 EXECUTE_IF_SET_IN_BITMAP (vars, 0, i, bi)
4931 tree var = referenced_var_lookup (i);
4932 if (is_global_var (var))
4934 pt->vars_contains_global = true;
4935 break;
4940 /* Return true if the points-to solution *PT is empty. */
4942 static bool
4943 pt_solution_empty_p (struct pt_solution *pt)
4945 if (pt->anything
4946 || pt->nonlocal)
4947 return false;
4949 if (pt->vars
4950 && !bitmap_empty_p (pt->vars))
4951 return false;
4953 /* If the solution includes ESCAPED, check if that is empty. */
4954 if (pt->escaped
4955 && !pt_solution_empty_p (&cfun->gimple_df->escaped))
4956 return false;
4958 return true;
4961 /* Return true if the points-to solution *PT includes global memory. */
4963 bool
4964 pt_solution_includes_global (struct pt_solution *pt)
4966 if (pt->anything
4967 || pt->nonlocal
4968 || pt->vars_contains_global)
4969 return true;
4971 if (pt->escaped)
4972 return pt_solution_includes_global (&cfun->gimple_df->escaped);
4974 return false;
4977 /* Return true if the points-to solution *PT includes the variable
4978 declaration DECL. */
4980 static bool
4981 pt_solution_includes_1 (struct pt_solution *pt, const_tree decl)
4983 if (pt->anything)
4984 return true;
4986 if (pt->nonlocal
4987 && is_global_var (decl))
4988 return true;
4990 if (pt->vars
4991 && bitmap_bit_p (pt->vars, DECL_UID (decl)))
4992 return true;
4994 /* If the solution includes ESCAPED, check it. */
4995 if (pt->escaped
4996 && pt_solution_includes_1 (&cfun->gimple_df->escaped, decl))
4997 return true;
4999 return false;
5002 bool
5003 pt_solution_includes (struct pt_solution *pt, const_tree decl)
5005 bool res = pt_solution_includes_1 (pt, decl);
5006 if (res)
5007 ++pta_stats.pt_solution_includes_may_alias;
5008 else
5009 ++pta_stats.pt_solution_includes_no_alias;
5010 return res;
5013 /* Return true if both points-to solutions PT1 and PT2 have a non-empty
5014 intersection. */
5016 static bool
5017 pt_solutions_intersect_1 (struct pt_solution *pt1, struct pt_solution *pt2)
5019 if (pt1->anything || pt2->anything)
5020 return true;
5022 /* If either points to unknown global memory and the other points to
5023 any global memory they alias. */
5024 if ((pt1->nonlocal
5025 && (pt2->nonlocal
5026 || pt2->vars_contains_global))
5027 || (pt2->nonlocal
5028 && pt1->vars_contains_global))
5029 return true;
5031 /* Check the escaped solution if required. */
5032 if ((pt1->escaped || pt2->escaped)
5033 && !pt_solution_empty_p (&cfun->gimple_df->escaped))
5035 /* If both point to escaped memory and that solution
5036 is not empty they alias. */
5037 if (pt1->escaped && pt2->escaped)
5038 return true;
5040 /* If either points to escaped memory see if the escaped solution
5041 intersects with the other. */
5042 if ((pt1->escaped
5043 && pt_solutions_intersect_1 (&cfun->gimple_df->escaped, pt2))
5044 || (pt2->escaped
5045 && pt_solutions_intersect_1 (&cfun->gimple_df->escaped, pt1)))
5046 return true;
5049 /* Now both pointers alias if their points-to solution intersects. */
5050 return (pt1->vars
5051 && pt2->vars
5052 && bitmap_intersect_p (pt1->vars, pt2->vars));
5055 bool
5056 pt_solutions_intersect (struct pt_solution *pt1, struct pt_solution *pt2)
5058 bool res = pt_solutions_intersect_1 (pt1, pt2);
5059 if (res)
5060 ++pta_stats.pt_solutions_intersect_may_alias;
5061 else
5062 ++pta_stats.pt_solutions_intersect_no_alias;
5063 return res;
5066 /* Return true if both points-to solutions PT1 and PT2 for two restrict
5067 qualified pointers are possibly based on the same pointer. */
5069 bool
5070 pt_solutions_same_restrict_base (struct pt_solution *pt1,
5071 struct pt_solution *pt2)
5073 /* If we deal with points-to solutions of two restrict qualified
5074 pointers solely rely on the pointed-to variable bitmap intersection.
5075 For two pointers that are based on each other the bitmaps will
5076 intersect. */
5077 if (pt1->vars_contains_restrict
5078 && pt2->vars_contains_restrict)
5080 gcc_assert (pt1->vars && pt2->vars);
5081 return bitmap_intersect_p (pt1->vars, pt2->vars);
5084 return true;
5088 /* Dump points-to information to OUTFILE. */
5090 static void
5091 dump_sa_points_to_info (FILE *outfile)
5093 unsigned int i;
5095 fprintf (outfile, "\nPoints-to sets\n\n");
5097 if (dump_flags & TDF_STATS)
5099 fprintf (outfile, "Stats:\n");
5100 fprintf (outfile, "Total vars: %d\n", stats.total_vars);
5101 fprintf (outfile, "Non-pointer vars: %d\n",
5102 stats.nonpointer_vars);
5103 fprintf (outfile, "Statically unified vars: %d\n",
5104 stats.unified_vars_static);
5105 fprintf (outfile, "Dynamically unified vars: %d\n",
5106 stats.unified_vars_dynamic);
5107 fprintf (outfile, "Iterations: %d\n", stats.iterations);
5108 fprintf (outfile, "Number of edges: %d\n", stats.num_edges);
5109 fprintf (outfile, "Number of implicit edges: %d\n",
5110 stats.num_implicit_edges);
5113 for (i = 0; i < VEC_length (varinfo_t, varmap); i++)
5114 dump_solution_for_var (outfile, i);
5118 /* Debug points-to information to stderr. */
5120 void
5121 debug_sa_points_to_info (void)
5123 dump_sa_points_to_info (stderr);
5127 /* Initialize the always-existing constraint variables for NULL
5128 ANYTHING, READONLY, and INTEGER */
5130 static void
5131 init_base_vars (void)
5133 struct constraint_expr lhs, rhs;
5134 varinfo_t var_anything;
5135 varinfo_t var_nothing;
5136 varinfo_t var_readonly;
5137 varinfo_t var_escaped;
5138 varinfo_t var_nonlocal;
5139 varinfo_t var_callused;
5140 varinfo_t var_storedanything;
5141 varinfo_t var_integer;
5143 /* Create the NULL variable, used to represent that a variable points
5144 to NULL. */
5145 var_nothing = new_var_info (NULL_TREE, "NULL");
5146 gcc_assert (var_nothing->id == nothing_id);
5147 var_nothing->is_artificial_var = 1;
5148 var_nothing->offset = 0;
5149 var_nothing->size = ~0;
5150 var_nothing->fullsize = ~0;
5151 var_nothing->is_special_var = 1;
5153 /* Create the ANYTHING variable, used to represent that a variable
5154 points to some unknown piece of memory. */
5155 var_anything = new_var_info (NULL_TREE, "ANYTHING");
5156 gcc_assert (var_anything->id == anything_id);
5157 var_anything->is_artificial_var = 1;
5158 var_anything->size = ~0;
5159 var_anything->offset = 0;
5160 var_anything->next = NULL;
5161 var_anything->fullsize = ~0;
5162 var_anything->is_special_var = 1;
5164 /* Anything points to anything. This makes deref constraints just
5165 work in the presence of linked list and other p = *p type loops,
5166 by saying that *ANYTHING = ANYTHING. */
5167 lhs.type = SCALAR;
5168 lhs.var = anything_id;
5169 lhs.offset = 0;
5170 rhs.type = ADDRESSOF;
5171 rhs.var = anything_id;
5172 rhs.offset = 0;
5174 /* This specifically does not use process_constraint because
5175 process_constraint ignores all anything = anything constraints, since all
5176 but this one are redundant. */
5177 VEC_safe_push (constraint_t, heap, constraints, new_constraint (lhs, rhs));
5179 /* Create the READONLY variable, used to represent that a variable
5180 points to readonly memory. */
5181 var_readonly = new_var_info (NULL_TREE, "READONLY");
5182 gcc_assert (var_readonly->id == readonly_id);
5183 var_readonly->is_artificial_var = 1;
5184 var_readonly->offset = 0;
5185 var_readonly->size = ~0;
5186 var_readonly->fullsize = ~0;
5187 var_readonly->next = NULL;
5188 var_readonly->is_special_var = 1;
5190 /* readonly memory points to anything, in order to make deref
5191 easier. In reality, it points to anything the particular
5192 readonly variable can point to, but we don't track this
5193 separately. */
5194 lhs.type = SCALAR;
5195 lhs.var = readonly_id;
5196 lhs.offset = 0;
5197 rhs.type = ADDRESSOF;
5198 rhs.var = readonly_id; /* FIXME */
5199 rhs.offset = 0;
5200 process_constraint (new_constraint (lhs, rhs));
5202 /* Create the ESCAPED variable, used to represent the set of escaped
5203 memory. */
5204 var_escaped = new_var_info (NULL_TREE, "ESCAPED");
5205 gcc_assert (var_escaped->id == escaped_id);
5206 var_escaped->is_artificial_var = 1;
5207 var_escaped->offset = 0;
5208 var_escaped->size = ~0;
5209 var_escaped->fullsize = ~0;
5210 var_escaped->is_special_var = 0;
5212 /* Create the NONLOCAL variable, used to represent the set of nonlocal
5213 memory. */
5214 var_nonlocal = new_var_info (NULL_TREE, "NONLOCAL");
5215 gcc_assert (var_nonlocal->id == nonlocal_id);
5216 var_nonlocal->is_artificial_var = 1;
5217 var_nonlocal->offset = 0;
5218 var_nonlocal->size = ~0;
5219 var_nonlocal->fullsize = ~0;
5220 var_nonlocal->is_special_var = 1;
5222 /* ESCAPED = *ESCAPED, because escaped is may-deref'd at calls, etc. */
5223 lhs.type = SCALAR;
5224 lhs.var = escaped_id;
5225 lhs.offset = 0;
5226 rhs.type = DEREF;
5227 rhs.var = escaped_id;
5228 rhs.offset = 0;
5229 process_constraint (new_constraint (lhs, rhs));
5231 /* ESCAPED = ESCAPED + UNKNOWN_OFFSET, because if a sub-field escapes the
5232 whole variable escapes. */
5233 lhs.type = SCALAR;
5234 lhs.var = escaped_id;
5235 lhs.offset = 0;
5236 rhs.type = SCALAR;
5237 rhs.var = escaped_id;
5238 rhs.offset = UNKNOWN_OFFSET;
5239 process_constraint (new_constraint (lhs, rhs));
5241 /* *ESCAPED = NONLOCAL. This is true because we have to assume
5242 everything pointed to by escaped points to what global memory can
5243 point to. */
5244 lhs.type = DEREF;
5245 lhs.var = escaped_id;
5246 lhs.offset = 0;
5247 rhs.type = SCALAR;
5248 rhs.var = nonlocal_id;
5249 rhs.offset = 0;
5250 process_constraint (new_constraint (lhs, rhs));
5252 /* NONLOCAL = &NONLOCAL, NONLOCAL = &ESCAPED. This is true because
5253 global memory may point to global memory and escaped memory. */
5254 lhs.type = SCALAR;
5255 lhs.var = nonlocal_id;
5256 lhs.offset = 0;
5257 rhs.type = ADDRESSOF;
5258 rhs.var = nonlocal_id;
5259 rhs.offset = 0;
5260 process_constraint (new_constraint (lhs, rhs));
5261 rhs.type = ADDRESSOF;
5262 rhs.var = escaped_id;
5263 rhs.offset = 0;
5264 process_constraint (new_constraint (lhs, rhs));
5266 /* Create the CALLUSED variable, used to represent the set of call-used
5267 memory. */
5268 var_callused = new_var_info (NULL_TREE, "CALLUSED");
5269 gcc_assert (var_callused->id == callused_id);
5270 var_callused->is_artificial_var = 1;
5271 var_callused->offset = 0;
5272 var_callused->size = ~0;
5273 var_callused->fullsize = ~0;
5274 var_callused->is_special_var = 0;
5276 /* CALLUSED = *CALLUSED, because call-used is may-deref'd at calls, etc. */
5277 lhs.type = SCALAR;
5278 lhs.var = callused_id;
5279 lhs.offset = 0;
5280 rhs.type = DEREF;
5281 rhs.var = callused_id;
5282 rhs.offset = 0;
5283 process_constraint (new_constraint (lhs, rhs));
5285 /* CALLUSED = CALLUSED + UNKNOWN, because if a sub-field is call-used the
5286 whole variable is call-used. */
5287 lhs.type = SCALAR;
5288 lhs.var = callused_id;
5289 lhs.offset = 0;
5290 rhs.type = SCALAR;
5291 rhs.var = callused_id;
5292 rhs.offset = UNKNOWN_OFFSET;
5293 process_constraint (new_constraint (lhs, rhs));
5295 /* Create the STOREDANYTHING variable, used to represent the set of
5296 variables stored to *ANYTHING. */
5297 var_storedanything = new_var_info (NULL_TREE, "STOREDANYTHING");
5298 gcc_assert (var_storedanything->id == storedanything_id);
5299 var_storedanything->is_artificial_var = 1;
5300 var_storedanything->offset = 0;
5301 var_storedanything->size = ~0;
5302 var_storedanything->fullsize = ~0;
5303 var_storedanything->is_special_var = 0;
5305 /* Create the INTEGER variable, used to represent that a variable points
5306 to what an INTEGER "points to". */
5307 var_integer = new_var_info (NULL_TREE, "INTEGER");
5308 gcc_assert (var_integer->id == integer_id);
5309 var_integer->is_artificial_var = 1;
5310 var_integer->size = ~0;
5311 var_integer->fullsize = ~0;
5312 var_integer->offset = 0;
5313 var_integer->next = NULL;
5314 var_integer->is_special_var = 1;
5316 /* INTEGER = ANYTHING, because we don't know where a dereference of
5317 a random integer will point to. */
5318 lhs.type = SCALAR;
5319 lhs.var = integer_id;
5320 lhs.offset = 0;
5321 rhs.type = ADDRESSOF;
5322 rhs.var = anything_id;
5323 rhs.offset = 0;
5324 process_constraint (new_constraint (lhs, rhs));
5327 /* Initialize things necessary to perform PTA */
5329 static void
5330 init_alias_vars (void)
5332 use_field_sensitive = (MAX_FIELDS_FOR_FIELD_SENSITIVE > 1);
5334 bitmap_obstack_initialize (&pta_obstack);
5335 bitmap_obstack_initialize (&oldpta_obstack);
5336 bitmap_obstack_initialize (&predbitmap_obstack);
5338 constraint_pool = create_alloc_pool ("Constraint pool",
5339 sizeof (struct constraint), 30);
5340 variable_info_pool = create_alloc_pool ("Variable info pool",
5341 sizeof (struct variable_info), 30);
5342 constraints = VEC_alloc (constraint_t, heap, 8);
5343 varmap = VEC_alloc (varinfo_t, heap, 8);
5344 vi_for_tree = pointer_map_create ();
5346 memset (&stats, 0, sizeof (stats));
5347 shared_bitmap_table = htab_create (511, shared_bitmap_hash,
5348 shared_bitmap_eq, free);
5349 init_base_vars ();
5352 /* Remove the REF and ADDRESS edges from GRAPH, as well as all the
5353 predecessor edges. */
5355 static void
5356 remove_preds_and_fake_succs (constraint_graph_t graph)
5358 unsigned int i;
5360 /* Clear the implicit ref and address nodes from the successor
5361 lists. */
5362 for (i = 0; i < FIRST_REF_NODE; i++)
5364 if (graph->succs[i])
5365 bitmap_clear_range (graph->succs[i], FIRST_REF_NODE,
5366 FIRST_REF_NODE * 2);
5369 /* Free the successor list for the non-ref nodes. */
5370 for (i = FIRST_REF_NODE; i < graph->size; i++)
5372 if (graph->succs[i])
5373 BITMAP_FREE (graph->succs[i]);
5376 /* Now reallocate the size of the successor list as, and blow away
5377 the predecessor bitmaps. */
5378 graph->size = VEC_length (varinfo_t, varmap);
5379 graph->succs = XRESIZEVEC (bitmap, graph->succs, graph->size);
5381 free (graph->implicit_preds);
5382 graph->implicit_preds = NULL;
5383 free (graph->preds);
5384 graph->preds = NULL;
5385 bitmap_obstack_release (&predbitmap_obstack);
5388 /* Initialize the heapvar for statement mapping. */
5390 static void
5391 init_alias_heapvars (void)
5393 if (!heapvar_for_stmt)
5394 heapvar_for_stmt = htab_create_ggc (11, tree_map_hash, heapvar_map_eq,
5395 NULL);
5398 /* Delete the heapvar for statement mapping. */
5400 void
5401 delete_alias_heapvars (void)
5403 if (heapvar_for_stmt)
5404 htab_delete (heapvar_for_stmt);
5405 heapvar_for_stmt = NULL;
5408 /* Solve the constraint set. */
5410 static void
5411 solve_constraints (void)
5413 struct scc_info *si;
5415 if (dump_file)
5417 fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
5418 dump_constraints (dump_file);
5421 if (dump_file)
5422 fprintf (dump_file,
5423 "\nCollapsing static cycles and doing variable "
5424 "substitution\n");
5426 init_graph (VEC_length (varinfo_t, varmap) * 2);
5428 if (dump_file)
5429 fprintf (dump_file, "Building predecessor graph\n");
5430 build_pred_graph ();
5432 if (dump_file)
5433 fprintf (dump_file, "Detecting pointer and location "
5434 "equivalences\n");
5435 si = perform_var_substitution (graph);
5437 if (dump_file)
5438 fprintf (dump_file, "Rewriting constraints and unifying "
5439 "variables\n");
5440 rewrite_constraints (graph, si);
5442 build_succ_graph ();
5443 free_var_substitution_info (si);
5445 if (dump_file && (dump_flags & TDF_GRAPH))
5446 dump_constraint_graph (dump_file);
5448 move_complex_constraints (graph);
5450 if (dump_file)
5451 fprintf (dump_file, "Uniting pointer but not location equivalent "
5452 "variables\n");
5453 unite_pointer_equivalences (graph);
5455 if (dump_file)
5456 fprintf (dump_file, "Finding indirect cycles\n");
5457 find_indirect_cycles (graph);
5459 /* Implicit nodes and predecessors are no longer necessary at this
5460 point. */
5461 remove_preds_and_fake_succs (graph);
5463 if (dump_file)
5464 fprintf (dump_file, "Solving graph\n");
5466 solve_graph (graph);
5468 if (dump_file)
5469 dump_sa_points_to_info (dump_file);
5472 /* Create points-to sets for the current function. See the comments
5473 at the start of the file for an algorithmic overview. */
5475 static void
5476 compute_points_to_sets (void)
5478 basic_block bb;
5479 unsigned i;
5480 varinfo_t vi;
5482 timevar_push (TV_TREE_PTA);
5484 init_alias_vars ();
5485 init_alias_heapvars ();
5487 intra_create_variable_infos ();
5489 /* Now walk all statements and derive aliases. */
5490 FOR_EACH_BB (bb)
5492 gimple_stmt_iterator gsi;
5494 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5496 gimple phi = gsi_stmt (gsi);
5498 if (is_gimple_reg (gimple_phi_result (phi)))
5499 find_func_aliases (phi);
5502 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5504 gimple stmt = gsi_stmt (gsi);
5506 find_func_aliases (stmt);
5510 /* From the constraints compute the points-to sets. */
5511 solve_constraints ();
5513 /* Compute the points-to sets for ESCAPED and CALLUSED used for
5514 call-clobber analysis. */
5515 find_what_var_points_to (get_varinfo (escaped_id),
5516 &cfun->gimple_df->escaped);
5517 find_what_var_points_to (get_varinfo (callused_id),
5518 &cfun->gimple_df->callused);
5520 /* Make sure the ESCAPED solution (which is used as placeholder in
5521 other solutions) does not reference itself. This simplifies
5522 points-to solution queries. */
5523 cfun->gimple_df->escaped.escaped = 0;
5525 /* Mark escaped HEAP variables as global. */
5526 for (i = 0; VEC_iterate (varinfo_t, varmap, i, vi); ++i)
5527 if (vi->is_heap_var
5528 && !vi->is_restrict_var
5529 && !vi->is_global_var)
5530 DECL_EXTERNAL (vi->decl) = vi->is_global_var
5531 = pt_solution_includes (&cfun->gimple_df->escaped, vi->decl);
5533 /* Compute the points-to sets for pointer SSA_NAMEs. */
5534 for (i = 0; i < num_ssa_names; ++i)
5536 tree ptr = ssa_name (i);
5537 if (ptr
5538 && POINTER_TYPE_P (TREE_TYPE (ptr)))
5539 find_what_p_points_to (ptr);
5542 timevar_pop (TV_TREE_PTA);
5546 /* Delete created points-to sets. */
5548 static void
5549 delete_points_to_sets (void)
5551 unsigned int i;
5553 htab_delete (shared_bitmap_table);
5554 if (dump_file && (dump_flags & TDF_STATS))
5555 fprintf (dump_file, "Points to sets created:%d\n",
5556 stats.points_to_sets_created);
5558 pointer_map_destroy (vi_for_tree);
5559 bitmap_obstack_release (&pta_obstack);
5560 VEC_free (constraint_t, heap, constraints);
5562 for (i = 0; i < graph->size; i++)
5563 VEC_free (constraint_t, heap, graph->complex[i]);
5564 free (graph->complex);
5566 free (graph->rep);
5567 free (graph->succs);
5568 free (graph->pe);
5569 free (graph->pe_rep);
5570 free (graph->indirect_cycles);
5571 free (graph);
5573 VEC_free (varinfo_t, heap, varmap);
5574 free_alloc_pool (variable_info_pool);
5575 free_alloc_pool (constraint_pool);
5579 /* Compute points-to information for every SSA_NAME pointer in the
5580 current function and compute the transitive closure of escaped
5581 variables to re-initialize the call-clobber states of local variables. */
5583 unsigned int
5584 compute_may_aliases (void)
5586 /* For each pointer P_i, determine the sets of variables that P_i may
5587 point-to. Compute the reachability set of escaped and call-used
5588 variables. */
5589 compute_points_to_sets ();
5591 /* Debugging dumps. */
5592 if (dump_file)
5594 dump_alias_info (dump_file);
5596 if (dump_flags & TDF_DETAILS)
5597 dump_referenced_vars (dump_file);
5600 /* Deallocate memory used by aliasing data structures and the internal
5601 points-to solution. */
5602 delete_points_to_sets ();
5604 gcc_assert (!need_ssa_update_p (cfun));
5606 return 0;
5609 static bool
5610 gate_tree_pta (void)
5612 return flag_tree_pta;
5615 /* A dummy pass to cause points-to information to be computed via
5616 TODO_rebuild_alias. */
5618 struct gimple_opt_pass pass_build_alias =
5621 GIMPLE_PASS,
5622 "alias", /* name */
5623 gate_tree_pta, /* gate */
5624 NULL, /* execute */
5625 NULL, /* sub */
5626 NULL, /* next */
5627 0, /* static_pass_number */
5628 TV_NONE, /* tv_id */
5629 PROP_cfg | PROP_ssa, /* properties_required */
5630 0, /* properties_provided */
5631 0, /* properties_destroyed */
5632 0, /* todo_flags_start */
5633 TODO_rebuild_alias | TODO_dump_func /* todo_flags_finish */
5637 /* A dummy pass to cause points-to information to be computed via
5638 TODO_rebuild_alias. */
5640 struct gimple_opt_pass pass_build_ealias =
5643 GIMPLE_PASS,
5644 "ealias", /* name */
5645 gate_tree_pta, /* gate */
5646 NULL, /* execute */
5647 NULL, /* sub */
5648 NULL, /* next */
5649 0, /* static_pass_number */
5650 TV_NONE, /* tv_id */
5651 PROP_cfg | PROP_ssa, /* properties_required */
5652 0, /* properties_provided */
5653 0, /* properties_destroyed */
5654 0, /* todo_flags_start */
5655 TODO_rebuild_alias | TODO_dump_func /* todo_flags_finish */
5660 /* Return true if we should execute IPA PTA. */
5661 static bool
5662 gate_ipa_pta (void)
5664 return (optimize
5665 && flag_ipa_pta
5666 /* Don't bother doing anything if the program has errors. */
5667 && !(errorcount || sorrycount));
5670 /* Execute the driver for IPA PTA. */
5671 static unsigned int
5672 ipa_pta_execute (void)
5674 struct cgraph_node *node;
5676 in_ipa_mode = 1;
5678 init_alias_heapvars ();
5679 init_alias_vars ();
5681 /* Build the constraints. */
5682 for (node = cgraph_nodes; node; node = node->next)
5684 /* Nodes without a body are not interesting. Especially do not
5685 visit clones at this point for now - we get duplicate decls
5686 there for inline clones at least. */
5687 if (!gimple_has_body_p (node->decl)
5688 || node->clone_of)
5689 continue;
5691 /* It does not make sense to have graph edges into or out of
5692 externally visible functions. There is no extra information
5693 we can gather from them. */
5694 if (node->local.externally_visible)
5695 continue;
5697 create_function_info_for (node->decl,
5698 cgraph_node_name (node));
5701 for (node = cgraph_nodes; node; node = node->next)
5703 struct function *func;
5704 basic_block bb;
5705 tree old_func_decl;
5707 /* Nodes without a body are not interesting. */
5708 if (!gimple_has_body_p (node->decl)
5709 || node->clone_of)
5710 continue;
5712 if (dump_file)
5713 fprintf (dump_file,
5714 "Generating constraints for %s\n",
5715 cgraph_node_name (node));
5717 func = DECL_STRUCT_FUNCTION (node->decl);
5718 old_func_decl = current_function_decl;
5719 push_cfun (func);
5720 current_function_decl = node->decl;
5722 /* For externally visible functions use local constraints for
5723 their arguments. For local functions we see all callers
5724 and thus do not need initial constraints for parameters. */
5725 if (node->local.externally_visible)
5726 intra_create_variable_infos ();
5728 /* Build constriants for the function body. */
5729 FOR_EACH_BB_FN (bb, func)
5731 gimple_stmt_iterator gsi;
5733 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
5734 gsi_next (&gsi))
5736 gimple phi = gsi_stmt (gsi);
5738 if (is_gimple_reg (gimple_phi_result (phi)))
5739 find_func_aliases (phi);
5742 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5744 gimple stmt = gsi_stmt (gsi);
5746 find_func_aliases (stmt);
5750 current_function_decl = old_func_decl;
5751 pop_cfun ();
5754 /* From the constraints compute the points-to sets. */
5755 solve_constraints ();
5757 delete_points_to_sets ();
5759 in_ipa_mode = 0;
5761 return 0;
5764 struct simple_ipa_opt_pass pass_ipa_pta =
5767 SIMPLE_IPA_PASS,
5768 "pta", /* name */
5769 gate_ipa_pta, /* gate */
5770 ipa_pta_execute, /* execute */
5771 NULL, /* sub */
5772 NULL, /* next */
5773 0, /* static_pass_number */
5774 TV_IPA_PTA, /* tv_id */
5775 0, /* properties_required */
5776 0, /* properties_provided */
5777 0, /* properties_destroyed */
5778 0, /* todo_flags_start */
5779 TODO_update_ssa /* todo_flags_finish */
5784 #include "gt-tree-ssa-structalias.h"