* config/rs6000/rs6000-c.c (altivec_resolve_overloaded_builtin):
[official-gcc.git] / gcc / tree-ssa-structalias.c
blobb0768d0c20bf65488d16f20951a9fa6f37942795
1 /* Tree based points-to analysis
2 Copyright (C) 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
3 Contributed by Daniel Berlin <dberlin@dberlin.org>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "ggc.h"
26 #include "obstack.h"
27 #include "bitmap.h"
28 #include "flags.h"
29 #include "rtl.h"
30 #include "tm_p.h"
31 #include "hard-reg-set.h"
32 #include "basic-block.h"
33 #include "output.h"
34 #include "tree.h"
35 #include "c-common.h"
36 #include "tree-flow.h"
37 #include "tree-inline.h"
38 #include "varray.h"
39 #include "c-tree.h"
40 #include "diagnostic.h"
41 #include "toplev.h"
42 #include "gimple.h"
43 #include "hashtab.h"
44 #include "function.h"
45 #include "cgraph.h"
46 #include "tree-pass.h"
47 #include "timevar.h"
48 #include "alloc-pool.h"
49 #include "splay-tree.h"
50 #include "params.h"
51 #include "cgraph.h"
52 #include "alias.h"
53 #include "pointer-set.h"
55 /* The idea behind this analyzer is to generate set constraints from the
56 program, then solve the resulting constraints in order to generate the
57 points-to sets.
59 Set constraints are a way of modeling program analysis problems that
60 involve sets. They consist of an inclusion constraint language,
61 describing the variables (each variable is a set) and operations that
62 are involved on the variables, and a set of rules that derive facts
63 from these operations. To solve a system of set constraints, you derive
64 all possible facts under the rules, which gives you the correct sets
65 as a consequence.
67 See "Efficient Field-sensitive pointer analysis for C" by "David
68 J. Pearce and Paul H. J. Kelly and Chris Hankin, at
69 http://citeseer.ist.psu.edu/pearce04efficient.html
71 Also see "Ultra-fast Aliasing Analysis using CLA: A Million Lines
72 of C Code in a Second" by ""Nevin Heintze and Olivier Tardieu" at
73 http://citeseer.ist.psu.edu/heintze01ultrafast.html
75 There are three types of real constraint expressions, DEREF,
76 ADDRESSOF, and SCALAR. Each constraint expression consists
77 of a constraint type, a variable, and an offset.
79 SCALAR is a constraint expression type used to represent x, whether
80 it appears on the LHS or the RHS of a statement.
81 DEREF is a constraint expression type used to represent *x, whether
82 it appears on the LHS or the RHS of a statement.
83 ADDRESSOF is a constraint expression used to represent &x, whether
84 it appears on the LHS or the RHS of a statement.
86 Each pointer variable in the program is assigned an integer id, and
87 each field of a structure variable is assigned an integer id as well.
89 Structure variables are linked to their list of fields through a "next
90 field" in each variable that points to the next field in offset
91 order.
92 Each variable for a structure field has
94 1. "size", that tells the size in bits of that field.
95 2. "fullsize, that tells the size in bits of the entire structure.
96 3. "offset", that tells the offset in bits from the beginning of the
97 structure to this field.
99 Thus,
100 struct f
102 int a;
103 int b;
104 } foo;
105 int *bar;
107 looks like
109 foo.a -> id 1, size 32, offset 0, fullsize 64, next foo.b
110 foo.b -> id 2, size 32, offset 32, fullsize 64, next NULL
111 bar -> id 3, size 32, offset 0, fullsize 32, next NULL
114 In order to solve the system of set constraints, the following is
115 done:
117 1. Each constraint variable x has a solution set associated with it,
118 Sol(x).
120 2. Constraints are separated into direct, copy, and complex.
121 Direct constraints are ADDRESSOF constraints that require no extra
122 processing, such as P = &Q
123 Copy constraints are those of the form P = Q.
124 Complex constraints are all the constraints involving dereferences
125 and offsets (including offsetted copies).
127 3. All direct constraints of the form P = &Q are processed, such
128 that Q is added to Sol(P)
130 4. All complex constraints for a given constraint variable are stored in a
131 linked list attached to that variable's node.
133 5. A directed graph is built out of the copy constraints. Each
134 constraint variable is a node in the graph, and an edge from
135 Q to P is added for each copy constraint of the form P = Q
137 6. The graph is then walked, and solution sets are
138 propagated along the copy edges, such that an edge from Q to P
139 causes Sol(P) <- Sol(P) union Sol(Q).
141 7. As we visit each node, all complex constraints associated with
142 that node are processed by adding appropriate copy edges to the graph, or the
143 appropriate variables to the solution set.
145 8. The process of walking the graph is iterated until no solution
146 sets change.
148 Prior to walking the graph in steps 6 and 7, We perform static
149 cycle elimination on the constraint graph, as well
150 as off-line variable substitution.
152 TODO: Adding offsets to pointer-to-structures can be handled (IE not punted
153 on and turned into anything), but isn't. You can just see what offset
154 inside the pointed-to struct it's going to access.
156 TODO: Constant bounded arrays can be handled as if they were structs of the
157 same number of elements.
159 TODO: Modeling heap and incoming pointers becomes much better if we
160 add fields to them as we discover them, which we could do.
162 TODO: We could handle unions, but to be honest, it's probably not
163 worth the pain or slowdown. */
165 static GTY ((if_marked ("tree_map_marked_p"), param_is (struct tree_map)))
166 htab_t heapvar_for_stmt;
168 static bool use_field_sensitive = true;
169 static int in_ipa_mode = 0;
171 /* Used for predecessor bitmaps. */
172 static bitmap_obstack predbitmap_obstack;
174 /* Used for points-to sets. */
175 static bitmap_obstack pta_obstack;
177 /* Used for oldsolution members of variables. */
178 static bitmap_obstack oldpta_obstack;
180 /* Used for per-solver-iteration bitmaps. */
181 static bitmap_obstack iteration_obstack;
183 static unsigned int create_variable_info_for (tree, const char *);
184 typedef struct constraint_graph *constraint_graph_t;
185 static void unify_nodes (constraint_graph_t, unsigned int, unsigned int, bool);
187 struct constraint;
188 typedef struct constraint *constraint_t;
190 DEF_VEC_P(constraint_t);
191 DEF_VEC_ALLOC_P(constraint_t,heap);
193 #define EXECUTE_IF_IN_NONNULL_BITMAP(a, b, c, d) \
194 if (a) \
195 EXECUTE_IF_SET_IN_BITMAP (a, b, c, d)
197 static struct constraint_stats
199 unsigned int total_vars;
200 unsigned int nonpointer_vars;
201 unsigned int unified_vars_static;
202 unsigned int unified_vars_dynamic;
203 unsigned int iterations;
204 unsigned int num_edges;
205 unsigned int num_implicit_edges;
206 unsigned int points_to_sets_created;
207 } stats;
209 struct variable_info
211 /* ID of this variable */
212 unsigned int id;
214 /* True if this is a variable created by the constraint analysis, such as
215 heap variables and constraints we had to break up. */
216 unsigned int is_artificial_var:1;
218 /* True if this is a special variable whose solution set should not be
219 changed. */
220 unsigned int is_special_var:1;
222 /* True for variables whose size is not known or variable. */
223 unsigned int is_unknown_size_var:1;
225 /* True for (sub-)fields that represent a whole variable. */
226 unsigned int is_full_var : 1;
228 /* True if this is a heap variable. */
229 unsigned int is_heap_var:1;
231 /* True if we may not use TBAA to prune references to this
232 variable. This is used for C++ placement new. */
233 unsigned int no_tbaa_pruning : 1;
235 /* True if this field may contain pointers. */
236 unsigned int may_have_pointers : 1;
238 /* A link to the variable for the next field in this structure. */
239 struct variable_info *next;
241 /* Offset of this variable, in bits, from the base variable */
242 unsigned HOST_WIDE_INT offset;
244 /* Size of the variable, in bits. */
245 unsigned HOST_WIDE_INT size;
247 /* Full size of the base variable, in bits. */
248 unsigned HOST_WIDE_INT fullsize;
250 /* Name of this variable */
251 const char *name;
253 /* Tree that this variable is associated with. */
254 tree decl;
256 /* Points-to set for this variable. */
257 bitmap solution;
259 /* Old points-to set for this variable. */
260 bitmap oldsolution;
262 typedef struct variable_info *varinfo_t;
264 static varinfo_t first_vi_for_offset (varinfo_t, unsigned HOST_WIDE_INT);
265 static varinfo_t first_or_preceding_vi_for_offset (varinfo_t,
266 unsigned HOST_WIDE_INT);
267 static varinfo_t lookup_vi_for_tree (tree);
269 /* Pool of variable info structures. */
270 static alloc_pool variable_info_pool;
272 DEF_VEC_P(varinfo_t);
274 DEF_VEC_ALLOC_P(varinfo_t, heap);
276 /* Table of variable info structures for constraint variables.
277 Indexed directly by variable info id. */
278 static VEC(varinfo_t,heap) *varmap;
280 /* Return the varmap element N */
282 static inline varinfo_t
283 get_varinfo (unsigned int n)
285 return VEC_index (varinfo_t, varmap, n);
288 /* Static IDs for the special variables. */
289 enum { nothing_id = 0, anything_id = 1, readonly_id = 2,
290 escaped_id = 3, nonlocal_id = 4, callused_id = 5,
291 storedanything_id = 6, integer_id = 7 };
293 /* Variable that represents the unknown pointer. */
294 static varinfo_t var_anything;
295 static tree anything_tree;
297 /* Variable that represents the NULL pointer. */
298 static varinfo_t var_nothing;
299 static tree nothing_tree;
301 /* Variable that represents read only memory. */
302 static varinfo_t var_readonly;
303 static tree readonly_tree;
305 /* Variable that represents escaped memory. */
306 static varinfo_t var_escaped;
307 static tree escaped_tree;
309 /* Variable that represents nonlocal memory. */
310 static varinfo_t var_nonlocal;
311 static tree nonlocal_tree;
313 /* Variable that represents call-used memory. */
314 static varinfo_t var_callused;
315 static tree callused_tree;
317 /* Variable that represents variables that are stored to anything. */
318 static varinfo_t var_storedanything;
319 static tree storedanything_tree;
321 /* Variable that represents integers. This is used for when people do things
322 like &0->a.b. */
323 static varinfo_t var_integer;
324 static tree integer_tree;
326 /* Lookup a heap var for FROM, and return it if we find one. */
328 static tree
329 heapvar_lookup (tree from)
331 struct tree_map *h, in;
332 in.base.from = from;
334 h = (struct tree_map *) htab_find_with_hash (heapvar_for_stmt, &in,
335 htab_hash_pointer (from));
336 if (h)
337 return h->to;
338 return NULL_TREE;
341 /* Insert a mapping FROM->TO in the heap var for statement
342 hashtable. */
344 static void
345 heapvar_insert (tree from, tree to)
347 struct tree_map *h;
348 void **loc;
350 h = GGC_NEW (struct tree_map);
351 h->hash = htab_hash_pointer (from);
352 h->base.from = from;
353 h->to = to;
354 loc = htab_find_slot_with_hash (heapvar_for_stmt, h, h->hash, INSERT);
355 *(struct tree_map **) loc = h;
358 /* Return a new variable info structure consisting for a variable
359 named NAME, and using constraint graph node NODE. */
361 static varinfo_t
362 new_var_info (tree t, unsigned int id, const char *name)
364 varinfo_t ret = (varinfo_t) pool_alloc (variable_info_pool);
365 tree var;
367 ret->id = id;
368 ret->name = name;
369 ret->decl = t;
370 ret->is_artificial_var = false;
371 ret->is_heap_var = false;
372 ret->is_special_var = false;
373 ret->is_unknown_size_var = false;
374 ret->is_full_var = false;
375 ret->may_have_pointers = true;
376 var = t;
377 if (TREE_CODE (var) == SSA_NAME)
378 var = SSA_NAME_VAR (var);
379 ret->no_tbaa_pruning = (DECL_P (var)
380 && POINTER_TYPE_P (TREE_TYPE (var))
381 && DECL_NO_TBAA_P (var));
382 ret->solution = BITMAP_ALLOC (&pta_obstack);
383 ret->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
384 ret->next = NULL;
385 return ret;
388 typedef enum {SCALAR, DEREF, ADDRESSOF} constraint_expr_type;
390 /* An expression that appears in a constraint. */
392 struct constraint_expr
394 /* Constraint type. */
395 constraint_expr_type type;
397 /* Variable we are referring to in the constraint. */
398 unsigned int var;
400 /* Offset, in bits, of this constraint from the beginning of
401 variables it ends up referring to.
403 IOW, in a deref constraint, we would deref, get the result set,
404 then add OFFSET to each member. */
405 HOST_WIDE_INT offset;
408 /* Use 0x8000... as special unknown offset. */
409 #define UNKNOWN_OFFSET ((HOST_WIDE_INT)-1 << (HOST_BITS_PER_WIDE_INT-1))
411 typedef struct constraint_expr ce_s;
412 DEF_VEC_O(ce_s);
413 DEF_VEC_ALLOC_O(ce_s, heap);
414 static void get_constraint_for_1 (tree, VEC(ce_s, heap) **, bool);
415 static void get_constraint_for (tree, VEC(ce_s, heap) **);
416 static void do_deref (VEC (ce_s, heap) **);
418 /* Our set constraints are made up of two constraint expressions, one
419 LHS, and one RHS.
421 As described in the introduction, our set constraints each represent an
422 operation between set valued variables.
424 struct constraint
426 struct constraint_expr lhs;
427 struct constraint_expr rhs;
430 /* List of constraints that we use to build the constraint graph from. */
432 static VEC(constraint_t,heap) *constraints;
433 static alloc_pool constraint_pool;
436 DEF_VEC_I(int);
437 DEF_VEC_ALLOC_I(int, heap);
439 /* The constraint graph is represented as an array of bitmaps
440 containing successor nodes. */
442 struct constraint_graph
444 /* Size of this graph, which may be different than the number of
445 nodes in the variable map. */
446 unsigned int size;
448 /* Explicit successors of each node. */
449 bitmap *succs;
451 /* Implicit predecessors of each node (Used for variable
452 substitution). */
453 bitmap *implicit_preds;
455 /* Explicit predecessors of each node (Used for variable substitution). */
456 bitmap *preds;
458 /* Indirect cycle representatives, or -1 if the node has no indirect
459 cycles. */
460 int *indirect_cycles;
462 /* Representative node for a node. rep[a] == a unless the node has
463 been unified. */
464 unsigned int *rep;
466 /* Equivalence class representative for a label. This is used for
467 variable substitution. */
468 int *eq_rep;
470 /* Pointer equivalence label for a node. All nodes with the same
471 pointer equivalence label can be unified together at some point
472 (either during constraint optimization or after the constraint
473 graph is built). */
474 unsigned int *pe;
476 /* Pointer equivalence representative for a label. This is used to
477 handle nodes that are pointer equivalent but not location
478 equivalent. We can unite these once the addressof constraints
479 are transformed into initial points-to sets. */
480 int *pe_rep;
482 /* Pointer equivalence label for each node, used during variable
483 substitution. */
484 unsigned int *pointer_label;
486 /* Location equivalence label for each node, used during location
487 equivalence finding. */
488 unsigned int *loc_label;
490 /* Pointed-by set for each node, used during location equivalence
491 finding. This is pointed-by rather than pointed-to, because it
492 is constructed using the predecessor graph. */
493 bitmap *pointed_by;
495 /* Points to sets for pointer equivalence. This is *not* the actual
496 points-to sets for nodes. */
497 bitmap *points_to;
499 /* Bitmap of nodes where the bit is set if the node is a direct
500 node. Used for variable substitution. */
501 sbitmap direct_nodes;
503 /* Bitmap of nodes where the bit is set if the node is address
504 taken. Used for variable substitution. */
505 bitmap address_taken;
507 /* Vector of complex constraints for each graph node. Complex
508 constraints are those involving dereferences or offsets that are
509 not 0. */
510 VEC(constraint_t,heap) **complex;
513 static constraint_graph_t graph;
515 /* During variable substitution and the offline version of indirect
516 cycle finding, we create nodes to represent dereferences and
517 address taken constraints. These represent where these start and
518 end. */
519 #define FIRST_REF_NODE (VEC_length (varinfo_t, varmap))
520 #define LAST_REF_NODE (FIRST_REF_NODE + (FIRST_REF_NODE - 1))
522 /* Return the representative node for NODE, if NODE has been unioned
523 with another NODE.
524 This function performs path compression along the way to finding
525 the representative. */
527 static unsigned int
528 find (unsigned int node)
530 gcc_assert (node < graph->size);
531 if (graph->rep[node] != node)
532 return graph->rep[node] = find (graph->rep[node]);
533 return node;
536 /* Union the TO and FROM nodes to the TO nodes.
537 Note that at some point in the future, we may want to do
538 union-by-rank, in which case we are going to have to return the
539 node we unified to. */
541 static bool
542 unite (unsigned int to, unsigned int from)
544 gcc_assert (to < graph->size && from < graph->size);
545 if (to != from && graph->rep[from] != to)
547 graph->rep[from] = to;
548 return true;
550 return false;
553 /* Create a new constraint consisting of LHS and RHS expressions. */
555 static constraint_t
556 new_constraint (const struct constraint_expr lhs,
557 const struct constraint_expr rhs)
559 constraint_t ret = (constraint_t) pool_alloc (constraint_pool);
560 ret->lhs = lhs;
561 ret->rhs = rhs;
562 return ret;
565 /* Print out constraint C to FILE. */
567 static void
568 dump_constraint (FILE *file, constraint_t c)
570 if (c->lhs.type == ADDRESSOF)
571 fprintf (file, "&");
572 else if (c->lhs.type == DEREF)
573 fprintf (file, "*");
574 fprintf (file, "%s", get_varinfo (c->lhs.var)->name);
575 if (c->lhs.offset == UNKNOWN_OFFSET)
576 fprintf (file, " + UNKNOWN");
577 else if (c->lhs.offset != 0)
578 fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->lhs.offset);
579 fprintf (file, " = ");
580 if (c->rhs.type == ADDRESSOF)
581 fprintf (file, "&");
582 else if (c->rhs.type == DEREF)
583 fprintf (file, "*");
584 fprintf (file, "%s", get_varinfo (c->rhs.var)->name);
585 if (c->rhs.offset == UNKNOWN_OFFSET)
586 fprintf (file, " + UNKNOWN");
587 else if (c->rhs.offset != 0)
588 fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->rhs.offset);
589 fprintf (file, "\n");
593 void debug_constraint (constraint_t);
594 void debug_constraints (void);
595 void debug_constraint_graph (void);
596 void debug_solution_for_var (unsigned int);
597 void debug_sa_points_to_info (void);
599 /* Print out constraint C to stderr. */
601 void
602 debug_constraint (constraint_t c)
604 dump_constraint (stderr, c);
607 /* Print out all constraints to FILE */
609 static void
610 dump_constraints (FILE *file)
612 int i;
613 constraint_t c;
614 for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
615 dump_constraint (file, c);
618 /* Print out all constraints to stderr. */
620 void
621 debug_constraints (void)
623 dump_constraints (stderr);
626 /* Print out to FILE the edge in the constraint graph that is created by
627 constraint c. The edge may have a label, depending on the type of
628 constraint that it represents. If complex1, e.g: a = *b, then the label
629 is "=*", if complex2, e.g: *a = b, then the label is "*=", if
630 complex with an offset, e.g: a = b + 8, then the label is "+".
631 Otherwise the edge has no label. */
633 static void
634 dump_constraint_edge (FILE *file, constraint_t c)
636 if (c->rhs.type != ADDRESSOF)
638 const char *src = get_varinfo (c->rhs.var)->name;
639 const char *dst = get_varinfo (c->lhs.var)->name;
640 fprintf (file, " \"%s\" -> \"%s\" ", src, dst);
641 /* Due to preprocessing of constraints, instructions like *a = *b are
642 illegal; thus, we do not have to handle such cases. */
643 if (c->lhs.type == DEREF)
644 fprintf (file, " [ label=\"*=\" ] ;\n");
645 else if (c->rhs.type == DEREF)
646 fprintf (file, " [ label=\"=*\" ] ;\n");
647 else
649 /* We must check the case where the constraint is an offset.
650 In this case, it is treated as a complex constraint. */
651 if (c->rhs.offset != c->lhs.offset)
652 fprintf (file, " [ label=\"+\" ] ;\n");
653 else
654 fprintf (file, " ;\n");
659 /* Print the constraint graph in dot format. */
661 static void
662 dump_constraint_graph (FILE *file)
664 unsigned int i=0, size;
665 constraint_t c;
667 /* Only print the graph if it has already been initialized: */
668 if (!graph)
669 return;
671 /* Print the constraints used to produce the constraint graph. The
672 constraints will be printed as comments in the dot file: */
673 fprintf (file, "\n\n/* Constraints used in the constraint graph:\n");
674 dump_constraints (file);
675 fprintf (file, "*/\n");
677 /* Prints the header of the dot file: */
678 fprintf (file, "\n\n// The constraint graph in dot format:\n");
679 fprintf (file, "strict digraph {\n");
680 fprintf (file, " node [\n shape = box\n ]\n");
681 fprintf (file, " edge [\n fontsize = \"12\"\n ]\n");
682 fprintf (file, "\n // List of nodes in the constraint graph:\n");
684 /* The next lines print the nodes in the graph. In order to get the
685 number of nodes in the graph, we must choose the minimum between the
686 vector VEC (varinfo_t, varmap) and graph->size. If the graph has not
687 yet been initialized, then graph->size == 0, otherwise we must only
688 read nodes that have an entry in VEC (varinfo_t, varmap). */
689 size = VEC_length (varinfo_t, varmap);
690 size = size < graph->size ? size : graph->size;
691 for (i = 0; i < size; i++)
693 const char *name = get_varinfo (graph->rep[i])->name;
694 fprintf (file, " \"%s\" ;\n", name);
697 /* Go over the list of constraints printing the edges in the constraint
698 graph. */
699 fprintf (file, "\n // The constraint edges:\n");
700 for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
701 if (c)
702 dump_constraint_edge (file, c);
704 /* Prints the tail of the dot file. By now, only the closing bracket. */
705 fprintf (file, "}\n\n\n");
708 /* Print out the constraint graph to stderr. */
710 void
711 debug_constraint_graph (void)
713 dump_constraint_graph (stderr);
716 /* SOLVER FUNCTIONS
718 The solver is a simple worklist solver, that works on the following
719 algorithm:
721 sbitmap changed_nodes = all zeroes;
722 changed_count = 0;
723 For each node that is not already collapsed:
724 changed_count++;
725 set bit in changed nodes
727 while (changed_count > 0)
729 compute topological ordering for constraint graph
731 find and collapse cycles in the constraint graph (updating
732 changed if necessary)
734 for each node (n) in the graph in topological order:
735 changed_count--;
737 Process each complex constraint associated with the node,
738 updating changed if necessary.
740 For each outgoing edge from n, propagate the solution from n to
741 the destination of the edge, updating changed as necessary.
743 } */
745 /* Return true if two constraint expressions A and B are equal. */
747 static bool
748 constraint_expr_equal (struct constraint_expr a, struct constraint_expr b)
750 return a.type == b.type && a.var == b.var && a.offset == b.offset;
753 /* Return true if constraint expression A is less than constraint expression
754 B. This is just arbitrary, but consistent, in order to give them an
755 ordering. */
757 static bool
758 constraint_expr_less (struct constraint_expr a, struct constraint_expr b)
760 if (a.type == b.type)
762 if (a.var == b.var)
763 return a.offset < b.offset;
764 else
765 return a.var < b.var;
767 else
768 return a.type < b.type;
771 /* Return true if constraint A is less than constraint B. This is just
772 arbitrary, but consistent, in order to give them an ordering. */
774 static bool
775 constraint_less (const constraint_t a, const constraint_t b)
777 if (constraint_expr_less (a->lhs, b->lhs))
778 return true;
779 else if (constraint_expr_less (b->lhs, a->lhs))
780 return false;
781 else
782 return constraint_expr_less (a->rhs, b->rhs);
785 /* Return true if two constraints A and B are equal. */
787 static bool
788 constraint_equal (struct constraint a, struct constraint b)
790 return constraint_expr_equal (a.lhs, b.lhs)
791 && constraint_expr_equal (a.rhs, b.rhs);
795 /* Find a constraint LOOKFOR in the sorted constraint vector VEC */
797 static constraint_t
798 constraint_vec_find (VEC(constraint_t,heap) *vec,
799 struct constraint lookfor)
801 unsigned int place;
802 constraint_t found;
804 if (vec == NULL)
805 return NULL;
807 place = VEC_lower_bound (constraint_t, vec, &lookfor, constraint_less);
808 if (place >= VEC_length (constraint_t, vec))
809 return NULL;
810 found = VEC_index (constraint_t, vec, place);
811 if (!constraint_equal (*found, lookfor))
812 return NULL;
813 return found;
816 /* Union two constraint vectors, TO and FROM. Put the result in TO. */
818 static void
819 constraint_set_union (VEC(constraint_t,heap) **to,
820 VEC(constraint_t,heap) **from)
822 int i;
823 constraint_t c;
825 for (i = 0; VEC_iterate (constraint_t, *from, i, c); i++)
827 if (constraint_vec_find (*to, *c) == NULL)
829 unsigned int place = VEC_lower_bound (constraint_t, *to, c,
830 constraint_less);
831 VEC_safe_insert (constraint_t, heap, *to, place, c);
836 /* Expands the solution in SET to all sub-fields of variables included.
837 Union the expanded result into RESULT. */
839 static void
840 solution_set_expand (bitmap result, bitmap set)
842 bitmap_iterator bi;
843 bitmap vars = NULL;
844 unsigned j;
846 /* In a first pass record all variables we need to add all
847 sub-fields off. This avoids quadratic behavior. */
848 EXECUTE_IF_SET_IN_BITMAP (set, 0, j, bi)
850 varinfo_t v = get_varinfo (j);
851 if (v->is_artificial_var
852 || v->is_full_var)
853 continue;
854 v = lookup_vi_for_tree (v->decl);
855 if (vars == NULL)
856 vars = BITMAP_ALLOC (NULL);
857 bitmap_set_bit (vars, v->id);
860 /* In the second pass now do the addition to the solution and
861 to speed up solving add it to the delta as well. */
862 if (vars != NULL)
864 EXECUTE_IF_SET_IN_BITMAP (vars, 0, j, bi)
866 varinfo_t v = get_varinfo (j);
867 for (; v != NULL; v = v->next)
868 bitmap_set_bit (result, v->id);
870 BITMAP_FREE (vars);
874 /* Take a solution set SET, add OFFSET to each member of the set, and
875 overwrite SET with the result when done. */
877 static void
878 solution_set_add (bitmap set, HOST_WIDE_INT offset)
880 bitmap result = BITMAP_ALLOC (&iteration_obstack);
881 unsigned int i;
882 bitmap_iterator bi;
884 /* If the offset is unknown we have to expand the solution to
885 all subfields. */
886 if (offset == UNKNOWN_OFFSET)
888 solution_set_expand (set, set);
889 return;
892 EXECUTE_IF_SET_IN_BITMAP (set, 0, i, bi)
894 varinfo_t vi = get_varinfo (i);
896 /* If this is a variable with just one field just set its bit
897 in the result. */
898 if (vi->is_artificial_var
899 || vi->is_unknown_size_var
900 || vi->is_full_var)
901 bitmap_set_bit (result, i);
902 else
904 unsigned HOST_WIDE_INT fieldoffset = vi->offset + offset;
906 /* If the offset makes the pointer point to before the
907 variable use offset zero for the field lookup. */
908 if (offset < 0
909 && fieldoffset > vi->offset)
910 fieldoffset = 0;
912 if (offset != 0)
913 vi = first_or_preceding_vi_for_offset (vi, fieldoffset);
915 bitmap_set_bit (result, vi->id);
916 /* If the result is not exactly at fieldoffset include the next
917 field as well. See get_constraint_for_ptr_offset for more
918 rationale. */
919 if (vi->offset != fieldoffset
920 && vi->next != NULL)
921 bitmap_set_bit (result, vi->next->id);
925 bitmap_copy (set, result);
926 BITMAP_FREE (result);
929 /* Union solution sets TO and FROM, and add INC to each member of FROM in the
930 process. */
932 static bool
933 set_union_with_increment (bitmap to, bitmap from, HOST_WIDE_INT inc)
935 if (inc == 0)
936 return bitmap_ior_into (to, from);
937 else
939 bitmap tmp;
940 bool res;
942 tmp = BITMAP_ALLOC (&iteration_obstack);
943 bitmap_copy (tmp, from);
944 solution_set_add (tmp, inc);
945 res = bitmap_ior_into (to, tmp);
946 BITMAP_FREE (tmp);
947 return res;
951 /* Insert constraint C into the list of complex constraints for graph
952 node VAR. */
954 static void
955 insert_into_complex (constraint_graph_t graph,
956 unsigned int var, constraint_t c)
958 VEC (constraint_t, heap) *complex = graph->complex[var];
959 unsigned int place = VEC_lower_bound (constraint_t, complex, c,
960 constraint_less);
962 /* Only insert constraints that do not already exist. */
963 if (place >= VEC_length (constraint_t, complex)
964 || !constraint_equal (*c, *VEC_index (constraint_t, complex, place)))
965 VEC_safe_insert (constraint_t, heap, graph->complex[var], place, c);
969 /* Condense two variable nodes into a single variable node, by moving
970 all associated info from SRC to TO. */
972 static void
973 merge_node_constraints (constraint_graph_t graph, unsigned int to,
974 unsigned int from)
976 unsigned int i;
977 constraint_t c;
979 gcc_assert (find (from) == to);
981 /* Move all complex constraints from src node into to node */
982 for (i = 0; VEC_iterate (constraint_t, graph->complex[from], i, c); i++)
984 /* In complex constraints for node src, we may have either
985 a = *src, and *src = a, or an offseted constraint which are
986 always added to the rhs node's constraints. */
988 if (c->rhs.type == DEREF)
989 c->rhs.var = to;
990 else if (c->lhs.type == DEREF)
991 c->lhs.var = to;
992 else
993 c->rhs.var = to;
995 constraint_set_union (&graph->complex[to], &graph->complex[from]);
996 VEC_free (constraint_t, heap, graph->complex[from]);
997 graph->complex[from] = NULL;
1001 /* Remove edges involving NODE from GRAPH. */
1003 static void
1004 clear_edges_for_node (constraint_graph_t graph, unsigned int node)
1006 if (graph->succs[node])
1007 BITMAP_FREE (graph->succs[node]);
1010 /* Merge GRAPH nodes FROM and TO into node TO. */
1012 static void
1013 merge_graph_nodes (constraint_graph_t graph, unsigned int to,
1014 unsigned int from)
1016 if (graph->indirect_cycles[from] != -1)
1018 /* If we have indirect cycles with the from node, and we have
1019 none on the to node, the to node has indirect cycles from the
1020 from node now that they are unified.
1021 If indirect cycles exist on both, unify the nodes that they
1022 are in a cycle with, since we know they are in a cycle with
1023 each other. */
1024 if (graph->indirect_cycles[to] == -1)
1025 graph->indirect_cycles[to] = graph->indirect_cycles[from];
1028 /* Merge all the successor edges. */
1029 if (graph->succs[from])
1031 if (!graph->succs[to])
1032 graph->succs[to] = BITMAP_ALLOC (&pta_obstack);
1033 bitmap_ior_into (graph->succs[to],
1034 graph->succs[from]);
1037 clear_edges_for_node (graph, from);
1041 /* Add an indirect graph edge to GRAPH, going from TO to FROM if
1042 it doesn't exist in the graph already. */
1044 static void
1045 add_implicit_graph_edge (constraint_graph_t graph, unsigned int to,
1046 unsigned int from)
1048 if (to == from)
1049 return;
1051 if (!graph->implicit_preds[to])
1052 graph->implicit_preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1054 if (bitmap_set_bit (graph->implicit_preds[to], from))
1055 stats.num_implicit_edges++;
1058 /* Add a predecessor graph edge to GRAPH, going from TO to FROM if
1059 it doesn't exist in the graph already.
1060 Return false if the edge already existed, true otherwise. */
1062 static void
1063 add_pred_graph_edge (constraint_graph_t graph, unsigned int to,
1064 unsigned int from)
1066 if (!graph->preds[to])
1067 graph->preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1068 bitmap_set_bit (graph->preds[to], from);
1071 /* Add a graph edge to GRAPH, going from FROM to TO if
1072 it doesn't exist in the graph already.
1073 Return false if the edge already existed, true otherwise. */
1075 static bool
1076 add_graph_edge (constraint_graph_t graph, unsigned int to,
1077 unsigned int from)
1079 if (to == from)
1081 return false;
1083 else
1085 bool r = false;
1087 if (!graph->succs[from])
1088 graph->succs[from] = BITMAP_ALLOC (&pta_obstack);
1089 if (bitmap_set_bit (graph->succs[from], to))
1091 r = true;
1092 if (to < FIRST_REF_NODE && from < FIRST_REF_NODE)
1093 stats.num_edges++;
1095 return r;
1100 /* Return true if {DEST.SRC} is an existing graph edge in GRAPH. */
1102 static bool
1103 valid_graph_edge (constraint_graph_t graph, unsigned int src,
1104 unsigned int dest)
1106 return (graph->succs[dest]
1107 && bitmap_bit_p (graph->succs[dest], src));
1110 /* Initialize the constraint graph structure to contain SIZE nodes. */
1112 static void
1113 init_graph (unsigned int size)
1115 unsigned int j;
1117 graph = XCNEW (struct constraint_graph);
1118 graph->size = size;
1119 graph->succs = XCNEWVEC (bitmap, graph->size);
1120 graph->indirect_cycles = XNEWVEC (int, graph->size);
1121 graph->rep = XNEWVEC (unsigned int, graph->size);
1122 graph->complex = XCNEWVEC (VEC(constraint_t, heap) *, size);
1123 graph->pe = XCNEWVEC (unsigned int, graph->size);
1124 graph->pe_rep = XNEWVEC (int, graph->size);
1126 for (j = 0; j < graph->size; j++)
1128 graph->rep[j] = j;
1129 graph->pe_rep[j] = -1;
1130 graph->indirect_cycles[j] = -1;
1134 /* Build the constraint graph, adding only predecessor edges right now. */
1136 static void
1137 build_pred_graph (void)
1139 int i;
1140 constraint_t c;
1141 unsigned int j;
1143 graph->implicit_preds = XCNEWVEC (bitmap, graph->size);
1144 graph->preds = XCNEWVEC (bitmap, graph->size);
1145 graph->pointer_label = XCNEWVEC (unsigned int, graph->size);
1146 graph->loc_label = XCNEWVEC (unsigned int, graph->size);
1147 graph->pointed_by = XCNEWVEC (bitmap, graph->size);
1148 graph->points_to = XCNEWVEC (bitmap, graph->size);
1149 graph->eq_rep = XNEWVEC (int, graph->size);
1150 graph->direct_nodes = sbitmap_alloc (graph->size);
1151 graph->address_taken = BITMAP_ALLOC (&predbitmap_obstack);
1152 sbitmap_zero (graph->direct_nodes);
1154 for (j = 0; j < FIRST_REF_NODE; j++)
1156 if (!get_varinfo (j)->is_special_var)
1157 SET_BIT (graph->direct_nodes, j);
1160 for (j = 0; j < graph->size; j++)
1161 graph->eq_rep[j] = -1;
1163 for (j = 0; j < VEC_length (varinfo_t, varmap); j++)
1164 graph->indirect_cycles[j] = -1;
1166 for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
1168 struct constraint_expr lhs = c->lhs;
1169 struct constraint_expr rhs = c->rhs;
1170 unsigned int lhsvar = lhs.var;
1171 unsigned int rhsvar = rhs.var;
1173 if (lhs.type == DEREF)
1175 /* *x = y. */
1176 if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1177 add_pred_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1179 else if (rhs.type == DEREF)
1181 /* x = *y */
1182 if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1183 add_pred_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1184 else
1185 RESET_BIT (graph->direct_nodes, lhsvar);
1187 else if (rhs.type == ADDRESSOF)
1189 varinfo_t v;
1191 /* x = &y */
1192 if (graph->points_to[lhsvar] == NULL)
1193 graph->points_to[lhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1194 bitmap_set_bit (graph->points_to[lhsvar], rhsvar);
1196 if (graph->pointed_by[rhsvar] == NULL)
1197 graph->pointed_by[rhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1198 bitmap_set_bit (graph->pointed_by[rhsvar], lhsvar);
1200 /* Implicitly, *x = y */
1201 add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1203 /* All related variables are no longer direct nodes. */
1204 RESET_BIT (graph->direct_nodes, rhsvar);
1205 v = get_varinfo (rhsvar);
1206 if (!v->is_full_var)
1208 v = lookup_vi_for_tree (v->decl);
1211 RESET_BIT (graph->direct_nodes, v->id);
1212 v = v->next;
1214 while (v != NULL);
1216 bitmap_set_bit (graph->address_taken, rhsvar);
1218 else if (lhsvar > anything_id
1219 && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1221 /* x = y */
1222 add_pred_graph_edge (graph, lhsvar, rhsvar);
1223 /* Implicitly, *x = *y */
1224 add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar,
1225 FIRST_REF_NODE + rhsvar);
1227 else if (lhs.offset != 0 || rhs.offset != 0)
1229 if (rhs.offset != 0)
1230 RESET_BIT (graph->direct_nodes, lhs.var);
1231 else if (lhs.offset != 0)
1232 RESET_BIT (graph->direct_nodes, rhs.var);
1237 /* Build the constraint graph, adding successor edges. */
1239 static void
1240 build_succ_graph (void)
1242 unsigned i, t;
1243 constraint_t c;
1245 for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
1247 struct constraint_expr lhs;
1248 struct constraint_expr rhs;
1249 unsigned int lhsvar;
1250 unsigned int rhsvar;
1252 if (!c)
1253 continue;
1255 lhs = c->lhs;
1256 rhs = c->rhs;
1257 lhsvar = find (lhs.var);
1258 rhsvar = find (rhs.var);
1260 if (lhs.type == DEREF)
1262 if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1263 add_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1265 else if (rhs.type == DEREF)
1267 if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1268 add_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1270 else if (rhs.type == ADDRESSOF)
1272 /* x = &y */
1273 gcc_assert (find (rhs.var) == rhs.var);
1274 bitmap_set_bit (get_varinfo (lhsvar)->solution, rhsvar);
1276 else if (lhsvar > anything_id
1277 && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1279 add_graph_edge (graph, lhsvar, rhsvar);
1283 /* Add edges from STOREDANYTHING to all non-direct nodes. */
1284 t = find (storedanything_id);
1285 for (i = integer_id + 1; i < FIRST_REF_NODE; ++i)
1287 if (!TEST_BIT (graph->direct_nodes, i))
1288 add_graph_edge (graph, find (i), t);
1293 /* Changed variables on the last iteration. */
1294 static unsigned int changed_count;
1295 static sbitmap changed;
1297 DEF_VEC_I(unsigned);
1298 DEF_VEC_ALLOC_I(unsigned,heap);
1301 /* Strongly Connected Component visitation info. */
1303 struct scc_info
1305 sbitmap visited;
1306 sbitmap deleted;
1307 unsigned int *dfs;
1308 unsigned int *node_mapping;
1309 int current_index;
1310 VEC(unsigned,heap) *scc_stack;
1314 /* Recursive routine to find strongly connected components in GRAPH.
1315 SI is the SCC info to store the information in, and N is the id of current
1316 graph node we are processing.
1318 This is Tarjan's strongly connected component finding algorithm, as
1319 modified by Nuutila to keep only non-root nodes on the stack.
1320 The algorithm can be found in "On finding the strongly connected
1321 connected components in a directed graph" by Esko Nuutila and Eljas
1322 Soisalon-Soininen, in Information Processing Letters volume 49,
1323 number 1, pages 9-14. */
1325 static void
1326 scc_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1328 unsigned int i;
1329 bitmap_iterator bi;
1330 unsigned int my_dfs;
1332 SET_BIT (si->visited, n);
1333 si->dfs[n] = si->current_index ++;
1334 my_dfs = si->dfs[n];
1336 /* Visit all the successors. */
1337 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[n], 0, i, bi)
1339 unsigned int w;
1341 if (i > LAST_REF_NODE)
1342 break;
1344 w = find (i);
1345 if (TEST_BIT (si->deleted, w))
1346 continue;
1348 if (!TEST_BIT (si->visited, w))
1349 scc_visit (graph, si, w);
1351 unsigned int t = find (w);
1352 unsigned int nnode = find (n);
1353 gcc_assert (nnode == n);
1355 if (si->dfs[t] < si->dfs[nnode])
1356 si->dfs[n] = si->dfs[t];
1360 /* See if any components have been identified. */
1361 if (si->dfs[n] == my_dfs)
1363 if (VEC_length (unsigned, si->scc_stack) > 0
1364 && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
1366 bitmap scc = BITMAP_ALLOC (NULL);
1367 bool have_ref_node = n >= FIRST_REF_NODE;
1368 unsigned int lowest_node;
1369 bitmap_iterator bi;
1371 bitmap_set_bit (scc, n);
1373 while (VEC_length (unsigned, si->scc_stack) != 0
1374 && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
1376 unsigned int w = VEC_pop (unsigned, si->scc_stack);
1378 bitmap_set_bit (scc, w);
1379 if (w >= FIRST_REF_NODE)
1380 have_ref_node = true;
1383 lowest_node = bitmap_first_set_bit (scc);
1384 gcc_assert (lowest_node < FIRST_REF_NODE);
1386 /* Collapse the SCC nodes into a single node, and mark the
1387 indirect cycles. */
1388 EXECUTE_IF_SET_IN_BITMAP (scc, 0, i, bi)
1390 if (i < FIRST_REF_NODE)
1392 if (unite (lowest_node, i))
1393 unify_nodes (graph, lowest_node, i, false);
1395 else
1397 unite (lowest_node, i);
1398 graph->indirect_cycles[i - FIRST_REF_NODE] = lowest_node;
1402 SET_BIT (si->deleted, n);
1404 else
1405 VEC_safe_push (unsigned, heap, si->scc_stack, n);
1408 /* Unify node FROM into node TO, updating the changed count if
1409 necessary when UPDATE_CHANGED is true. */
1411 static void
1412 unify_nodes (constraint_graph_t graph, unsigned int to, unsigned int from,
1413 bool update_changed)
1416 gcc_assert (to != from && find (to) == to);
1417 if (dump_file && (dump_flags & TDF_DETAILS))
1418 fprintf (dump_file, "Unifying %s to %s\n",
1419 get_varinfo (from)->name,
1420 get_varinfo (to)->name);
1422 if (update_changed)
1423 stats.unified_vars_dynamic++;
1424 else
1425 stats.unified_vars_static++;
1427 merge_graph_nodes (graph, to, from);
1428 merge_node_constraints (graph, to, from);
1430 if (get_varinfo (from)->no_tbaa_pruning)
1431 get_varinfo (to)->no_tbaa_pruning = true;
1433 /* Mark TO as changed if FROM was changed. If TO was already marked
1434 as changed, decrease the changed count. */
1436 if (update_changed && TEST_BIT (changed, from))
1438 RESET_BIT (changed, from);
1439 if (!TEST_BIT (changed, to))
1440 SET_BIT (changed, to);
1441 else
1443 gcc_assert (changed_count > 0);
1444 changed_count--;
1447 if (get_varinfo (from)->solution)
1449 /* If the solution changes because of the merging, we need to mark
1450 the variable as changed. */
1451 if (bitmap_ior_into (get_varinfo (to)->solution,
1452 get_varinfo (from)->solution))
1454 if (update_changed && !TEST_BIT (changed, to))
1456 SET_BIT (changed, to);
1457 changed_count++;
1461 BITMAP_FREE (get_varinfo (from)->solution);
1462 BITMAP_FREE (get_varinfo (from)->oldsolution);
1464 if (stats.iterations > 0)
1466 BITMAP_FREE (get_varinfo (to)->oldsolution);
1467 get_varinfo (to)->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
1470 if (valid_graph_edge (graph, to, to))
1472 if (graph->succs[to])
1473 bitmap_clear_bit (graph->succs[to], to);
1477 /* Information needed to compute the topological ordering of a graph. */
1479 struct topo_info
1481 /* sbitmap of visited nodes. */
1482 sbitmap visited;
1483 /* Array that stores the topological order of the graph, *in
1484 reverse*. */
1485 VEC(unsigned,heap) *topo_order;
1489 /* Initialize and return a topological info structure. */
1491 static struct topo_info *
1492 init_topo_info (void)
1494 size_t size = graph->size;
1495 struct topo_info *ti = XNEW (struct topo_info);
1496 ti->visited = sbitmap_alloc (size);
1497 sbitmap_zero (ti->visited);
1498 ti->topo_order = VEC_alloc (unsigned, heap, 1);
1499 return ti;
1503 /* Free the topological sort info pointed to by TI. */
1505 static void
1506 free_topo_info (struct topo_info *ti)
1508 sbitmap_free (ti->visited);
1509 VEC_free (unsigned, heap, ti->topo_order);
1510 free (ti);
1513 /* Visit the graph in topological order, and store the order in the
1514 topo_info structure. */
1516 static void
1517 topo_visit (constraint_graph_t graph, struct topo_info *ti,
1518 unsigned int n)
1520 bitmap_iterator bi;
1521 unsigned int j;
1523 SET_BIT (ti->visited, n);
1525 if (graph->succs[n])
1526 EXECUTE_IF_SET_IN_BITMAP (graph->succs[n], 0, j, bi)
1528 if (!TEST_BIT (ti->visited, j))
1529 topo_visit (graph, ti, j);
1532 VEC_safe_push (unsigned, heap, ti->topo_order, n);
1535 /* Process a constraint C that represents x = *(y + off), using DELTA as the
1536 starting solution for y. */
1538 static void
1539 do_sd_constraint (constraint_graph_t graph, constraint_t c,
1540 bitmap delta)
1542 unsigned int lhs = c->lhs.var;
1543 bool flag = false;
1544 bitmap sol = get_varinfo (lhs)->solution;
1545 unsigned int j;
1546 bitmap_iterator bi;
1547 HOST_WIDE_INT roffset = c->rhs.offset;
1549 /* Our IL does not allow this. */
1550 gcc_assert (c->lhs.offset == 0);
1552 /* If the solution of Y contains anything it is good enough to transfer
1553 this to the LHS. */
1554 if (bitmap_bit_p (delta, anything_id))
1556 flag |= bitmap_set_bit (sol, anything_id);
1557 goto done;
1560 /* If we do not know at with offset the rhs is dereferenced compute
1561 the reachability set of DELTA, conservatively assuming it is
1562 dereferenced at all valid offsets. */
1563 if (roffset == UNKNOWN_OFFSET)
1565 solution_set_expand (delta, delta);
1566 /* No further offset processing is necessary. */
1567 roffset = 0;
1570 /* For each variable j in delta (Sol(y)), add
1571 an edge in the graph from j to x, and union Sol(j) into Sol(x). */
1572 EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1574 varinfo_t v = get_varinfo (j);
1575 HOST_WIDE_INT fieldoffset = v->offset + roffset;
1576 unsigned int t;
1578 if (v->is_full_var)
1579 fieldoffset = v->offset;
1580 else if (roffset != 0)
1581 v = first_vi_for_offset (v, fieldoffset);
1582 /* If the access is outside of the variable we can ignore it. */
1583 if (!v)
1584 continue;
1588 t = find (v->id);
1590 /* Adding edges from the special vars is pointless.
1591 They don't have sets that can change. */
1592 if (get_varinfo (t)->is_special_var)
1593 flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1594 /* Merging the solution from ESCAPED needlessly increases
1595 the set. Use ESCAPED as representative instead. */
1596 else if (v->id == escaped_id)
1597 flag |= bitmap_set_bit (sol, escaped_id);
1598 else if (add_graph_edge (graph, lhs, t))
1599 flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1601 /* If the variable is not exactly at the requested offset
1602 we have to include the next one. */
1603 if (v->offset == (unsigned HOST_WIDE_INT)fieldoffset
1604 || v->next == NULL)
1605 break;
1607 v = v->next;
1608 fieldoffset = v->offset;
1610 while (1);
1613 done:
1614 /* If the LHS solution changed, mark the var as changed. */
1615 if (flag)
1617 get_varinfo (lhs)->solution = sol;
1618 if (!TEST_BIT (changed, lhs))
1620 SET_BIT (changed, lhs);
1621 changed_count++;
1626 /* Process a constraint C that represents *(x + off) = y using DELTA
1627 as the starting solution for x. */
1629 static void
1630 do_ds_constraint (constraint_t c, bitmap delta)
1632 unsigned int rhs = c->rhs.var;
1633 bitmap sol = get_varinfo (rhs)->solution;
1634 unsigned int j;
1635 bitmap_iterator bi;
1636 HOST_WIDE_INT loff = c->lhs.offset;
1638 /* Our IL does not allow this. */
1639 gcc_assert (c->rhs.offset == 0);
1641 /* If the solution of y contains ANYTHING simply use the ANYTHING
1642 solution. This avoids needlessly increasing the points-to sets. */
1643 if (bitmap_bit_p (sol, anything_id))
1644 sol = get_varinfo (find (anything_id))->solution;
1646 /* If the solution for x contains ANYTHING we have to merge the
1647 solution of y into all pointer variables which we do via
1648 STOREDANYTHING. */
1649 if (bitmap_bit_p (delta, anything_id))
1651 unsigned t = find (storedanything_id);
1652 if (add_graph_edge (graph, t, rhs))
1654 if (bitmap_ior_into (get_varinfo (t)->solution, sol))
1656 if (!TEST_BIT (changed, t))
1658 SET_BIT (changed, t);
1659 changed_count++;
1663 return;
1666 /* If we do not know at with offset the rhs is dereferenced compute
1667 the reachability set of DELTA, conservatively assuming it is
1668 dereferenced at all valid offsets. */
1669 if (loff == UNKNOWN_OFFSET)
1671 solution_set_expand (delta, delta);
1672 loff = 0;
1675 /* For each member j of delta (Sol(x)), add an edge from y to j and
1676 union Sol(y) into Sol(j) */
1677 EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1679 varinfo_t v = get_varinfo (j);
1680 unsigned int t;
1681 HOST_WIDE_INT fieldoffset = v->offset + loff;
1683 if (v->is_special_var)
1684 continue;
1686 if (v->is_full_var)
1687 fieldoffset = v->offset;
1688 else if (loff != 0)
1689 v = first_vi_for_offset (v, fieldoffset);
1690 /* If the access is outside of the variable we can ignore it. */
1691 if (!v)
1692 continue;
1696 if (v->may_have_pointers)
1698 t = find (v->id);
1699 if (add_graph_edge (graph, t, rhs))
1701 if (bitmap_ior_into (get_varinfo (t)->solution, sol))
1703 if (t == rhs)
1704 sol = get_varinfo (rhs)->solution;
1705 if (!TEST_BIT (changed, t))
1707 SET_BIT (changed, t);
1708 changed_count++;
1714 /* If the variable is not exactly at the requested offset
1715 we have to include the next one. */
1716 if (v->offset == (unsigned HOST_WIDE_INT)fieldoffset
1717 || v->next == NULL)
1718 break;
1720 v = v->next;
1721 fieldoffset = v->offset;
1723 while (1);
1727 /* Handle a non-simple (simple meaning requires no iteration),
1728 constraint (IE *x = &y, x = *y, *x = y, and x = y with offsets involved). */
1730 static void
1731 do_complex_constraint (constraint_graph_t graph, constraint_t c, bitmap delta)
1733 if (c->lhs.type == DEREF)
1735 if (c->rhs.type == ADDRESSOF)
1737 gcc_unreachable();
1739 else
1741 /* *x = y */
1742 do_ds_constraint (c, delta);
1745 else if (c->rhs.type == DEREF)
1747 /* x = *y */
1748 if (!(get_varinfo (c->lhs.var)->is_special_var))
1749 do_sd_constraint (graph, c, delta);
1751 else
1753 bitmap tmp;
1754 bitmap solution;
1755 bool flag = false;
1757 gcc_assert (c->rhs.type == SCALAR && c->lhs.type == SCALAR);
1758 solution = get_varinfo (c->rhs.var)->solution;
1759 tmp = get_varinfo (c->lhs.var)->solution;
1761 flag = set_union_with_increment (tmp, solution, c->rhs.offset);
1763 if (flag)
1765 get_varinfo (c->lhs.var)->solution = tmp;
1766 if (!TEST_BIT (changed, c->lhs.var))
1768 SET_BIT (changed, c->lhs.var);
1769 changed_count++;
1775 /* Initialize and return a new SCC info structure. */
1777 static struct scc_info *
1778 init_scc_info (size_t size)
1780 struct scc_info *si = XNEW (struct scc_info);
1781 size_t i;
1783 si->current_index = 0;
1784 si->visited = sbitmap_alloc (size);
1785 sbitmap_zero (si->visited);
1786 si->deleted = sbitmap_alloc (size);
1787 sbitmap_zero (si->deleted);
1788 si->node_mapping = XNEWVEC (unsigned int, size);
1789 si->dfs = XCNEWVEC (unsigned int, size);
1791 for (i = 0; i < size; i++)
1792 si->node_mapping[i] = i;
1794 si->scc_stack = VEC_alloc (unsigned, heap, 1);
1795 return si;
1798 /* Free an SCC info structure pointed to by SI */
1800 static void
1801 free_scc_info (struct scc_info *si)
1803 sbitmap_free (si->visited);
1804 sbitmap_free (si->deleted);
1805 free (si->node_mapping);
1806 free (si->dfs);
1807 VEC_free (unsigned, heap, si->scc_stack);
1808 free (si);
1812 /* Find indirect cycles in GRAPH that occur, using strongly connected
1813 components, and note them in the indirect cycles map.
1815 This technique comes from Ben Hardekopf and Calvin Lin,
1816 "It Pays to be Lazy: Fast and Accurate Pointer Analysis for Millions of
1817 Lines of Code", submitted to PLDI 2007. */
1819 static void
1820 find_indirect_cycles (constraint_graph_t graph)
1822 unsigned int i;
1823 unsigned int size = graph->size;
1824 struct scc_info *si = init_scc_info (size);
1826 for (i = 0; i < MIN (LAST_REF_NODE, size); i ++ )
1827 if (!TEST_BIT (si->visited, i) && find (i) == i)
1828 scc_visit (graph, si, i);
1830 free_scc_info (si);
1833 /* Compute a topological ordering for GRAPH, and store the result in the
1834 topo_info structure TI. */
1836 static void
1837 compute_topo_order (constraint_graph_t graph,
1838 struct topo_info *ti)
1840 unsigned int i;
1841 unsigned int size = graph->size;
1843 for (i = 0; i != size; ++i)
1844 if (!TEST_BIT (ti->visited, i) && find (i) == i)
1845 topo_visit (graph, ti, i);
1848 /* Structure used to for hash value numbering of pointer equivalence
1849 classes. */
1851 typedef struct equiv_class_label
1853 hashval_t hashcode;
1854 unsigned int equivalence_class;
1855 bitmap labels;
1856 } *equiv_class_label_t;
1857 typedef const struct equiv_class_label *const_equiv_class_label_t;
1859 /* A hashtable for mapping a bitmap of labels->pointer equivalence
1860 classes. */
1861 static htab_t pointer_equiv_class_table;
1863 /* A hashtable for mapping a bitmap of labels->location equivalence
1864 classes. */
1865 static htab_t location_equiv_class_table;
1867 /* Hash function for a equiv_class_label_t */
1869 static hashval_t
1870 equiv_class_label_hash (const void *p)
1872 const_equiv_class_label_t const ecl = (const_equiv_class_label_t) p;
1873 return ecl->hashcode;
1876 /* Equality function for two equiv_class_label_t's. */
1878 static int
1879 equiv_class_label_eq (const void *p1, const void *p2)
1881 const_equiv_class_label_t const eql1 = (const_equiv_class_label_t) p1;
1882 const_equiv_class_label_t const eql2 = (const_equiv_class_label_t) p2;
1883 return bitmap_equal_p (eql1->labels, eql2->labels);
1886 /* Lookup a equivalence class in TABLE by the bitmap of LABELS it
1887 contains. */
1889 static unsigned int
1890 equiv_class_lookup (htab_t table, bitmap labels)
1892 void **slot;
1893 struct equiv_class_label ecl;
1895 ecl.labels = labels;
1896 ecl.hashcode = bitmap_hash (labels);
1898 slot = htab_find_slot_with_hash (table, &ecl,
1899 ecl.hashcode, NO_INSERT);
1900 if (!slot)
1901 return 0;
1902 else
1903 return ((equiv_class_label_t) *slot)->equivalence_class;
1907 /* Add an equivalence class named EQUIVALENCE_CLASS with labels LABELS
1908 to TABLE. */
1910 static void
1911 equiv_class_add (htab_t table, unsigned int equivalence_class,
1912 bitmap labels)
1914 void **slot;
1915 equiv_class_label_t ecl = XNEW (struct equiv_class_label);
1917 ecl->labels = labels;
1918 ecl->equivalence_class = equivalence_class;
1919 ecl->hashcode = bitmap_hash (labels);
1921 slot = htab_find_slot_with_hash (table, ecl,
1922 ecl->hashcode, INSERT);
1923 gcc_assert (!*slot);
1924 *slot = (void *) ecl;
1927 /* Perform offline variable substitution.
1929 This is a worst case quadratic time way of identifying variables
1930 that must have equivalent points-to sets, including those caused by
1931 static cycles, and single entry subgraphs, in the constraint graph.
1933 The technique is described in "Exploiting Pointer and Location
1934 Equivalence to Optimize Pointer Analysis. In the 14th International
1935 Static Analysis Symposium (SAS), August 2007." It is known as the
1936 "HU" algorithm, and is equivalent to value numbering the collapsed
1937 constraint graph including evaluating unions.
1939 The general method of finding equivalence classes is as follows:
1940 Add fake nodes (REF nodes) and edges for *a = b and a = *b constraints.
1941 Initialize all non-REF nodes to be direct nodes.
1942 For each constraint a = a U {b}, we set pts(a) = pts(a) u {fresh
1943 variable}
1944 For each constraint containing the dereference, we also do the same
1945 thing.
1947 We then compute SCC's in the graph and unify nodes in the same SCC,
1948 including pts sets.
1950 For each non-collapsed node x:
1951 Visit all unvisited explicit incoming edges.
1952 Ignoring all non-pointers, set pts(x) = Union of pts(a) for y
1953 where y->x.
1954 Lookup the equivalence class for pts(x).
1955 If we found one, equivalence_class(x) = found class.
1956 Otherwise, equivalence_class(x) = new class, and new_class is
1957 added to the lookup table.
1959 All direct nodes with the same equivalence class can be replaced
1960 with a single representative node.
1961 All unlabeled nodes (label == 0) are not pointers and all edges
1962 involving them can be eliminated.
1963 We perform these optimizations during rewrite_constraints
1965 In addition to pointer equivalence class finding, we also perform
1966 location equivalence class finding. This is the set of variables
1967 that always appear together in points-to sets. We use this to
1968 compress the size of the points-to sets. */
1970 /* Current maximum pointer equivalence class id. */
1971 static int pointer_equiv_class;
1973 /* Current maximum location equivalence class id. */
1974 static int location_equiv_class;
1976 /* Recursive routine to find strongly connected components in GRAPH,
1977 and label it's nodes with DFS numbers. */
1979 static void
1980 condense_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1982 unsigned int i;
1983 bitmap_iterator bi;
1984 unsigned int my_dfs;
1986 gcc_assert (si->node_mapping[n] == n);
1987 SET_BIT (si->visited, n);
1988 si->dfs[n] = si->current_index ++;
1989 my_dfs = si->dfs[n];
1991 /* Visit all the successors. */
1992 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
1994 unsigned int w = si->node_mapping[i];
1996 if (TEST_BIT (si->deleted, w))
1997 continue;
1999 if (!TEST_BIT (si->visited, w))
2000 condense_visit (graph, si, w);
2002 unsigned int t = si->node_mapping[w];
2003 unsigned int nnode = si->node_mapping[n];
2004 gcc_assert (nnode == n);
2006 if (si->dfs[t] < si->dfs[nnode])
2007 si->dfs[n] = si->dfs[t];
2011 /* Visit all the implicit predecessors. */
2012 EXECUTE_IF_IN_NONNULL_BITMAP (graph->implicit_preds[n], 0, i, bi)
2014 unsigned int w = si->node_mapping[i];
2016 if (TEST_BIT (si->deleted, w))
2017 continue;
2019 if (!TEST_BIT (si->visited, w))
2020 condense_visit (graph, si, w);
2022 unsigned int t = si->node_mapping[w];
2023 unsigned int nnode = si->node_mapping[n];
2024 gcc_assert (nnode == n);
2026 if (si->dfs[t] < si->dfs[nnode])
2027 si->dfs[n] = si->dfs[t];
2031 /* See if any components have been identified. */
2032 if (si->dfs[n] == my_dfs)
2034 while (VEC_length (unsigned, si->scc_stack) != 0
2035 && si->dfs[VEC_last (unsigned, si->scc_stack)] >= my_dfs)
2037 unsigned int w = VEC_pop (unsigned, si->scc_stack);
2038 si->node_mapping[w] = n;
2040 if (!TEST_BIT (graph->direct_nodes, w))
2041 RESET_BIT (graph->direct_nodes, n);
2043 /* Unify our nodes. */
2044 if (graph->preds[w])
2046 if (!graph->preds[n])
2047 graph->preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2048 bitmap_ior_into (graph->preds[n], graph->preds[w]);
2050 if (graph->implicit_preds[w])
2052 if (!graph->implicit_preds[n])
2053 graph->implicit_preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2054 bitmap_ior_into (graph->implicit_preds[n],
2055 graph->implicit_preds[w]);
2057 if (graph->points_to[w])
2059 if (!graph->points_to[n])
2060 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2061 bitmap_ior_into (graph->points_to[n],
2062 graph->points_to[w]);
2065 SET_BIT (si->deleted, n);
2067 else
2068 VEC_safe_push (unsigned, heap, si->scc_stack, n);
2071 /* Label pointer equivalences. */
2073 static void
2074 label_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
2076 unsigned int i;
2077 bitmap_iterator bi;
2078 SET_BIT (si->visited, n);
2080 if (!graph->points_to[n])
2081 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2083 /* Label and union our incoming edges's points to sets. */
2084 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
2086 unsigned int w = si->node_mapping[i];
2087 if (!TEST_BIT (si->visited, w))
2088 label_visit (graph, si, w);
2090 /* Skip unused edges */
2091 if (w == n || graph->pointer_label[w] == 0)
2092 continue;
2094 if (graph->points_to[w])
2095 bitmap_ior_into(graph->points_to[n], graph->points_to[w]);
2097 /* Indirect nodes get fresh variables. */
2098 if (!TEST_BIT (graph->direct_nodes, n))
2099 bitmap_set_bit (graph->points_to[n], FIRST_REF_NODE + n);
2101 if (!bitmap_empty_p (graph->points_to[n]))
2103 unsigned int label = equiv_class_lookup (pointer_equiv_class_table,
2104 graph->points_to[n]);
2105 if (!label)
2107 label = pointer_equiv_class++;
2108 equiv_class_add (pointer_equiv_class_table,
2109 label, graph->points_to[n]);
2111 graph->pointer_label[n] = label;
2115 /* Perform offline variable substitution, discovering equivalence
2116 classes, and eliminating non-pointer variables. */
2118 static struct scc_info *
2119 perform_var_substitution (constraint_graph_t graph)
2121 unsigned int i;
2122 unsigned int size = graph->size;
2123 struct scc_info *si = init_scc_info (size);
2125 bitmap_obstack_initialize (&iteration_obstack);
2126 pointer_equiv_class_table = htab_create (511, equiv_class_label_hash,
2127 equiv_class_label_eq, free);
2128 location_equiv_class_table = htab_create (511, equiv_class_label_hash,
2129 equiv_class_label_eq, free);
2130 pointer_equiv_class = 1;
2131 location_equiv_class = 1;
2133 /* Condense the nodes, which means to find SCC's, count incoming
2134 predecessors, and unite nodes in SCC's. */
2135 for (i = 0; i < FIRST_REF_NODE; i++)
2136 if (!TEST_BIT (si->visited, si->node_mapping[i]))
2137 condense_visit (graph, si, si->node_mapping[i]);
2139 sbitmap_zero (si->visited);
2140 /* Actually the label the nodes for pointer equivalences */
2141 for (i = 0; i < FIRST_REF_NODE; i++)
2142 if (!TEST_BIT (si->visited, si->node_mapping[i]))
2143 label_visit (graph, si, si->node_mapping[i]);
2145 /* Calculate location equivalence labels. */
2146 for (i = 0; i < FIRST_REF_NODE; i++)
2148 bitmap pointed_by;
2149 bitmap_iterator bi;
2150 unsigned int j;
2151 unsigned int label;
2153 if (!graph->pointed_by[i])
2154 continue;
2155 pointed_by = BITMAP_ALLOC (&iteration_obstack);
2157 /* Translate the pointed-by mapping for pointer equivalence
2158 labels. */
2159 EXECUTE_IF_SET_IN_BITMAP (graph->pointed_by[i], 0, j, bi)
2161 bitmap_set_bit (pointed_by,
2162 graph->pointer_label[si->node_mapping[j]]);
2164 /* The original pointed_by is now dead. */
2165 BITMAP_FREE (graph->pointed_by[i]);
2167 /* Look up the location equivalence label if one exists, or make
2168 one otherwise. */
2169 label = equiv_class_lookup (location_equiv_class_table,
2170 pointed_by);
2171 if (label == 0)
2173 label = location_equiv_class++;
2174 equiv_class_add (location_equiv_class_table,
2175 label, pointed_by);
2177 else
2179 if (dump_file && (dump_flags & TDF_DETAILS))
2180 fprintf (dump_file, "Found location equivalence for node %s\n",
2181 get_varinfo (i)->name);
2182 BITMAP_FREE (pointed_by);
2184 graph->loc_label[i] = label;
2188 if (dump_file && (dump_flags & TDF_DETAILS))
2189 for (i = 0; i < FIRST_REF_NODE; i++)
2191 bool direct_node = TEST_BIT (graph->direct_nodes, i);
2192 fprintf (dump_file,
2193 "Equivalence classes for %s node id %d:%s are pointer: %d"
2194 ", location:%d\n",
2195 direct_node ? "Direct node" : "Indirect node", i,
2196 get_varinfo (i)->name,
2197 graph->pointer_label[si->node_mapping[i]],
2198 graph->loc_label[si->node_mapping[i]]);
2201 /* Quickly eliminate our non-pointer variables. */
2203 for (i = 0; i < FIRST_REF_NODE; i++)
2205 unsigned int node = si->node_mapping[i];
2207 if (graph->pointer_label[node] == 0)
2209 if (dump_file && (dump_flags & TDF_DETAILS))
2210 fprintf (dump_file,
2211 "%s is a non-pointer variable, eliminating edges.\n",
2212 get_varinfo (node)->name);
2213 stats.nonpointer_vars++;
2214 clear_edges_for_node (graph, node);
2218 return si;
2221 /* Free information that was only necessary for variable
2222 substitution. */
2224 static void
2225 free_var_substitution_info (struct scc_info *si)
2227 free_scc_info (si);
2228 free (graph->pointer_label);
2229 free (graph->loc_label);
2230 free (graph->pointed_by);
2231 free (graph->points_to);
2232 free (graph->eq_rep);
2233 sbitmap_free (graph->direct_nodes);
2234 htab_delete (pointer_equiv_class_table);
2235 htab_delete (location_equiv_class_table);
2236 bitmap_obstack_release (&iteration_obstack);
2239 /* Return an existing node that is equivalent to NODE, which has
2240 equivalence class LABEL, if one exists. Return NODE otherwise. */
2242 static unsigned int
2243 find_equivalent_node (constraint_graph_t graph,
2244 unsigned int node, unsigned int label)
2246 /* If the address version of this variable is unused, we can
2247 substitute it for anything else with the same label.
2248 Otherwise, we know the pointers are equivalent, but not the
2249 locations, and we can unite them later. */
2251 if (!bitmap_bit_p (graph->address_taken, node))
2253 gcc_assert (label < graph->size);
2255 if (graph->eq_rep[label] != -1)
2257 /* Unify the two variables since we know they are equivalent. */
2258 if (unite (graph->eq_rep[label], node))
2259 unify_nodes (graph, graph->eq_rep[label], node, false);
2260 return graph->eq_rep[label];
2262 else
2264 graph->eq_rep[label] = node;
2265 graph->pe_rep[label] = node;
2268 else
2270 gcc_assert (label < graph->size);
2271 graph->pe[node] = label;
2272 if (graph->pe_rep[label] == -1)
2273 graph->pe_rep[label] = node;
2276 return node;
2279 /* Unite pointer equivalent but not location equivalent nodes in
2280 GRAPH. This may only be performed once variable substitution is
2281 finished. */
2283 static void
2284 unite_pointer_equivalences (constraint_graph_t graph)
2286 unsigned int i;
2288 /* Go through the pointer equivalences and unite them to their
2289 representative, if they aren't already. */
2290 for (i = 0; i < FIRST_REF_NODE; i++)
2292 unsigned int label = graph->pe[i];
2293 if (label)
2295 int label_rep = graph->pe_rep[label];
2297 if (label_rep == -1)
2298 continue;
2300 label_rep = find (label_rep);
2301 if (label_rep >= 0 && unite (label_rep, find (i)))
2302 unify_nodes (graph, label_rep, i, false);
2307 /* Move complex constraints to the GRAPH nodes they belong to. */
2309 static void
2310 move_complex_constraints (constraint_graph_t graph)
2312 int i;
2313 constraint_t c;
2315 for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
2317 if (c)
2319 struct constraint_expr lhs = c->lhs;
2320 struct constraint_expr rhs = c->rhs;
2322 if (lhs.type == DEREF)
2324 insert_into_complex (graph, lhs.var, c);
2326 else if (rhs.type == DEREF)
2328 if (!(get_varinfo (lhs.var)->is_special_var))
2329 insert_into_complex (graph, rhs.var, c);
2331 else if (rhs.type != ADDRESSOF && lhs.var > anything_id
2332 && (lhs.offset != 0 || rhs.offset != 0))
2334 insert_into_complex (graph, rhs.var, c);
2341 /* Optimize and rewrite complex constraints while performing
2342 collapsing of equivalent nodes. SI is the SCC_INFO that is the
2343 result of perform_variable_substitution. */
2345 static void
2346 rewrite_constraints (constraint_graph_t graph,
2347 struct scc_info *si)
2349 int i;
2350 unsigned int j;
2351 constraint_t c;
2353 for (j = 0; j < graph->size; j++)
2354 gcc_assert (find (j) == j);
2356 for (i = 0; VEC_iterate (constraint_t, constraints, i, c); i++)
2358 struct constraint_expr lhs = c->lhs;
2359 struct constraint_expr rhs = c->rhs;
2360 unsigned int lhsvar = find (lhs.var);
2361 unsigned int rhsvar = find (rhs.var);
2362 unsigned int lhsnode, rhsnode;
2363 unsigned int lhslabel, rhslabel;
2365 lhsnode = si->node_mapping[lhsvar];
2366 rhsnode = si->node_mapping[rhsvar];
2367 lhslabel = graph->pointer_label[lhsnode];
2368 rhslabel = graph->pointer_label[rhsnode];
2370 /* See if it is really a non-pointer variable, and if so, ignore
2371 the constraint. */
2372 if (lhslabel == 0)
2374 if (dump_file && (dump_flags & TDF_DETAILS))
2377 fprintf (dump_file, "%s is a non-pointer variable,"
2378 "ignoring constraint:",
2379 get_varinfo (lhs.var)->name);
2380 dump_constraint (dump_file, c);
2382 VEC_replace (constraint_t, constraints, i, NULL);
2383 continue;
2386 if (rhslabel == 0)
2388 if (dump_file && (dump_flags & TDF_DETAILS))
2391 fprintf (dump_file, "%s is a non-pointer variable,"
2392 "ignoring constraint:",
2393 get_varinfo (rhs.var)->name);
2394 dump_constraint (dump_file, c);
2396 VEC_replace (constraint_t, constraints, i, NULL);
2397 continue;
2400 lhsvar = find_equivalent_node (graph, lhsvar, lhslabel);
2401 rhsvar = find_equivalent_node (graph, rhsvar, rhslabel);
2402 c->lhs.var = lhsvar;
2403 c->rhs.var = rhsvar;
2408 /* Eliminate indirect cycles involving NODE. Return true if NODE was
2409 part of an SCC, false otherwise. */
2411 static bool
2412 eliminate_indirect_cycles (unsigned int node)
2414 if (graph->indirect_cycles[node] != -1
2415 && !bitmap_empty_p (get_varinfo (node)->solution))
2417 unsigned int i;
2418 VEC(unsigned,heap) *queue = NULL;
2419 int queuepos;
2420 unsigned int to = find (graph->indirect_cycles[node]);
2421 bitmap_iterator bi;
2423 /* We can't touch the solution set and call unify_nodes
2424 at the same time, because unify_nodes is going to do
2425 bitmap unions into it. */
2427 EXECUTE_IF_SET_IN_BITMAP (get_varinfo (node)->solution, 0, i, bi)
2429 if (find (i) == i && i != to)
2431 if (unite (to, i))
2432 VEC_safe_push (unsigned, heap, queue, i);
2436 for (queuepos = 0;
2437 VEC_iterate (unsigned, queue, queuepos, i);
2438 queuepos++)
2440 unify_nodes (graph, to, i, true);
2442 VEC_free (unsigned, heap, queue);
2443 return true;
2445 return false;
2448 /* Solve the constraint graph GRAPH using our worklist solver.
2449 This is based on the PW* family of solvers from the "Efficient Field
2450 Sensitive Pointer Analysis for C" paper.
2451 It works by iterating over all the graph nodes, processing the complex
2452 constraints and propagating the copy constraints, until everything stops
2453 changed. This corresponds to steps 6-8 in the solving list given above. */
2455 static void
2456 solve_graph (constraint_graph_t graph)
2458 unsigned int size = graph->size;
2459 unsigned int i;
2460 bitmap pts;
2462 changed_count = 0;
2463 changed = sbitmap_alloc (size);
2464 sbitmap_zero (changed);
2466 /* Mark all initial non-collapsed nodes as changed. */
2467 for (i = 0; i < size; i++)
2469 varinfo_t ivi = get_varinfo (i);
2470 if (find (i) == i && !bitmap_empty_p (ivi->solution)
2471 && ((graph->succs[i] && !bitmap_empty_p (graph->succs[i]))
2472 || VEC_length (constraint_t, graph->complex[i]) > 0))
2474 SET_BIT (changed, i);
2475 changed_count++;
2479 /* Allocate a bitmap to be used to store the changed bits. */
2480 pts = BITMAP_ALLOC (&pta_obstack);
2482 while (changed_count > 0)
2484 unsigned int i;
2485 struct topo_info *ti = init_topo_info ();
2486 stats.iterations++;
2488 bitmap_obstack_initialize (&iteration_obstack);
2490 compute_topo_order (graph, ti);
2492 while (VEC_length (unsigned, ti->topo_order) != 0)
2495 i = VEC_pop (unsigned, ti->topo_order);
2497 /* If this variable is not a representative, skip it. */
2498 if (find (i) != i)
2499 continue;
2501 /* In certain indirect cycle cases, we may merge this
2502 variable to another. */
2503 if (eliminate_indirect_cycles (i) && find (i) != i)
2504 continue;
2506 /* If the node has changed, we need to process the
2507 complex constraints and outgoing edges again. */
2508 if (TEST_BIT (changed, i))
2510 unsigned int j;
2511 constraint_t c;
2512 bitmap solution;
2513 VEC(constraint_t,heap) *complex = graph->complex[i];
2514 bool solution_empty;
2516 RESET_BIT (changed, i);
2517 changed_count--;
2519 /* Compute the changed set of solution bits. */
2520 bitmap_and_compl (pts, get_varinfo (i)->solution,
2521 get_varinfo (i)->oldsolution);
2523 if (bitmap_empty_p (pts))
2524 continue;
2526 bitmap_ior_into (get_varinfo (i)->oldsolution, pts);
2528 solution = get_varinfo (i)->solution;
2529 solution_empty = bitmap_empty_p (solution);
2531 /* Process the complex constraints */
2532 for (j = 0; VEC_iterate (constraint_t, complex, j, c); j++)
2534 /* XXX: This is going to unsort the constraints in
2535 some cases, which will occasionally add duplicate
2536 constraints during unification. This does not
2537 affect correctness. */
2538 c->lhs.var = find (c->lhs.var);
2539 c->rhs.var = find (c->rhs.var);
2541 /* The only complex constraint that can change our
2542 solution to non-empty, given an empty solution,
2543 is a constraint where the lhs side is receiving
2544 some set from elsewhere. */
2545 if (!solution_empty || c->lhs.type != DEREF)
2546 do_complex_constraint (graph, c, pts);
2549 solution_empty = bitmap_empty_p (solution);
2551 if (!solution_empty)
2553 bitmap_iterator bi;
2554 unsigned eff_escaped_id = find (escaped_id);
2556 /* Propagate solution to all successors. */
2557 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i],
2558 0, j, bi)
2560 bitmap tmp;
2561 bool flag;
2563 unsigned int to = find (j);
2564 tmp = get_varinfo (to)->solution;
2565 flag = false;
2567 /* Don't try to propagate to ourselves. */
2568 if (to == i)
2569 continue;
2571 /* If we propagate from ESCAPED use ESCAPED as
2572 placeholder. */
2573 if (i == eff_escaped_id)
2574 flag = bitmap_set_bit (tmp, escaped_id);
2575 else
2576 flag = set_union_with_increment (tmp, pts, 0);
2578 if (flag)
2580 get_varinfo (to)->solution = tmp;
2581 if (!TEST_BIT (changed, to))
2583 SET_BIT (changed, to);
2584 changed_count++;
2591 free_topo_info (ti);
2592 bitmap_obstack_release (&iteration_obstack);
2595 BITMAP_FREE (pts);
2596 sbitmap_free (changed);
2597 bitmap_obstack_release (&oldpta_obstack);
2600 /* Map from trees to variable infos. */
2601 static struct pointer_map_t *vi_for_tree;
2604 /* Insert ID as the variable id for tree T in the vi_for_tree map. */
2606 static void
2607 insert_vi_for_tree (tree t, varinfo_t vi)
2609 void **slot = pointer_map_insert (vi_for_tree, t);
2610 gcc_assert (vi);
2611 gcc_assert (*slot == NULL);
2612 *slot = vi;
2615 /* Find the variable info for tree T in VI_FOR_TREE. If T does not
2616 exist in the map, return NULL, otherwise, return the varinfo we found. */
2618 static varinfo_t
2619 lookup_vi_for_tree (tree t)
2621 void **slot = pointer_map_contains (vi_for_tree, t);
2622 if (slot == NULL)
2623 return NULL;
2625 return (varinfo_t) *slot;
2628 /* Return a printable name for DECL */
2630 static const char *
2631 alias_get_name (tree decl)
2633 const char *res = get_name (decl);
2634 char *temp;
2635 int num_printed = 0;
2637 if (res != NULL)
2638 return res;
2640 res = "NULL";
2641 if (!dump_file)
2642 return res;
2644 if (TREE_CODE (decl) == SSA_NAME)
2646 num_printed = asprintf (&temp, "%s_%u",
2647 alias_get_name (SSA_NAME_VAR (decl)),
2648 SSA_NAME_VERSION (decl));
2650 else if (DECL_P (decl))
2652 num_printed = asprintf (&temp, "D.%u", DECL_UID (decl));
2654 if (num_printed > 0)
2656 res = ggc_strdup (temp);
2657 free (temp);
2659 return res;
2662 /* Find the variable id for tree T in the map.
2663 If T doesn't exist in the map, create an entry for it and return it. */
2665 static varinfo_t
2666 get_vi_for_tree (tree t)
2668 void **slot = pointer_map_contains (vi_for_tree, t);
2669 if (slot == NULL)
2670 return get_varinfo (create_variable_info_for (t, alias_get_name (t)));
2672 return (varinfo_t) *slot;
2675 /* Get a constraint expression for a new temporary variable. */
2677 static struct constraint_expr
2678 get_constraint_exp_for_temp (tree t)
2680 struct constraint_expr cexpr;
2682 gcc_assert (SSA_VAR_P (t));
2684 cexpr.type = SCALAR;
2685 cexpr.var = get_vi_for_tree (t)->id;
2686 cexpr.offset = 0;
2688 return cexpr;
2691 /* Get a constraint expression vector from an SSA_VAR_P node.
2692 If address_p is true, the result will be taken its address of. */
2694 static void
2695 get_constraint_for_ssa_var (tree t, VEC(ce_s, heap) **results, bool address_p)
2697 struct constraint_expr cexpr;
2698 varinfo_t vi;
2700 /* We allow FUNCTION_DECLs here even though it doesn't make much sense. */
2701 gcc_assert (SSA_VAR_P (t) || DECL_P (t));
2703 /* For parameters, get at the points-to set for the actual parm
2704 decl. */
2705 if (TREE_CODE (t) == SSA_NAME
2706 && TREE_CODE (SSA_NAME_VAR (t)) == PARM_DECL
2707 && SSA_NAME_IS_DEFAULT_DEF (t))
2709 get_constraint_for_ssa_var (SSA_NAME_VAR (t), results, address_p);
2710 return;
2713 vi = get_vi_for_tree (t);
2714 cexpr.var = vi->id;
2715 cexpr.type = SCALAR;
2716 cexpr.offset = 0;
2717 /* If we determine the result is "anything", and we know this is readonly,
2718 say it points to readonly memory instead. */
2719 if (cexpr.var == anything_id && TREE_READONLY (t))
2721 gcc_unreachable ();
2722 cexpr.type = ADDRESSOF;
2723 cexpr.var = readonly_id;
2726 /* If we are not taking the address of the constraint expr, add all
2727 sub-fiels of the variable as well. */
2728 if (!address_p)
2730 for (; vi; vi = vi->next)
2732 cexpr.var = vi->id;
2733 VEC_safe_push (ce_s, heap, *results, &cexpr);
2735 return;
2738 VEC_safe_push (ce_s, heap, *results, &cexpr);
2741 /* Process constraint T, performing various simplifications and then
2742 adding it to our list of overall constraints. */
2744 static void
2745 process_constraint (constraint_t t)
2747 struct constraint_expr rhs = t->rhs;
2748 struct constraint_expr lhs = t->lhs;
2750 gcc_assert (rhs.var < VEC_length (varinfo_t, varmap));
2751 gcc_assert (lhs.var < VEC_length (varinfo_t, varmap));
2753 /* If we didn't get any useful constraint from the lhs we get
2754 &ANYTHING as fallback from get_constraint_for. Deal with
2755 it here by turning it into *ANYTHING. */
2756 if (lhs.type == ADDRESSOF
2757 && lhs.var == anything_id)
2758 lhs.type = DEREF;
2760 /* ADDRESSOF on the lhs is invalid. */
2761 gcc_assert (lhs.type != ADDRESSOF);
2763 /* This can happen in our IR with things like n->a = *p */
2764 if (rhs.type == DEREF && lhs.type == DEREF && rhs.var != anything_id)
2766 /* Split into tmp = *rhs, *lhs = tmp */
2767 tree rhsdecl = get_varinfo (rhs.var)->decl;
2768 tree pointertype = TREE_TYPE (rhsdecl);
2769 tree pointedtotype = TREE_TYPE (pointertype);
2770 tree tmpvar = create_tmp_var_raw (pointedtotype, "doubledereftmp");
2771 struct constraint_expr tmplhs = get_constraint_exp_for_temp (tmpvar);
2773 process_constraint (new_constraint (tmplhs, rhs));
2774 process_constraint (new_constraint (lhs, tmplhs));
2776 else if (rhs.type == ADDRESSOF && lhs.type == DEREF)
2778 /* Split into tmp = &rhs, *lhs = tmp */
2779 tree rhsdecl = get_varinfo (rhs.var)->decl;
2780 tree pointertype = TREE_TYPE (rhsdecl);
2781 tree tmpvar = create_tmp_var_raw (pointertype, "derefaddrtmp");
2782 struct constraint_expr tmplhs = get_constraint_exp_for_temp (tmpvar);
2784 process_constraint (new_constraint (tmplhs, rhs));
2785 process_constraint (new_constraint (lhs, tmplhs));
2787 else
2789 gcc_assert (rhs.type != ADDRESSOF || rhs.offset == 0);
2790 VEC_safe_push (constraint_t, heap, constraints, t);
2794 /* Return true if T is a type that could contain pointers. */
2796 static bool
2797 type_could_have_pointers (tree type)
2799 if (POINTER_TYPE_P (type))
2800 return true;
2802 if (TREE_CODE (type) == ARRAY_TYPE)
2803 return type_could_have_pointers (TREE_TYPE (type));
2805 return AGGREGATE_TYPE_P (type);
2808 /* Return true if T is a variable of a type that could contain
2809 pointers. */
2811 static bool
2812 could_have_pointers (tree t)
2814 return type_could_have_pointers (TREE_TYPE (t));
2817 /* Return the position, in bits, of FIELD_DECL from the beginning of its
2818 structure. */
2820 static HOST_WIDE_INT
2821 bitpos_of_field (const tree fdecl)
2824 if (!host_integerp (DECL_FIELD_OFFSET (fdecl), 0)
2825 || !host_integerp (DECL_FIELD_BIT_OFFSET (fdecl), 0))
2826 return -1;
2828 return (TREE_INT_CST_LOW (DECL_FIELD_OFFSET (fdecl)) * 8
2829 + TREE_INT_CST_LOW (DECL_FIELD_BIT_OFFSET (fdecl)));
2833 /* Get constraint expressions for offsetting PTR by OFFSET. Stores the
2834 resulting constraint expressions in *RESULTS. */
2836 static void
2837 get_constraint_for_ptr_offset (tree ptr, tree offset,
2838 VEC (ce_s, heap) **results)
2840 struct constraint_expr *c;
2841 unsigned int j, n;
2842 HOST_WIDE_INT rhsunitoffset, rhsoffset;
2844 /* If we do not do field-sensitive PTA adding offsets to pointers
2845 does not change the points-to solution. */
2846 if (!use_field_sensitive)
2848 get_constraint_for (ptr, results);
2849 return;
2852 /* If the offset is not a non-negative integer constant that fits
2853 in a HOST_WIDE_INT, we have to fall back to a conservative
2854 solution which includes all sub-fields of all pointed-to
2855 variables of ptr. */
2856 if (!host_integerp (offset, 0))
2857 rhsoffset = UNKNOWN_OFFSET;
2858 else
2860 /* Make sure the bit-offset also fits. */
2861 rhsunitoffset = TREE_INT_CST_LOW (offset);
2862 rhsoffset = rhsunitoffset * BITS_PER_UNIT;
2863 if (rhsunitoffset != rhsoffset / BITS_PER_UNIT)
2864 rhsoffset = UNKNOWN_OFFSET;
2867 get_constraint_for (ptr, results);
2868 if (rhsoffset == 0)
2869 return;
2871 /* As we are eventually appending to the solution do not use
2872 VEC_iterate here. */
2873 n = VEC_length (ce_s, *results);
2874 for (j = 0; j < n; j++)
2876 varinfo_t curr;
2877 c = VEC_index (ce_s, *results, j);
2878 curr = get_varinfo (c->var);
2880 if (c->type == ADDRESSOF
2881 /* If this varinfo represents a full variable just use it. */
2882 && curr->is_full_var)
2883 c->offset = 0;
2884 else if (c->type == ADDRESSOF
2885 /* If we do not know the offset add all subfields. */
2886 && rhsoffset == UNKNOWN_OFFSET)
2888 varinfo_t temp = lookup_vi_for_tree (curr->decl);
2891 struct constraint_expr c2;
2892 c2.var = temp->id;
2893 c2.type = ADDRESSOF;
2894 c2.offset = 0;
2895 VEC_safe_push (ce_s, heap, *results, &c2);
2896 temp = temp->next;
2898 while (temp);
2900 else if (c->type == ADDRESSOF)
2902 varinfo_t temp;
2903 unsigned HOST_WIDE_INT offset = curr->offset + rhsoffset;
2905 /* Search the sub-field which overlaps with the
2906 pointed-to offset. If the result is outside of the variable
2907 we have to provide a conservative result, as the variable is
2908 still reachable from the resulting pointer (even though it
2909 technically cannot point to anything). The last and first
2910 sub-fields are such conservative results.
2911 ??? If we always had a sub-field for &object + 1 then
2912 we could represent this in a more precise way. */
2913 if (rhsoffset < 0
2914 && curr->offset < offset)
2915 offset = 0;
2916 temp = first_or_preceding_vi_for_offset (curr, offset);
2918 /* If the found variable is not exactly at the pointed to
2919 result, we have to include the next variable in the
2920 solution as well. Otherwise two increments by offset / 2
2921 do not result in the same or a conservative superset
2922 solution. */
2923 if (temp->offset != offset
2924 && temp->next != NULL)
2926 struct constraint_expr c2;
2927 c2.var = temp->next->id;
2928 c2.type = ADDRESSOF;
2929 c2.offset = 0;
2930 VEC_safe_push (ce_s, heap, *results, &c2);
2932 c->var = temp->id;
2933 c->offset = 0;
2935 else
2936 c->offset = rhsoffset;
2941 /* Given a COMPONENT_REF T, return the constraint_expr vector for it.
2942 If address_p is true the result will be taken its address of. */
2944 static void
2945 get_constraint_for_component_ref (tree t, VEC(ce_s, heap) **results,
2946 bool address_p)
2948 tree orig_t = t;
2949 HOST_WIDE_INT bitsize = -1;
2950 HOST_WIDE_INT bitmaxsize = -1;
2951 HOST_WIDE_INT bitpos;
2952 tree forzero;
2953 struct constraint_expr *result;
2955 /* Some people like to do cute things like take the address of
2956 &0->a.b */
2957 forzero = t;
2958 while (!SSA_VAR_P (forzero) && !CONSTANT_CLASS_P (forzero))
2959 forzero = TREE_OPERAND (forzero, 0);
2961 if (CONSTANT_CLASS_P (forzero) && integer_zerop (forzero))
2963 struct constraint_expr temp;
2965 temp.offset = 0;
2966 temp.var = integer_id;
2967 temp.type = SCALAR;
2968 VEC_safe_push (ce_s, heap, *results, &temp);
2969 return;
2972 t = get_ref_base_and_extent (t, &bitpos, &bitsize, &bitmaxsize);
2974 /* Pretend to take the address of the base, we'll take care of
2975 adding the required subset of sub-fields below. */
2976 get_constraint_for_1 (t, results, true);
2977 gcc_assert (VEC_length (ce_s, *results) == 1);
2978 result = VEC_last (ce_s, *results);
2980 if (result->type == SCALAR
2981 && get_varinfo (result->var)->is_full_var)
2982 /* For single-field vars do not bother about the offset. */
2983 result->offset = 0;
2984 else if (result->type == SCALAR)
2986 /* In languages like C, you can access one past the end of an
2987 array. You aren't allowed to dereference it, so we can
2988 ignore this constraint. When we handle pointer subtraction,
2989 we may have to do something cute here. */
2991 if ((unsigned HOST_WIDE_INT)bitpos < get_varinfo (result->var)->fullsize
2992 && bitmaxsize != 0)
2994 /* It's also not true that the constraint will actually start at the
2995 right offset, it may start in some padding. We only care about
2996 setting the constraint to the first actual field it touches, so
2997 walk to find it. */
2998 struct constraint_expr cexpr = *result;
2999 varinfo_t curr;
3000 VEC_pop (ce_s, *results);
3001 cexpr.offset = 0;
3002 for (curr = get_varinfo (cexpr.var); curr; curr = curr->next)
3004 if (ranges_overlap_p (curr->offset, curr->size,
3005 bitpos, bitmaxsize))
3007 cexpr.var = curr->id;
3008 VEC_safe_push (ce_s, heap, *results, &cexpr);
3009 if (address_p)
3010 break;
3013 /* If we are going to take the address of this field then
3014 to be able to compute reachability correctly add at least
3015 the last field of the variable. */
3016 if (address_p
3017 && VEC_length (ce_s, *results) == 0)
3019 curr = get_varinfo (cexpr.var);
3020 while (curr->next != NULL)
3021 curr = curr->next;
3022 cexpr.var = curr->id;
3023 VEC_safe_push (ce_s, heap, *results, &cexpr);
3025 else
3026 /* Assert that we found *some* field there. The user couldn't be
3027 accessing *only* padding. */
3028 /* Still the user could access one past the end of an array
3029 embedded in a struct resulting in accessing *only* padding. */
3030 gcc_assert (VEC_length (ce_s, *results) >= 1
3031 || ref_contains_array_ref (orig_t));
3033 else if (bitmaxsize == 0)
3035 if (dump_file && (dump_flags & TDF_DETAILS))
3036 fprintf (dump_file, "Access to zero-sized part of variable,"
3037 "ignoring\n");
3039 else
3040 if (dump_file && (dump_flags & TDF_DETAILS))
3041 fprintf (dump_file, "Access to past the end of variable, ignoring\n");
3043 else if (result->type == DEREF)
3045 /* If we do not know exactly where the access goes say so. Note
3046 that only for non-structure accesses we know that we access
3047 at most one subfiled of any variable. */
3048 if (bitpos == -1
3049 || bitsize != bitmaxsize
3050 || AGGREGATE_TYPE_P (TREE_TYPE (orig_t)))
3051 result->offset = UNKNOWN_OFFSET;
3052 else
3053 result->offset = bitpos;
3055 else if (result->type == ADDRESSOF)
3057 /* We can end up here for component references on a
3058 VIEW_CONVERT_EXPR <>(&foobar). */
3059 result->type = SCALAR;
3060 result->var = anything_id;
3061 result->offset = 0;
3063 else
3064 gcc_unreachable ();
3068 /* Dereference the constraint expression CONS, and return the result.
3069 DEREF (ADDRESSOF) = SCALAR
3070 DEREF (SCALAR) = DEREF
3071 DEREF (DEREF) = (temp = DEREF1; result = DEREF(temp))
3072 This is needed so that we can handle dereferencing DEREF constraints. */
3074 static void
3075 do_deref (VEC (ce_s, heap) **constraints)
3077 struct constraint_expr *c;
3078 unsigned int i = 0;
3080 for (i = 0; VEC_iterate (ce_s, *constraints, i, c); i++)
3082 if (c->type == SCALAR)
3083 c->type = DEREF;
3084 else if (c->type == ADDRESSOF)
3085 c->type = SCALAR;
3086 else if (c->type == DEREF)
3088 tree tmpvar = create_tmp_var_raw (ptr_type_node, "dereftmp");
3089 struct constraint_expr tmplhs = get_constraint_exp_for_temp (tmpvar);
3090 process_constraint (new_constraint (tmplhs, *c));
3091 c->var = tmplhs.var;
3093 else
3094 gcc_unreachable ();
3098 /* Given a tree T, return the constraint expression for it. */
3100 static void
3101 get_constraint_for_1 (tree t, VEC (ce_s, heap) **results, bool address_p)
3103 struct constraint_expr temp;
3105 /* x = integer is all glommed to a single variable, which doesn't
3106 point to anything by itself. That is, of course, unless it is an
3107 integer constant being treated as a pointer, in which case, we
3108 will return that this is really the addressof anything. This
3109 happens below, since it will fall into the default case. The only
3110 case we know something about an integer treated like a pointer is
3111 when it is the NULL pointer, and then we just say it points to
3112 NULL.
3114 Do not do that if -fno-delete-null-pointer-checks though, because
3115 in that case *NULL does not fail, so it _should_ alias *anything.
3116 It is not worth adding a new option or renaming the existing one,
3117 since this case is relatively obscure. */
3118 if (flag_delete_null_pointer_checks
3119 && ((TREE_CODE (t) == INTEGER_CST
3120 && integer_zerop (t))
3121 /* The only valid CONSTRUCTORs in gimple with pointer typed
3122 elements are zero-initializer. */
3123 || TREE_CODE (t) == CONSTRUCTOR))
3125 temp.var = nothing_id;
3126 temp.type = ADDRESSOF;
3127 temp.offset = 0;
3128 VEC_safe_push (ce_s, heap, *results, &temp);
3129 return;
3132 /* String constants are read-only. */
3133 if (TREE_CODE (t) == STRING_CST)
3135 temp.var = readonly_id;
3136 temp.type = SCALAR;
3137 temp.offset = 0;
3138 VEC_safe_push (ce_s, heap, *results, &temp);
3139 return;
3142 switch (TREE_CODE_CLASS (TREE_CODE (t)))
3144 case tcc_expression:
3146 switch (TREE_CODE (t))
3148 case ADDR_EXPR:
3150 struct constraint_expr *c;
3151 unsigned int i;
3152 tree exp = TREE_OPERAND (t, 0);
3154 get_constraint_for_1 (exp, results, true);
3156 for (i = 0; VEC_iterate (ce_s, *results, i, c); i++)
3158 if (c->type == DEREF)
3159 c->type = SCALAR;
3160 else
3161 c->type = ADDRESSOF;
3163 return;
3165 break;
3166 default:;
3168 break;
3170 case tcc_reference:
3172 switch (TREE_CODE (t))
3174 case INDIRECT_REF:
3176 get_constraint_for_1 (TREE_OPERAND (t, 0), results, address_p);
3177 do_deref (results);
3178 return;
3180 case ARRAY_REF:
3181 case ARRAY_RANGE_REF:
3182 case COMPONENT_REF:
3183 get_constraint_for_component_ref (t, results, address_p);
3184 return;
3185 case VIEW_CONVERT_EXPR:
3186 get_constraint_for_1 (TREE_OPERAND (t, 0), results, address_p);
3187 return;
3188 /* We are missing handling for TARGET_MEM_REF here. */
3189 default:;
3191 break;
3193 case tcc_exceptional:
3195 switch (TREE_CODE (t))
3197 case SSA_NAME:
3199 get_constraint_for_ssa_var (t, results, address_p);
3200 return;
3202 default:;
3204 break;
3206 case tcc_declaration:
3208 get_constraint_for_ssa_var (t, results, address_p);
3209 return;
3211 default:;
3214 /* The default fallback is a constraint from anything. */
3215 temp.type = ADDRESSOF;
3216 temp.var = anything_id;
3217 temp.offset = 0;
3218 VEC_safe_push (ce_s, heap, *results, &temp);
3221 /* Given a gimple tree T, return the constraint expression vector for it. */
3223 static void
3224 get_constraint_for (tree t, VEC (ce_s, heap) **results)
3226 gcc_assert (VEC_length (ce_s, *results) == 0);
3228 get_constraint_for_1 (t, results, false);
3231 /* Handle aggregate copies by expanding into copies of the respective
3232 fields of the structures. */
3234 static void
3235 do_structure_copy (tree lhsop, tree rhsop)
3237 struct constraint_expr *lhsp, *rhsp;
3238 VEC (ce_s, heap) *lhsc = NULL, *rhsc = NULL;
3239 unsigned j;
3241 get_constraint_for (lhsop, &lhsc);
3242 get_constraint_for (rhsop, &rhsc);
3243 lhsp = VEC_index (ce_s, lhsc, 0);
3244 rhsp = VEC_index (ce_s, rhsc, 0);
3245 if (lhsp->type == DEREF
3246 || (lhsp->type == ADDRESSOF && lhsp->var == anything_id)
3247 || rhsp->type == DEREF)
3249 struct constraint_expr tmp;
3250 tree tmpvar = create_tmp_var_raw (ptr_type_node,
3251 "structcopydereftmp");
3252 tmp.var = get_vi_for_tree (tmpvar)->id;
3253 tmp.type = SCALAR;
3254 tmp.offset = 0;
3255 for (j = 0; VEC_iterate (ce_s, rhsc, j, rhsp); ++j)
3256 process_constraint (new_constraint (tmp, *rhsp));
3257 for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp); ++j)
3258 process_constraint (new_constraint (*lhsp, tmp));
3260 else if (lhsp->type == SCALAR
3261 && (rhsp->type == SCALAR
3262 || rhsp->type == ADDRESSOF))
3264 tree lhsbase, rhsbase;
3265 HOST_WIDE_INT lhssize, lhsmaxsize, lhsoffset;
3266 HOST_WIDE_INT rhssize, rhsmaxsize, rhsoffset;
3267 unsigned k = 0;
3268 lhsbase = get_ref_base_and_extent (lhsop, &lhsoffset,
3269 &lhssize, &lhsmaxsize);
3270 rhsbase = get_ref_base_and_extent (rhsop, &rhsoffset,
3271 &rhssize, &rhsmaxsize);
3272 for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp);)
3274 varinfo_t lhsv, rhsv;
3275 rhsp = VEC_index (ce_s, rhsc, k);
3276 lhsv = get_varinfo (lhsp->var);
3277 rhsv = get_varinfo (rhsp->var);
3278 if (lhsv->may_have_pointers
3279 && ranges_overlap_p (lhsv->offset + rhsoffset, lhsv->size,
3280 rhsv->offset + lhsoffset, rhsv->size))
3281 process_constraint (new_constraint (*lhsp, *rhsp));
3282 if (lhsv->offset + rhsoffset + lhsv->size
3283 > rhsv->offset + lhsoffset + rhsv->size)
3285 ++k;
3286 if (k >= VEC_length (ce_s, rhsc))
3287 break;
3289 else
3290 ++j;
3293 else
3294 gcc_unreachable ();
3296 VEC_free (ce_s, heap, lhsc);
3297 VEC_free (ce_s, heap, rhsc);
3300 /* Create a constraint ID = OP. */
3302 static void
3303 make_constraint_to (unsigned id, tree op)
3305 VEC(ce_s, heap) *rhsc = NULL;
3306 struct constraint_expr *c;
3307 struct constraint_expr includes;
3308 unsigned int j;
3310 includes.var = id;
3311 includes.offset = 0;
3312 includes.type = SCALAR;
3314 get_constraint_for (op, &rhsc);
3315 for (j = 0; VEC_iterate (ce_s, rhsc, j, c); j++)
3316 process_constraint (new_constraint (includes, *c));
3317 VEC_free (ce_s, heap, rhsc);
3320 /* Make constraints necessary to make OP escape. */
3322 static void
3323 make_escape_constraint (tree op)
3325 make_constraint_to (escaped_id, op);
3328 /* For non-IPA mode, generate constraints necessary for a call on the
3329 RHS. */
3331 static void
3332 handle_rhs_call (gimple stmt, VEC(ce_s, heap) **results)
3334 struct constraint_expr rhsc;
3335 unsigned i;
3337 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3339 tree arg = gimple_call_arg (stmt, i);
3341 /* Find those pointers being passed, and make sure they end up
3342 pointing to anything. */
3343 if (could_have_pointers (arg))
3344 make_escape_constraint (arg);
3347 /* The static chain escapes as well. */
3348 if (gimple_call_chain (stmt))
3349 make_escape_constraint (gimple_call_chain (stmt));
3351 /* Regular functions return nonlocal memory. */
3352 rhsc.var = nonlocal_id;
3353 rhsc.offset = 0;
3354 rhsc.type = SCALAR;
3355 VEC_safe_push (ce_s, heap, *results, &rhsc);
3358 /* For non-IPA mode, generate constraints necessary for a call
3359 that returns a pointer and assigns it to LHS. This simply makes
3360 the LHS point to global and escaped variables. */
3362 static void
3363 handle_lhs_call (tree lhs, int flags, VEC(ce_s, heap) *rhsc)
3365 VEC(ce_s, heap) *lhsc = NULL;
3366 unsigned int j;
3367 struct constraint_expr *lhsp;
3369 get_constraint_for (lhs, &lhsc);
3371 if (flags & ECF_MALLOC)
3373 struct constraint_expr rhsc;
3374 tree heapvar = heapvar_lookup (lhs);
3375 varinfo_t vi;
3377 if (heapvar == NULL)
3379 heapvar = create_tmp_var_raw (ptr_type_node, "HEAP");
3380 DECL_EXTERNAL (heapvar) = 1;
3381 get_var_ann (heapvar)->is_heapvar = 1;
3382 if (gimple_referenced_vars (cfun))
3383 add_referenced_var (heapvar);
3384 heapvar_insert (lhs, heapvar);
3387 rhsc.var = create_variable_info_for (heapvar,
3388 alias_get_name (heapvar));
3389 vi = get_varinfo (rhsc.var);
3390 vi->is_artificial_var = 1;
3391 vi->is_heap_var = 1;
3392 vi->is_unknown_size_var = true;
3393 vi->fullsize = ~0;
3394 vi->size = ~0;
3395 rhsc.type = ADDRESSOF;
3396 rhsc.offset = 0;
3397 for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp); j++)
3398 process_constraint (new_constraint (*lhsp, rhsc));
3400 else if (VEC_length (ce_s, rhsc) > 0)
3402 struct constraint_expr *lhsp, *rhsp;
3403 unsigned int i, j;
3404 /* If the store is to a global decl make sure to
3405 add proper escape constraints. */
3406 lhs = get_base_address (lhs);
3407 if (lhs
3408 && DECL_P (lhs)
3409 && is_global_var (lhs))
3411 struct constraint_expr tmpc;
3412 tmpc.var = escaped_id;
3413 tmpc.offset = 0;
3414 tmpc.type = SCALAR;
3415 VEC_safe_push (ce_s, heap, lhsc, &tmpc);
3417 for (i = 0; VEC_iterate (ce_s, lhsc, i, lhsp); ++i)
3418 for (j = 0; VEC_iterate (ce_s, rhsc, j, rhsp); ++j)
3419 process_constraint (new_constraint (*lhsp, *rhsp));
3421 VEC_free (ce_s, heap, lhsc);
3424 /* For non-IPA mode, generate constraints necessary for a call of a
3425 const function that returns a pointer in the statement STMT. */
3427 static void
3428 handle_const_call (gimple stmt, VEC(ce_s, heap) **results)
3430 struct constraint_expr rhsc, tmpc;
3431 tree tmpvar = NULL_TREE;
3432 unsigned int k;
3434 /* Treat nested const functions the same as pure functions as far
3435 as the static chain is concerned. */
3436 if (gimple_call_chain (stmt))
3438 make_constraint_to (callused_id, gimple_call_chain (stmt));
3439 rhsc.var = callused_id;
3440 rhsc.offset = 0;
3441 rhsc.type = SCALAR;
3442 VEC_safe_push (ce_s, heap, *results, &rhsc);
3445 /* May return arguments. */
3446 for (k = 0; k < gimple_call_num_args (stmt); ++k)
3448 tree arg = gimple_call_arg (stmt, k);
3450 if (could_have_pointers (arg))
3452 VEC(ce_s, heap) *argc = NULL;
3453 struct constraint_expr *argp;
3454 int i;
3456 /* We always use a temporary here, otherwise we end up with
3457 a quadratic amount of constraints for
3458 large_struct = const_call (large_struct);
3459 with field-sensitive PTA. */
3460 if (tmpvar == NULL_TREE)
3462 tmpvar = create_tmp_var_raw (ptr_type_node, "consttmp");
3463 tmpc = get_constraint_exp_for_temp (tmpvar);
3466 get_constraint_for (arg, &argc);
3467 for (i = 0; VEC_iterate (ce_s, argc, i, argp); i++)
3468 process_constraint (new_constraint (tmpc, *argp));
3469 VEC_free (ce_s, heap, argc);
3472 if (tmpvar != NULL_TREE)
3473 VEC_safe_push (ce_s, heap, *results, &tmpc);
3475 /* May return addresses of globals. */
3476 rhsc.var = nonlocal_id;
3477 rhsc.offset = 0;
3478 rhsc.type = ADDRESSOF;
3479 VEC_safe_push (ce_s, heap, *results, &rhsc);
3482 /* For non-IPA mode, generate constraints necessary for a call to a
3483 pure function in statement STMT. */
3485 static void
3486 handle_pure_call (gimple stmt, VEC(ce_s, heap) **results)
3488 struct constraint_expr rhsc;
3489 unsigned i;
3490 bool need_callused = false;
3492 /* Memory reached from pointer arguments is call-used. */
3493 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3495 tree arg = gimple_call_arg (stmt, i);
3497 if (could_have_pointers (arg))
3499 make_constraint_to (callused_id, arg);
3500 need_callused = true;
3504 /* The static chain is used as well. */
3505 if (gimple_call_chain (stmt))
3507 make_constraint_to (callused_id, gimple_call_chain (stmt));
3508 need_callused = true;
3511 /* Pure functions may return callused and nonlocal memory. */
3512 if (need_callused)
3514 rhsc.var = callused_id;
3515 rhsc.offset = 0;
3516 rhsc.type = SCALAR;
3517 VEC_safe_push (ce_s, heap, *results, &rhsc);
3519 rhsc.var = nonlocal_id;
3520 rhsc.offset = 0;
3521 rhsc.type = SCALAR;
3522 VEC_safe_push (ce_s, heap, *results, &rhsc);
3525 /* Walk statement T setting up aliasing constraints according to the
3526 references found in T. This function is the main part of the
3527 constraint builder. AI points to auxiliary alias information used
3528 when building alias sets and computing alias grouping heuristics. */
3530 static void
3531 find_func_aliases (gimple origt)
3533 gimple t = origt;
3534 VEC(ce_s, heap) *lhsc = NULL;
3535 VEC(ce_s, heap) *rhsc = NULL;
3536 struct constraint_expr *c;
3537 enum escape_type stmt_escape_type;
3539 /* Now build constraints expressions. */
3540 if (gimple_code (t) == GIMPLE_PHI)
3542 gcc_assert (!AGGREGATE_TYPE_P (TREE_TYPE (gimple_phi_result (t))));
3544 /* Only care about pointers and structures containing
3545 pointers. */
3546 if (could_have_pointers (gimple_phi_result (t)))
3548 size_t i;
3549 unsigned int j;
3551 /* For a phi node, assign all the arguments to
3552 the result. */
3553 get_constraint_for (gimple_phi_result (t), &lhsc);
3554 for (i = 0; i < gimple_phi_num_args (t); i++)
3556 tree rhstype;
3557 tree strippedrhs = PHI_ARG_DEF (t, i);
3559 STRIP_NOPS (strippedrhs);
3560 rhstype = TREE_TYPE (strippedrhs);
3561 get_constraint_for (gimple_phi_arg_def (t, i), &rhsc);
3563 for (j = 0; VEC_iterate (ce_s, lhsc, j, c); j++)
3565 struct constraint_expr *c2;
3566 while (VEC_length (ce_s, rhsc) > 0)
3568 c2 = VEC_last (ce_s, rhsc);
3569 process_constraint (new_constraint (*c, *c2));
3570 VEC_pop (ce_s, rhsc);
3576 /* In IPA mode, we need to generate constraints to pass call
3577 arguments through their calls. There are two cases,
3578 either a GIMPLE_CALL returning a value, or just a plain
3579 GIMPLE_CALL when we are not.
3581 In non-ipa mode, we need to generate constraints for each
3582 pointer passed by address. */
3583 else if (is_gimple_call (t))
3585 if (!in_ipa_mode)
3587 VEC(ce_s, heap) *rhsc = NULL;
3588 int flags = gimple_call_flags (t);
3590 /* Const functions can return their arguments and addresses
3591 of global memory but not of escaped memory. */
3592 if (flags & (ECF_CONST|ECF_NOVOPS))
3594 if (gimple_call_lhs (t)
3595 && could_have_pointers (gimple_call_lhs (t)))
3596 handle_const_call (t, &rhsc);
3598 /* Pure functions can return addresses in and of memory
3599 reachable from their arguments, but they are not an escape
3600 point for reachable memory of their arguments. */
3601 else if (flags & (ECF_PURE|ECF_LOOPING_CONST_OR_PURE))
3602 handle_pure_call (t, &rhsc);
3603 else
3604 handle_rhs_call (t, &rhsc);
3605 if (gimple_call_lhs (t)
3606 && could_have_pointers (gimple_call_lhs (t)))
3607 handle_lhs_call (gimple_call_lhs (t), flags, rhsc);
3608 VEC_free (ce_s, heap, rhsc);
3610 else
3612 tree lhsop;
3613 varinfo_t fi;
3614 int i = 1;
3615 size_t j;
3616 tree decl;
3618 lhsop = gimple_call_lhs (t);
3619 decl = gimple_call_fndecl (t);
3621 /* If we can directly resolve the function being called, do so.
3622 Otherwise, it must be some sort of indirect expression that
3623 we should still be able to handle. */
3624 if (decl)
3625 fi = get_vi_for_tree (decl);
3626 else
3628 decl = gimple_call_fn (t);
3629 fi = get_vi_for_tree (decl);
3632 /* Assign all the passed arguments to the appropriate incoming
3633 parameters of the function. */
3634 for (j = 0; j < gimple_call_num_args (t); j++)
3636 struct constraint_expr lhs ;
3637 struct constraint_expr *rhsp;
3638 tree arg = gimple_call_arg (t, j);
3640 get_constraint_for (arg, &rhsc);
3641 if (TREE_CODE (decl) != FUNCTION_DECL)
3643 lhs.type = DEREF;
3644 lhs.var = fi->id;
3645 lhs.offset = i;
3647 else
3649 lhs.type = SCALAR;
3650 lhs.var = first_vi_for_offset (fi, i)->id;
3651 lhs.offset = 0;
3653 while (VEC_length (ce_s, rhsc) != 0)
3655 rhsp = VEC_last (ce_s, rhsc);
3656 process_constraint (new_constraint (lhs, *rhsp));
3657 VEC_pop (ce_s, rhsc);
3659 i++;
3662 /* If we are returning a value, assign it to the result. */
3663 if (lhsop)
3665 struct constraint_expr rhs;
3666 struct constraint_expr *lhsp;
3667 unsigned int j = 0;
3669 get_constraint_for (lhsop, &lhsc);
3670 if (TREE_CODE (decl) != FUNCTION_DECL)
3672 rhs.type = DEREF;
3673 rhs.var = fi->id;
3674 rhs.offset = i;
3676 else
3678 rhs.type = SCALAR;
3679 rhs.var = first_vi_for_offset (fi, i)->id;
3680 rhs.offset = 0;
3682 for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp); j++)
3683 process_constraint (new_constraint (*lhsp, rhs));
3687 /* Otherwise, just a regular assignment statement. Only care about
3688 operations with pointer result, others are dealt with as escape
3689 points if they have pointer operands. */
3690 else if (is_gimple_assign (t)
3691 && could_have_pointers (gimple_assign_lhs (t)))
3693 /* Otherwise, just a regular assignment statement. */
3694 tree lhsop = gimple_assign_lhs (t);
3695 tree rhsop = (gimple_num_ops (t) == 2) ? gimple_assign_rhs1 (t) : NULL;
3697 if (rhsop && AGGREGATE_TYPE_P (TREE_TYPE (lhsop)))
3698 do_structure_copy (lhsop, rhsop);
3699 else
3701 unsigned int j;
3702 struct constraint_expr temp;
3703 get_constraint_for (lhsop, &lhsc);
3705 if (gimple_assign_rhs_code (t) == POINTER_PLUS_EXPR)
3706 get_constraint_for_ptr_offset (gimple_assign_rhs1 (t),
3707 gimple_assign_rhs2 (t), &rhsc);
3708 else if ((CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (t))
3709 && !(POINTER_TYPE_P (gimple_expr_type (t))
3710 && !POINTER_TYPE_P (TREE_TYPE (rhsop))))
3711 || gimple_assign_single_p (t))
3712 get_constraint_for (rhsop, &rhsc);
3713 else
3715 temp.type = ADDRESSOF;
3716 temp.var = anything_id;
3717 temp.offset = 0;
3718 VEC_safe_push (ce_s, heap, rhsc, &temp);
3720 for (j = 0; VEC_iterate (ce_s, lhsc, j, c); j++)
3722 struct constraint_expr *c2;
3723 unsigned int k;
3725 for (k = 0; VEC_iterate (ce_s, rhsc, k, c2); k++)
3726 process_constraint (new_constraint (*c, *c2));
3730 else if (gimple_code (t) == GIMPLE_CHANGE_DYNAMIC_TYPE)
3732 unsigned int j;
3734 get_constraint_for (gimple_cdt_location (t), &lhsc);
3735 for (j = 0; VEC_iterate (ce_s, lhsc, j, c); ++j)
3736 get_varinfo (c->var)->no_tbaa_pruning = true;
3739 stmt_escape_type = is_escape_site (t);
3740 if (stmt_escape_type == ESCAPE_STORED_IN_GLOBAL)
3742 gcc_assert (is_gimple_assign (t));
3743 if (gimple_assign_rhs_code (t) == ADDR_EXPR)
3745 tree rhs = gimple_assign_rhs1 (t);
3746 tree base = get_base_address (TREE_OPERAND (rhs, 0));
3747 if (base
3748 && (!DECL_P (base)
3749 || !is_global_var (base)))
3750 make_escape_constraint (rhs);
3752 else if (get_gimple_rhs_class (gimple_assign_rhs_code (t))
3753 == GIMPLE_SINGLE_RHS)
3755 if (could_have_pointers (gimple_assign_rhs1 (t)))
3756 make_escape_constraint (gimple_assign_rhs1 (t));
3758 else
3759 gcc_unreachable ();
3761 else if (stmt_escape_type == ESCAPE_BAD_CAST)
3763 gcc_assert (is_gimple_assign (t));
3764 gcc_assert (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (t))
3765 || gimple_assign_rhs_code (t) == VIEW_CONVERT_EXPR);
3766 make_escape_constraint (gimple_assign_rhs1 (t));
3768 else if (stmt_escape_type == ESCAPE_TO_ASM)
3770 unsigned i, noutputs;
3771 const char **oconstraints;
3772 const char *constraint;
3773 bool allows_mem, allows_reg, is_inout;
3775 noutputs = gimple_asm_noutputs (t);
3776 oconstraints = XALLOCAVEC (const char *, noutputs);
3778 for (i = 0; i < noutputs; ++i)
3780 tree link = gimple_asm_output_op (t, i);
3781 tree op = TREE_VALUE (link);
3783 constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
3784 oconstraints[i] = constraint;
3785 parse_output_constraint (&constraint, i, 0, 0, &allows_mem,
3786 &allows_reg, &is_inout);
3788 /* A memory constraint makes the address of the operand escape. */
3789 if (!allows_reg && allows_mem)
3790 make_escape_constraint (build_fold_addr_expr (op));
3792 /* The asm may read global memory, so outputs may point to
3793 any global memory. */
3794 if (op && could_have_pointers (op))
3796 VEC(ce_s, heap) *lhsc = NULL;
3797 struct constraint_expr rhsc, *lhsp;
3798 unsigned j;
3799 get_constraint_for (op, &lhsc);
3800 rhsc.var = nonlocal_id;
3801 rhsc.offset = 0;
3802 rhsc.type = SCALAR;
3803 for (j = 0; VEC_iterate (ce_s, lhsc, j, lhsp); j++)
3804 process_constraint (new_constraint (*lhsp, rhsc));
3805 VEC_free (ce_s, heap, lhsc);
3808 for (i = 0; i < gimple_asm_ninputs (t); ++i)
3810 tree link = gimple_asm_input_op (t, i);
3811 tree op = TREE_VALUE (link);
3813 constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
3815 parse_input_constraint (&constraint, 0, 0, noutputs, 0, oconstraints,
3816 &allows_mem, &allows_reg);
3818 /* A memory constraint makes the address of the operand escape. */
3819 if (!allows_reg && allows_mem)
3820 make_escape_constraint (build_fold_addr_expr (op));
3821 /* Strictly we'd only need the constraint to ESCAPED if
3822 the asm clobbers memory, otherwise using CALLUSED
3823 would be enough. */
3824 else if (op && could_have_pointers (op))
3825 make_escape_constraint (op);
3829 VEC_free (ce_s, heap, rhsc);
3830 VEC_free (ce_s, heap, lhsc);
3834 /* Find the first varinfo in the same variable as START that overlaps with
3835 OFFSET. Return NULL if we can't find one. */
3837 static varinfo_t
3838 first_vi_for_offset (varinfo_t start, unsigned HOST_WIDE_INT offset)
3840 /* If the offset is outside of the variable, bail out. */
3841 if (offset >= start->fullsize)
3842 return NULL;
3844 /* If we cannot reach offset from start, lookup the first field
3845 and start from there. */
3846 if (start->offset > offset)
3847 start = lookup_vi_for_tree (start->decl);
3849 while (start)
3851 /* We may not find a variable in the field list with the actual
3852 offset when when we have glommed a structure to a variable.
3853 In that case, however, offset should still be within the size
3854 of the variable. */
3855 if (offset >= start->offset
3856 && offset < (start->offset + start->size))
3857 return start;
3859 start= start->next;
3862 return NULL;
3865 /* Find the first varinfo in the same variable as START that overlaps with
3866 OFFSET. If there is no such varinfo the varinfo directly preceding
3867 OFFSET is returned. */
3869 static varinfo_t
3870 first_or_preceding_vi_for_offset (varinfo_t start,
3871 unsigned HOST_WIDE_INT offset)
3873 /* If we cannot reach offset from start, lookup the first field
3874 and start from there. */
3875 if (start->offset > offset)
3876 start = lookup_vi_for_tree (start->decl);
3878 /* We may not find a variable in the field list with the actual
3879 offset when when we have glommed a structure to a variable.
3880 In that case, however, offset should still be within the size
3881 of the variable.
3882 If we got beyond the offset we look for return the field
3883 directly preceding offset which may be the last field. */
3884 while (start->next
3885 && offset >= start->offset
3886 && !(offset < (start->offset + start->size)))
3887 start = start->next;
3889 return start;
3893 /* Insert the varinfo FIELD into the field list for BASE, at the front
3894 of the list. */
3896 static void
3897 insert_into_field_list (varinfo_t base, varinfo_t field)
3899 varinfo_t prev = base;
3900 varinfo_t curr = base->next;
3902 field->next = curr;
3903 prev->next = field;
3906 /* Insert the varinfo FIELD into the field list for BASE, ordered by
3907 offset. */
3909 static void
3910 insert_into_field_list_sorted (varinfo_t base, varinfo_t field)
3912 varinfo_t prev = base;
3913 varinfo_t curr = base->next;
3915 if (curr == NULL)
3917 prev->next = field;
3918 field->next = NULL;
3920 else
3922 while (curr)
3924 if (field->offset <= curr->offset)
3925 break;
3926 prev = curr;
3927 curr = curr->next;
3929 field->next = prev->next;
3930 prev->next = field;
3934 /* This structure is used during pushing fields onto the fieldstack
3935 to track the offset of the field, since bitpos_of_field gives it
3936 relative to its immediate containing type, and we want it relative
3937 to the ultimate containing object. */
3939 struct fieldoff
3941 /* Offset from the base of the base containing object to this field. */
3942 HOST_WIDE_INT offset;
3944 /* Size, in bits, of the field. */
3945 unsigned HOST_WIDE_INT size;
3947 unsigned has_unknown_size : 1;
3949 unsigned may_have_pointers : 1;
3951 typedef struct fieldoff fieldoff_s;
3953 DEF_VEC_O(fieldoff_s);
3954 DEF_VEC_ALLOC_O(fieldoff_s,heap);
3956 /* qsort comparison function for two fieldoff's PA and PB */
3958 static int
3959 fieldoff_compare (const void *pa, const void *pb)
3961 const fieldoff_s *foa = (const fieldoff_s *)pa;
3962 const fieldoff_s *fob = (const fieldoff_s *)pb;
3963 unsigned HOST_WIDE_INT foasize, fobsize;
3965 if (foa->offset < fob->offset)
3966 return -1;
3967 else if (foa->offset > fob->offset)
3968 return 1;
3970 foasize = foa->size;
3971 fobsize = fob->size;
3972 if (foasize < fobsize)
3973 return -1;
3974 else if (foasize > fobsize)
3975 return 1;
3976 return 0;
3979 /* Sort a fieldstack according to the field offset and sizes. */
3980 static void
3981 sort_fieldstack (VEC(fieldoff_s,heap) *fieldstack)
3983 qsort (VEC_address (fieldoff_s, fieldstack),
3984 VEC_length (fieldoff_s, fieldstack),
3985 sizeof (fieldoff_s),
3986 fieldoff_compare);
3989 /* Return true if V is a tree that we can have subvars for.
3990 Normally, this is any aggregate type. Also complex
3991 types which are not gimple registers can have subvars. */
3993 static inline bool
3994 var_can_have_subvars (const_tree v)
3996 /* Volatile variables should never have subvars. */
3997 if (TREE_THIS_VOLATILE (v))
3998 return false;
4000 /* Non decls or memory tags can never have subvars. */
4001 if (!DECL_P (v))
4002 return false;
4004 /* Aggregates without overlapping fields can have subvars. */
4005 if (TREE_CODE (TREE_TYPE (v)) == RECORD_TYPE)
4006 return true;
4008 return false;
4011 /* Given a TYPE, and a vector of field offsets FIELDSTACK, push all
4012 the fields of TYPE onto fieldstack, recording their offsets along
4013 the way.
4015 OFFSET is used to keep track of the offset in this entire
4016 structure, rather than just the immediately containing structure.
4017 Returns the number of fields pushed. */
4019 static int
4020 push_fields_onto_fieldstack (tree type, VEC(fieldoff_s,heap) **fieldstack,
4021 HOST_WIDE_INT offset)
4023 tree field;
4024 int count = 0;
4026 if (TREE_CODE (type) != RECORD_TYPE)
4027 return 0;
4029 /* If the vector of fields is growing too big, bail out early.
4030 Callers check for VEC_length <= MAX_FIELDS_FOR_FIELD_SENSITIVE, make
4031 sure this fails. */
4032 if (VEC_length (fieldoff_s, *fieldstack) > MAX_FIELDS_FOR_FIELD_SENSITIVE)
4033 return 0;
4035 for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
4036 if (TREE_CODE (field) == FIELD_DECL)
4038 bool push = false;
4039 int pushed = 0;
4040 HOST_WIDE_INT foff = bitpos_of_field (field);
4042 if (!var_can_have_subvars (field)
4043 || TREE_CODE (TREE_TYPE (field)) == QUAL_UNION_TYPE
4044 || TREE_CODE (TREE_TYPE (field)) == UNION_TYPE)
4045 push = true;
4046 else if (!(pushed = push_fields_onto_fieldstack
4047 (TREE_TYPE (field), fieldstack, offset + foff))
4048 && (DECL_SIZE (field)
4049 && !integer_zerop (DECL_SIZE (field))))
4050 /* Empty structures may have actual size, like in C++. So
4051 see if we didn't push any subfields and the size is
4052 nonzero, push the field onto the stack. */
4053 push = true;
4055 if (push)
4057 fieldoff_s *pair = NULL;
4058 bool has_unknown_size = false;
4060 if (!VEC_empty (fieldoff_s, *fieldstack))
4061 pair = VEC_last (fieldoff_s, *fieldstack);
4063 if (!DECL_SIZE (field)
4064 || !host_integerp (DECL_SIZE (field), 1))
4065 has_unknown_size = true;
4067 /* If adjacent fields do not contain pointers merge them. */
4068 if (pair
4069 && !pair->may_have_pointers
4070 && !could_have_pointers (field)
4071 && !pair->has_unknown_size
4072 && !has_unknown_size
4073 && pair->offset + (HOST_WIDE_INT)pair->size == offset + foff)
4075 pair = VEC_last (fieldoff_s, *fieldstack);
4076 pair->size += TREE_INT_CST_LOW (DECL_SIZE (field));
4078 else
4080 pair = VEC_safe_push (fieldoff_s, heap, *fieldstack, NULL);
4081 pair->offset = offset + foff;
4082 pair->has_unknown_size = has_unknown_size;
4083 if (!has_unknown_size)
4084 pair->size = TREE_INT_CST_LOW (DECL_SIZE (field));
4085 else
4086 pair->size = -1;
4087 pair->may_have_pointers = could_have_pointers (field);
4088 count++;
4091 else
4092 count += pushed;
4095 return count;
4098 /* Create a constraint ID = &FROM. */
4100 static void
4101 make_constraint_from (varinfo_t vi, int from)
4103 struct constraint_expr lhs, rhs;
4105 lhs.var = vi->id;
4106 lhs.offset = 0;
4107 lhs.type = SCALAR;
4109 rhs.var = from;
4110 rhs.offset = 0;
4111 rhs.type = ADDRESSOF;
4112 process_constraint (new_constraint (lhs, rhs));
4115 /* Create a constraint ID = FROM. */
4117 static void
4118 make_copy_constraint (varinfo_t vi, int from)
4120 struct constraint_expr lhs, rhs;
4122 lhs.var = vi->id;
4123 lhs.offset = 0;
4124 lhs.type = SCALAR;
4126 rhs.var = from;
4127 rhs.offset = 0;
4128 rhs.type = SCALAR;
4129 process_constraint (new_constraint (lhs, rhs));
4132 /* Count the number of arguments DECL has, and set IS_VARARGS to true
4133 if it is a varargs function. */
4135 static unsigned int
4136 count_num_arguments (tree decl, bool *is_varargs)
4138 unsigned int i = 0;
4139 tree t;
4141 for (t = TYPE_ARG_TYPES (TREE_TYPE (decl));
4143 t = TREE_CHAIN (t))
4145 if (TREE_VALUE (t) == void_type_node)
4146 break;
4147 i++;
4150 if (!t)
4151 *is_varargs = true;
4152 return i;
4155 /* Creation function node for DECL, using NAME, and return the index
4156 of the variable we've created for the function. */
4158 static unsigned int
4159 create_function_info_for (tree decl, const char *name)
4161 unsigned int index = VEC_length (varinfo_t, varmap);
4162 varinfo_t vi;
4163 tree arg;
4164 unsigned int i;
4165 bool is_varargs = false;
4167 /* Create the variable info. */
4169 vi = new_var_info (decl, index, name);
4170 vi->decl = decl;
4171 vi->offset = 0;
4172 vi->size = 1;
4173 vi->fullsize = count_num_arguments (decl, &is_varargs) + 1;
4174 insert_vi_for_tree (vi->decl, vi);
4175 VEC_safe_push (varinfo_t, heap, varmap, vi);
4177 stats.total_vars++;
4179 /* If it's varargs, we don't know how many arguments it has, so we
4180 can't do much. */
4181 if (is_varargs)
4183 vi->fullsize = ~0;
4184 vi->size = ~0;
4185 vi->is_unknown_size_var = true;
4186 return index;
4190 arg = DECL_ARGUMENTS (decl);
4192 /* Set up variables for each argument. */
4193 for (i = 1; i < vi->fullsize; i++)
4195 varinfo_t argvi;
4196 const char *newname;
4197 char *tempname;
4198 unsigned int newindex;
4199 tree argdecl = decl;
4201 if (arg)
4202 argdecl = arg;
4204 newindex = VEC_length (varinfo_t, varmap);
4205 asprintf (&tempname, "%s.arg%d", name, i-1);
4206 newname = ggc_strdup (tempname);
4207 free (tempname);
4209 argvi = new_var_info (argdecl, newindex, newname);
4210 argvi->decl = argdecl;
4211 VEC_safe_push (varinfo_t, heap, varmap, argvi);
4212 argvi->offset = i;
4213 argvi->size = 1;
4214 argvi->is_full_var = true;
4215 argvi->fullsize = vi->fullsize;
4216 insert_into_field_list_sorted (vi, argvi);
4217 stats.total_vars ++;
4218 if (arg)
4220 insert_vi_for_tree (arg, argvi);
4221 arg = TREE_CHAIN (arg);
4225 /* Create a variable for the return var. */
4226 if (DECL_RESULT (decl) != NULL
4227 || !VOID_TYPE_P (TREE_TYPE (TREE_TYPE (decl))))
4229 varinfo_t resultvi;
4230 const char *newname;
4231 char *tempname;
4232 unsigned int newindex;
4233 tree resultdecl = decl;
4235 vi->fullsize ++;
4237 if (DECL_RESULT (decl))
4238 resultdecl = DECL_RESULT (decl);
4240 newindex = VEC_length (varinfo_t, varmap);
4241 asprintf (&tempname, "%s.result", name);
4242 newname = ggc_strdup (tempname);
4243 free (tempname);
4245 resultvi = new_var_info (resultdecl, newindex, newname);
4246 resultvi->decl = resultdecl;
4247 VEC_safe_push (varinfo_t, heap, varmap, resultvi);
4248 resultvi->offset = i;
4249 resultvi->size = 1;
4250 resultvi->fullsize = vi->fullsize;
4251 resultvi->is_full_var = true;
4252 insert_into_field_list_sorted (vi, resultvi);
4253 stats.total_vars ++;
4254 if (DECL_RESULT (decl))
4255 insert_vi_for_tree (DECL_RESULT (decl), resultvi);
4257 return index;
4261 /* Return true if FIELDSTACK contains fields that overlap.
4262 FIELDSTACK is assumed to be sorted by offset. */
4264 static bool
4265 check_for_overlaps (VEC (fieldoff_s,heap) *fieldstack)
4267 fieldoff_s *fo = NULL;
4268 unsigned int i;
4269 HOST_WIDE_INT lastoffset = -1;
4271 for (i = 0; VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
4273 if (fo->offset == lastoffset)
4274 return true;
4275 lastoffset = fo->offset;
4277 return false;
4280 /* Create a varinfo structure for NAME and DECL, and add it to VARMAP.
4281 This will also create any varinfo structures necessary for fields
4282 of DECL. */
4284 static unsigned int
4285 create_variable_info_for (tree decl, const char *name)
4287 unsigned int index = VEC_length (varinfo_t, varmap);
4288 varinfo_t vi;
4289 tree decl_type = TREE_TYPE (decl);
4290 tree declsize = DECL_P (decl) ? DECL_SIZE (decl) : TYPE_SIZE (decl_type);
4291 bool is_global = DECL_P (decl) ? is_global_var (decl) : false;
4292 VEC (fieldoff_s,heap) *fieldstack = NULL;
4294 if (TREE_CODE (decl) == FUNCTION_DECL && in_ipa_mode)
4295 return create_function_info_for (decl, name);
4297 if (var_can_have_subvars (decl) && use_field_sensitive
4298 && (!var_ann (decl)
4299 || var_ann (decl)->noalias_state == 0)
4300 && (!var_ann (decl)
4301 || !var_ann (decl)->is_heapvar))
4302 push_fields_onto_fieldstack (decl_type, &fieldstack, 0);
4304 /* If the variable doesn't have subvars, we may end up needing to
4305 sort the field list and create fake variables for all the
4306 fields. */
4307 vi = new_var_info (decl, index, name);
4308 vi->decl = decl;
4309 vi->offset = 0;
4310 vi->may_have_pointers = could_have_pointers (decl);
4311 if (!declsize
4312 || !host_integerp (declsize, 1))
4314 vi->is_unknown_size_var = true;
4315 vi->fullsize = ~0;
4316 vi->size = ~0;
4318 else
4320 vi->fullsize = TREE_INT_CST_LOW (declsize);
4321 vi->size = vi->fullsize;
4324 insert_vi_for_tree (vi->decl, vi);
4325 VEC_safe_push (varinfo_t, heap, varmap, vi);
4326 if (is_global && (!flag_whole_program || !in_ipa_mode)
4327 && vi->may_have_pointers)
4329 if (var_ann (decl)
4330 && var_ann (decl)->noalias_state == NO_ALIAS_ANYTHING)
4331 make_constraint_from (vi, vi->id);
4332 else
4333 make_copy_constraint (vi, nonlocal_id);
4336 stats.total_vars++;
4337 if (use_field_sensitive
4338 && !vi->is_unknown_size_var
4339 && var_can_have_subvars (decl)
4340 && VEC_length (fieldoff_s, fieldstack) > 1
4341 && VEC_length (fieldoff_s, fieldstack) <= MAX_FIELDS_FOR_FIELD_SENSITIVE)
4343 unsigned int newindex = VEC_length (varinfo_t, varmap);
4344 fieldoff_s *fo = NULL;
4345 bool notokay = false;
4346 unsigned int i;
4348 for (i = 0; !notokay && VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
4350 if (fo->has_unknown_size
4351 || fo->offset < 0)
4353 notokay = true;
4354 break;
4358 /* We can't sort them if we have a field with a variable sized type,
4359 which will make notokay = true. In that case, we are going to return
4360 without creating varinfos for the fields anyway, so sorting them is a
4361 waste to boot. */
4362 if (!notokay)
4364 sort_fieldstack (fieldstack);
4365 /* Due to some C++ FE issues, like PR 22488, we might end up
4366 what appear to be overlapping fields even though they,
4367 in reality, do not overlap. Until the C++ FE is fixed,
4368 we will simply disable field-sensitivity for these cases. */
4369 notokay = check_for_overlaps (fieldstack);
4373 if (VEC_length (fieldoff_s, fieldstack) != 0)
4374 fo = VEC_index (fieldoff_s, fieldstack, 0);
4376 if (fo == NULL || notokay)
4378 vi->is_unknown_size_var = 1;
4379 vi->fullsize = ~0;
4380 vi->size = ~0;
4381 vi->is_full_var = true;
4382 VEC_free (fieldoff_s, heap, fieldstack);
4383 return index;
4386 vi->size = fo->size;
4387 vi->offset = fo->offset;
4388 vi->may_have_pointers = fo->may_have_pointers;
4389 for (i = VEC_length (fieldoff_s, fieldstack) - 1;
4390 i >= 1 && VEC_iterate (fieldoff_s, fieldstack, i, fo);
4391 i--)
4393 varinfo_t newvi;
4394 const char *newname = "NULL";
4395 char *tempname;
4397 newindex = VEC_length (varinfo_t, varmap);
4398 if (dump_file)
4400 asprintf (&tempname, "%s." HOST_WIDE_INT_PRINT_DEC
4401 "+" HOST_WIDE_INT_PRINT_DEC,
4402 vi->name, fo->offset, fo->size);
4403 newname = ggc_strdup (tempname);
4404 free (tempname);
4406 newvi = new_var_info (decl, newindex, newname);
4407 newvi->offset = fo->offset;
4408 newvi->size = fo->size;
4409 newvi->fullsize = vi->fullsize;
4410 newvi->may_have_pointers = fo->may_have_pointers;
4411 insert_into_field_list (vi, newvi);
4412 VEC_safe_push (varinfo_t, heap, varmap, newvi);
4413 if (is_global && (!flag_whole_program || !in_ipa_mode)
4414 && newvi->may_have_pointers)
4415 make_copy_constraint (newvi, nonlocal_id);
4417 stats.total_vars++;
4420 else
4421 vi->is_full_var = true;
4423 VEC_free (fieldoff_s, heap, fieldstack);
4425 return index;
4428 /* Print out the points-to solution for VAR to FILE. */
4430 static void
4431 dump_solution_for_var (FILE *file, unsigned int var)
4433 varinfo_t vi = get_varinfo (var);
4434 unsigned int i;
4435 bitmap_iterator bi;
4437 if (find (var) != var)
4439 varinfo_t vipt = get_varinfo (find (var));
4440 fprintf (file, "%s = same as %s\n", vi->name, vipt->name);
4442 else
4444 fprintf (file, "%s = { ", vi->name);
4445 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
4447 fprintf (file, "%s ", get_varinfo (i)->name);
4449 fprintf (file, "}");
4450 if (vi->no_tbaa_pruning)
4451 fprintf (file, " no-tbaa-pruning");
4452 fprintf (file, "\n");
4456 /* Print the points-to solution for VAR to stdout. */
4458 void
4459 debug_solution_for_var (unsigned int var)
4461 dump_solution_for_var (stdout, var);
4464 /* Create varinfo structures for all of the variables in the
4465 function for intraprocedural mode. */
4467 static void
4468 intra_create_variable_infos (void)
4470 tree t;
4471 struct constraint_expr lhs, rhs;
4473 /* For each incoming pointer argument arg, create the constraint ARG
4474 = NONLOCAL or a dummy variable if flag_argument_noalias is set. */
4475 for (t = DECL_ARGUMENTS (current_function_decl); t; t = TREE_CHAIN (t))
4477 varinfo_t p;
4479 if (!could_have_pointers (t))
4480 continue;
4482 /* If flag_argument_noalias is set, then function pointer
4483 arguments are guaranteed not to point to each other. In that
4484 case, create an artificial variable PARM_NOALIAS and the
4485 constraint ARG = &PARM_NOALIAS. */
4486 if (POINTER_TYPE_P (TREE_TYPE (t)) && flag_argument_noalias > 0)
4488 varinfo_t vi;
4489 tree heapvar = heapvar_lookup (t);
4491 lhs.offset = 0;
4492 lhs.type = SCALAR;
4493 lhs.var = get_vi_for_tree (t)->id;
4495 if (heapvar == NULL_TREE)
4497 var_ann_t ann;
4498 heapvar = create_tmp_var_raw (ptr_type_node,
4499 "PARM_NOALIAS");
4500 DECL_EXTERNAL (heapvar) = 1;
4501 if (gimple_referenced_vars (cfun))
4502 add_referenced_var (heapvar);
4504 heapvar_insert (t, heapvar);
4506 ann = get_var_ann (heapvar);
4507 ann->is_heapvar = 1;
4508 if (flag_argument_noalias == 1)
4509 ann->noalias_state = NO_ALIAS;
4510 else if (flag_argument_noalias == 2)
4511 ann->noalias_state = NO_ALIAS_GLOBAL;
4512 else if (flag_argument_noalias == 3)
4513 ann->noalias_state = NO_ALIAS_ANYTHING;
4514 else
4515 gcc_unreachable ();
4518 vi = get_vi_for_tree (heapvar);
4519 vi->is_artificial_var = 1;
4520 vi->is_heap_var = 1;
4521 vi->is_unknown_size_var = true;
4522 vi->fullsize = ~0;
4523 vi->size = ~0;
4524 rhs.var = vi->id;
4525 rhs.type = ADDRESSOF;
4526 rhs.offset = 0;
4527 for (p = get_varinfo (lhs.var); p; p = p->next)
4529 struct constraint_expr temp = lhs;
4530 temp.var = p->id;
4531 process_constraint (new_constraint (temp, rhs));
4534 else
4536 varinfo_t arg_vi = get_vi_for_tree (t);
4538 for (p = arg_vi; p; p = p->next)
4539 make_constraint_from (p, nonlocal_id);
4543 /* Add a constraint for a result decl that is passed by reference. */
4544 if (DECL_RESULT (cfun->decl)
4545 && DECL_BY_REFERENCE (DECL_RESULT (cfun->decl)))
4547 varinfo_t p, result_vi = get_vi_for_tree (DECL_RESULT (cfun->decl));
4549 for (p = result_vi; p; p = p->next)
4550 make_constraint_from (p, nonlocal_id);
4553 /* Add a constraint for the incoming static chain parameter. */
4554 if (cfun->static_chain_decl != NULL_TREE)
4556 varinfo_t p, chain_vi = get_vi_for_tree (cfun->static_chain_decl);
4558 for (p = chain_vi; p; p = p->next)
4559 make_constraint_from (p, nonlocal_id);
4563 /* Structure used to put solution bitmaps in a hashtable so they can
4564 be shared among variables with the same points-to set. */
4566 typedef struct shared_bitmap_info
4568 bitmap pt_vars;
4569 hashval_t hashcode;
4570 } *shared_bitmap_info_t;
4571 typedef const struct shared_bitmap_info *const_shared_bitmap_info_t;
4573 static htab_t shared_bitmap_table;
4575 /* Hash function for a shared_bitmap_info_t */
4577 static hashval_t
4578 shared_bitmap_hash (const void *p)
4580 const_shared_bitmap_info_t const bi = (const_shared_bitmap_info_t) p;
4581 return bi->hashcode;
4584 /* Equality function for two shared_bitmap_info_t's. */
4586 static int
4587 shared_bitmap_eq (const void *p1, const void *p2)
4589 const_shared_bitmap_info_t const sbi1 = (const_shared_bitmap_info_t) p1;
4590 const_shared_bitmap_info_t const sbi2 = (const_shared_bitmap_info_t) p2;
4591 return bitmap_equal_p (sbi1->pt_vars, sbi2->pt_vars);
4594 /* Lookup a bitmap in the shared bitmap hashtable, and return an already
4595 existing instance if there is one, NULL otherwise. */
4597 static bitmap
4598 shared_bitmap_lookup (bitmap pt_vars)
4600 void **slot;
4601 struct shared_bitmap_info sbi;
4603 sbi.pt_vars = pt_vars;
4604 sbi.hashcode = bitmap_hash (pt_vars);
4606 slot = htab_find_slot_with_hash (shared_bitmap_table, &sbi,
4607 sbi.hashcode, NO_INSERT);
4608 if (!slot)
4609 return NULL;
4610 else
4611 return ((shared_bitmap_info_t) *slot)->pt_vars;
4615 /* Add a bitmap to the shared bitmap hashtable. */
4617 static void
4618 shared_bitmap_add (bitmap pt_vars)
4620 void **slot;
4621 shared_bitmap_info_t sbi = XNEW (struct shared_bitmap_info);
4623 sbi->pt_vars = pt_vars;
4624 sbi->hashcode = bitmap_hash (pt_vars);
4626 slot = htab_find_slot_with_hash (shared_bitmap_table, sbi,
4627 sbi->hashcode, INSERT);
4628 gcc_assert (!*slot);
4629 *slot = (void *) sbi;
4633 /* Set bits in INTO corresponding to the variable uids in solution set FROM.
4634 If MEM_ALIAS_SET is not zero, we also use type based alias analysis to
4635 prune the points-to sets with this alias-set.
4636 Returns the number of pruned variables and updates the vars_contains_global
4637 member of *PT . */
4639 static unsigned
4640 set_uids_in_ptset (bitmap into, bitmap from,
4641 alias_set_type mem_alias_set, struct pt_solution *pt)
4643 unsigned int i;
4644 bitmap_iterator bi;
4645 unsigned pruned = 0;
4647 EXECUTE_IF_SET_IN_BITMAP (from, 0, i, bi)
4649 varinfo_t vi = get_varinfo (i);
4651 /* The only artificial variables that are allowed in a may-alias
4652 set are heap variables. */
4653 if (vi->is_artificial_var && !vi->is_heap_var)
4654 continue;
4656 if (TREE_CODE (vi->decl) == VAR_DECL
4657 || TREE_CODE (vi->decl) == PARM_DECL
4658 || TREE_CODE (vi->decl) == RESULT_DECL)
4660 /* Don't type prune artificial vars or points-to sets
4661 for pointers that have not been dereferenced or with
4662 type-based pruning disabled. */
4663 if (!vi->is_artificial_var
4664 && !vi->no_tbaa_pruning
4665 && mem_alias_set != 0)
4667 alias_set_type var_alias_set = get_alias_set (vi->decl);
4668 if (mem_alias_set != var_alias_set
4669 && !alias_set_subset_of (mem_alias_set, var_alias_set))
4671 ++pruned;
4672 continue;
4676 /* Add the decl to the points-to set. Note that the points-to
4677 set contains global variables. */
4678 bitmap_set_bit (into, DECL_UID (vi->decl));
4679 if (is_global_var (vi->decl))
4680 pt->vars_contains_global = true;
4684 return pruned;
4688 static bool have_alias_info = false;
4690 /* Emit a note for the pointer initialization point DEF. */
4692 static void
4693 emit_pointer_definition (tree ptr, bitmap visited)
4695 gimple def = SSA_NAME_DEF_STMT (ptr);
4696 if (gimple_code (def) == GIMPLE_PHI)
4698 use_operand_p argp;
4699 ssa_op_iter oi;
4701 FOR_EACH_PHI_ARG (argp, def, oi, SSA_OP_USE)
4703 tree arg = USE_FROM_PTR (argp);
4704 if (TREE_CODE (arg) == SSA_NAME)
4706 if (bitmap_set_bit (visited, SSA_NAME_VERSION (arg)))
4707 emit_pointer_definition (arg, visited);
4709 else
4710 inform (0, "initialized from %qE", arg);
4713 else if (!gimple_nop_p (def))
4714 inform (gimple_location (def), "initialized from here");
4717 /* Emit a strict aliasing warning for dereferencing the pointer PTR. */
4719 static void
4720 emit_alias_warning (tree ptr)
4722 gimple use;
4723 imm_use_iterator ui;
4724 bool warned = false;
4726 FOR_EACH_IMM_USE_STMT (use, ui, ptr)
4728 tree deref = NULL_TREE;
4730 if (gimple_has_lhs (use))
4732 tree lhs = get_base_address (gimple_get_lhs (use));
4733 if (lhs
4734 && INDIRECT_REF_P (lhs)
4735 && TREE_OPERAND (lhs, 0) == ptr)
4736 deref = lhs;
4738 if (gimple_assign_single_p (use))
4740 tree rhs = get_base_address (gimple_assign_rhs1 (use));
4741 if (rhs
4742 && INDIRECT_REF_P (rhs)
4743 && TREE_OPERAND (rhs, 0) == ptr)
4744 deref = rhs;
4746 else if (is_gimple_call (use))
4748 unsigned i;
4749 for (i = 0; i < gimple_call_num_args (use); ++i)
4751 tree op = get_base_address (gimple_call_arg (use, i));
4752 if (op
4753 && INDIRECT_REF_P (op)
4754 && TREE_OPERAND (op, 0) == ptr)
4755 deref = op;
4758 if (deref
4759 && !TREE_NO_WARNING (deref))
4761 TREE_NO_WARNING (deref) = 1;
4762 warned |= warning_at (gimple_location (use), OPT_Wstrict_aliasing,
4763 "dereferencing pointer %qD does break "
4764 "strict-aliasing rules", SSA_NAME_VAR (ptr));
4767 if (warned)
4769 bitmap visited = BITMAP_ALLOC (NULL);
4770 emit_pointer_definition (ptr, visited);
4771 BITMAP_FREE (visited);
4775 /* Compute the points-to solution *PT for the variable VI.
4776 Prunes the points-to set based on TBAA rules if DO_TBAA_PRUNING
4777 is true. Returns the number of TBAA pruned variables from the
4778 points-to set. */
4780 static unsigned int
4781 find_what_var_points_to (varinfo_t vi, struct pt_solution *pt,
4782 bool do_tbaa_pruning)
4784 unsigned int i, pruned;
4785 bitmap_iterator bi;
4786 bitmap finished_solution;
4787 bitmap result;
4788 tree ptr = vi->decl;
4789 alias_set_type mem_alias_set;
4791 memset (pt, 0, sizeof (struct pt_solution));
4793 /* This variable may have been collapsed, let's get the real
4794 variable. */
4795 vi = get_varinfo (find (vi->id));
4797 /* Translate artificial variables into SSA_NAME_PTR_INFO
4798 attributes. */
4799 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
4801 varinfo_t vi = get_varinfo (i);
4803 if (vi->is_artificial_var)
4805 if (vi->id == nothing_id)
4806 pt->null = 1;
4807 else if (vi->id == escaped_id)
4808 pt->escaped = 1;
4809 else if (vi->id == callused_id)
4810 gcc_unreachable ();
4811 else if (vi->id == nonlocal_id)
4812 pt->nonlocal = 1;
4813 else if (vi->is_heap_var)
4814 /* We represent heapvars in the points-to set properly. */
4816 else if (vi->id == anything_id
4817 || vi->id == readonly_id
4818 || vi->id == integer_id)
4819 pt->anything = 1;
4823 /* Instead of doing extra work, simply do not create
4824 elaborate points-to information for pt_anything pointers. */
4825 if (pt->anything)
4826 return 0;
4828 /* Share the final set of variables when possible. */
4829 finished_solution = BITMAP_GGC_ALLOC ();
4830 stats.points_to_sets_created++;
4832 if (TREE_CODE (ptr) == SSA_NAME)
4833 ptr = SSA_NAME_VAR (ptr);
4835 /* If the pointer decl is marked that no TBAA is to be applied,
4836 do not do tbaa pruning. */
4837 if (!do_tbaa_pruning
4838 || DECL_NO_TBAA_P (ptr))
4839 mem_alias_set = 0;
4840 else
4841 mem_alias_set = get_deref_alias_set (ptr);
4842 pruned = set_uids_in_ptset (finished_solution, vi->solution,
4843 mem_alias_set, pt);
4844 result = shared_bitmap_lookup (finished_solution);
4845 if (!result)
4847 shared_bitmap_add (finished_solution);
4848 pt->vars = finished_solution;
4850 else
4852 pt->vars = result;
4853 bitmap_clear (finished_solution);
4856 return pruned;
4859 /* Given a pointer variable P, fill in its points-to set. Apply
4860 type-based pruning if IS_DEREFERENCED is true. */
4862 static void
4863 find_what_p_points_to (tree p, bool is_dereferenced)
4865 struct ptr_info_def *pi;
4866 unsigned int pruned;
4867 tree lookup_p = p;
4868 varinfo_t vi;
4870 /* For parameters, get at the points-to set for the actual parm
4871 decl. */
4872 if (TREE_CODE (p) == SSA_NAME
4873 && TREE_CODE (SSA_NAME_VAR (p)) == PARM_DECL
4874 && SSA_NAME_IS_DEFAULT_DEF (p))
4875 lookup_p = SSA_NAME_VAR (p);
4877 vi = lookup_vi_for_tree (lookup_p);
4878 if (!vi)
4879 return;
4881 pi = get_ptr_info (p);
4882 pruned = find_what_var_points_to (vi, &pi->pt, is_dereferenced);
4884 if (!(pi->pt.anything || pi->pt.nonlocal || pi->pt.escaped)
4885 && bitmap_empty_p (pi->pt.vars)
4886 && pruned > 0
4887 && is_dereferenced
4888 && warn_strict_aliasing > 0
4889 && !SSA_NAME_IS_DEFAULT_DEF (p))
4891 if (dump_file && dump_flags & TDF_DETAILS)
4893 fprintf (dump_file, "alias warning for ");
4894 print_generic_expr (dump_file, p, 0);
4895 fprintf (dump_file, "\n");
4897 emit_alias_warning (p);
4902 /* Query statistics for points-to solutions. */
4904 static struct {
4905 unsigned HOST_WIDE_INT pt_solution_includes_may_alias;
4906 unsigned HOST_WIDE_INT pt_solution_includes_no_alias;
4907 unsigned HOST_WIDE_INT pt_solutions_intersect_may_alias;
4908 unsigned HOST_WIDE_INT pt_solutions_intersect_no_alias;
4909 } pta_stats;
4911 void
4912 dump_pta_stats (FILE *s)
4914 fprintf (s, "\nPTA query stats:\n");
4915 fprintf (s, " pt_solution_includes: "
4916 HOST_WIDE_INT_PRINT_DEC" disambiguations, "
4917 HOST_WIDE_INT_PRINT_DEC" queries\n",
4918 pta_stats.pt_solution_includes_no_alias,
4919 pta_stats.pt_solution_includes_no_alias
4920 + pta_stats.pt_solution_includes_may_alias);
4921 fprintf (s, " pt_solutions_intersect: "
4922 HOST_WIDE_INT_PRINT_DEC" disambiguations, "
4923 HOST_WIDE_INT_PRINT_DEC" queries\n",
4924 pta_stats.pt_solutions_intersect_no_alias,
4925 pta_stats.pt_solutions_intersect_no_alias
4926 + pta_stats.pt_solutions_intersect_may_alias);
4930 /* Reset the points-to solution *PT to a conservative default
4931 (point to anything). */
4933 void
4934 pt_solution_reset (struct pt_solution *pt)
4936 memset (pt, 0, sizeof (struct pt_solution));
4937 pt->anything = true;
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;
5067 /* Dump points-to information to OUTFILE. */
5069 static void
5070 dump_sa_points_to_info (FILE *outfile)
5072 unsigned int i;
5074 fprintf (outfile, "\nPoints-to sets\n\n");
5076 if (dump_flags & TDF_STATS)
5078 fprintf (outfile, "Stats:\n");
5079 fprintf (outfile, "Total vars: %d\n", stats.total_vars);
5080 fprintf (outfile, "Non-pointer vars: %d\n",
5081 stats.nonpointer_vars);
5082 fprintf (outfile, "Statically unified vars: %d\n",
5083 stats.unified_vars_static);
5084 fprintf (outfile, "Dynamically unified vars: %d\n",
5085 stats.unified_vars_dynamic);
5086 fprintf (outfile, "Iterations: %d\n", stats.iterations);
5087 fprintf (outfile, "Number of edges: %d\n", stats.num_edges);
5088 fprintf (outfile, "Number of implicit edges: %d\n",
5089 stats.num_implicit_edges);
5092 for (i = 0; i < VEC_length (varinfo_t, varmap); i++)
5093 dump_solution_for_var (outfile, i);
5097 /* Debug points-to information to stderr. */
5099 void
5100 debug_sa_points_to_info (void)
5102 dump_sa_points_to_info (stderr);
5106 /* Initialize the always-existing constraint variables for NULL
5107 ANYTHING, READONLY, and INTEGER */
5109 static void
5110 init_base_vars (void)
5112 struct constraint_expr lhs, rhs;
5114 /* Create the NULL variable, used to represent that a variable points
5115 to NULL. */
5116 nothing_tree = create_tmp_var_raw (void_type_node, "NULL");
5117 var_nothing = new_var_info (nothing_tree, nothing_id, "NULL");
5118 insert_vi_for_tree (nothing_tree, var_nothing);
5119 var_nothing->is_artificial_var = 1;
5120 var_nothing->offset = 0;
5121 var_nothing->size = ~0;
5122 var_nothing->fullsize = ~0;
5123 var_nothing->is_special_var = 1;
5124 VEC_safe_push (varinfo_t, heap, varmap, var_nothing);
5126 /* Create the ANYTHING variable, used to represent that a variable
5127 points to some unknown piece of memory. */
5128 anything_tree = create_tmp_var_raw (ptr_type_node, "ANYTHING");
5129 var_anything = new_var_info (anything_tree, anything_id, "ANYTHING");
5130 insert_vi_for_tree (anything_tree, var_anything);
5131 var_anything->is_artificial_var = 1;
5132 var_anything->size = ~0;
5133 var_anything->offset = 0;
5134 var_anything->next = NULL;
5135 var_anything->fullsize = ~0;
5136 var_anything->is_special_var = 1;
5138 /* Anything points to anything. This makes deref constraints just
5139 work in the presence of linked list and other p = *p type loops,
5140 by saying that *ANYTHING = ANYTHING. */
5141 VEC_safe_push (varinfo_t, heap, varmap, var_anything);
5142 lhs.type = SCALAR;
5143 lhs.var = anything_id;
5144 lhs.offset = 0;
5145 rhs.type = ADDRESSOF;
5146 rhs.var = anything_id;
5147 rhs.offset = 0;
5149 /* This specifically does not use process_constraint because
5150 process_constraint ignores all anything = anything constraints, since all
5151 but this one are redundant. */
5152 VEC_safe_push (constraint_t, heap, constraints, new_constraint (lhs, rhs));
5154 /* Create the READONLY variable, used to represent that a variable
5155 points to readonly memory. */
5156 readonly_tree = create_tmp_var_raw (ptr_type_node, "READONLY");
5157 var_readonly = new_var_info (readonly_tree, readonly_id, "READONLY");
5158 var_readonly->is_artificial_var = 1;
5159 var_readonly->offset = 0;
5160 var_readonly->size = ~0;
5161 var_readonly->fullsize = ~0;
5162 var_readonly->next = NULL;
5163 var_readonly->is_special_var = 1;
5164 insert_vi_for_tree (readonly_tree, var_readonly);
5165 VEC_safe_push (varinfo_t, heap, varmap, var_readonly);
5167 /* readonly memory points to anything, in order to make deref
5168 easier. In reality, it points to anything the particular
5169 readonly variable can point to, but we don't track this
5170 separately. */
5171 lhs.type = SCALAR;
5172 lhs.var = readonly_id;
5173 lhs.offset = 0;
5174 rhs.type = ADDRESSOF;
5175 rhs.var = readonly_id; /* FIXME */
5176 rhs.offset = 0;
5177 process_constraint (new_constraint (lhs, rhs));
5179 /* Create the ESCAPED variable, used to represent the set of escaped
5180 memory. */
5181 escaped_tree = create_tmp_var_raw (ptr_type_node, "ESCAPED");
5182 var_escaped = new_var_info (escaped_tree, escaped_id, "ESCAPED");
5183 insert_vi_for_tree (escaped_tree, var_escaped);
5184 var_escaped->is_artificial_var = 1;
5185 var_escaped->offset = 0;
5186 var_escaped->size = ~0;
5187 var_escaped->fullsize = ~0;
5188 var_escaped->is_special_var = 0;
5189 VEC_safe_push (varinfo_t, heap, varmap, var_escaped);
5190 gcc_assert (VEC_index (varinfo_t, varmap, 3) == var_escaped);
5192 /* Create the NONLOCAL variable, used to represent the set of nonlocal
5193 memory. */
5194 nonlocal_tree = create_tmp_var_raw (ptr_type_node, "NONLOCAL");
5195 var_nonlocal = new_var_info (nonlocal_tree, nonlocal_id, "NONLOCAL");
5196 insert_vi_for_tree (nonlocal_tree, var_nonlocal);
5197 var_nonlocal->is_artificial_var = 1;
5198 var_nonlocal->offset = 0;
5199 var_nonlocal->size = ~0;
5200 var_nonlocal->fullsize = ~0;
5201 var_nonlocal->is_special_var = 1;
5202 VEC_safe_push (varinfo_t, heap, varmap, var_nonlocal);
5204 /* ESCAPED = *ESCAPED, because escaped is may-deref'd at calls, etc. */
5205 lhs.type = SCALAR;
5206 lhs.var = escaped_id;
5207 lhs.offset = 0;
5208 rhs.type = DEREF;
5209 rhs.var = escaped_id;
5210 rhs.offset = 0;
5211 process_constraint (new_constraint (lhs, rhs));
5213 /* ESCAPED = ESCAPED + UNKNOWN_OFFSET, because if a sub-field escapes the
5214 whole variable escapes. */
5215 lhs.type = SCALAR;
5216 lhs.var = escaped_id;
5217 lhs.offset = 0;
5218 rhs.type = SCALAR;
5219 rhs.var = escaped_id;
5220 rhs.offset = UNKNOWN_OFFSET;
5221 process_constraint (new_constraint (lhs, rhs));
5223 /* *ESCAPED = NONLOCAL. This is true because we have to assume
5224 everything pointed to by escaped points to what global memory can
5225 point to. */
5226 lhs.type = DEREF;
5227 lhs.var = escaped_id;
5228 lhs.offset = 0;
5229 rhs.type = SCALAR;
5230 rhs.var = nonlocal_id;
5231 rhs.offset = 0;
5232 process_constraint (new_constraint (lhs, rhs));
5234 /* NONLOCAL = &NONLOCAL, NONLOCAL = &ESCAPED. This is true because
5235 global memory may point to global memory and escaped memory. */
5236 lhs.type = SCALAR;
5237 lhs.var = nonlocal_id;
5238 lhs.offset = 0;
5239 rhs.type = ADDRESSOF;
5240 rhs.var = nonlocal_id;
5241 rhs.offset = 0;
5242 process_constraint (new_constraint (lhs, rhs));
5243 rhs.type = ADDRESSOF;
5244 rhs.var = escaped_id;
5245 rhs.offset = 0;
5246 process_constraint (new_constraint (lhs, rhs));
5248 /* Create the CALLUSED variable, used to represent the set of call-used
5249 memory. */
5250 callused_tree = create_tmp_var_raw (ptr_type_node, "CALLUSED");
5251 var_callused = new_var_info (callused_tree, callused_id, "CALLUSED");
5252 insert_vi_for_tree (callused_tree, var_callused);
5253 var_callused->is_artificial_var = 1;
5254 var_callused->offset = 0;
5255 var_callused->size = ~0;
5256 var_callused->fullsize = ~0;
5257 var_callused->is_special_var = 0;
5258 VEC_safe_push (varinfo_t, heap, varmap, var_callused);
5260 /* CALLUSED = *CALLUSED, because call-used is may-deref'd at calls, etc. */
5261 lhs.type = SCALAR;
5262 lhs.var = callused_id;
5263 lhs.offset = 0;
5264 rhs.type = DEREF;
5265 rhs.var = callused_id;
5266 rhs.offset = 0;
5267 process_constraint (new_constraint (lhs, rhs));
5269 /* CALLUSED = CALLUSED + UNKNOWN, because if a sub-field is call-used the
5270 whole variable is call-used. */
5271 lhs.type = SCALAR;
5272 lhs.var = callused_id;
5273 lhs.offset = 0;
5274 rhs.type = SCALAR;
5275 rhs.var = callused_id;
5276 rhs.offset = UNKNOWN_OFFSET;
5277 process_constraint (new_constraint (lhs, rhs));
5279 /* Create the STOREDANYTHING variable, used to represent the set of
5280 variables stored to *ANYTHING. */
5281 storedanything_tree = create_tmp_var_raw (ptr_type_node, "STOREDANYTHING");
5282 var_storedanything = new_var_info (storedanything_tree, storedanything_id,
5283 "STOREDANYTHING");
5284 insert_vi_for_tree (storedanything_tree, var_storedanything);
5285 var_storedanything->is_artificial_var = 1;
5286 var_storedanything->offset = 0;
5287 var_storedanything->size = ~0;
5288 var_storedanything->fullsize = ~0;
5289 var_storedanything->is_special_var = 0;
5290 VEC_safe_push (varinfo_t, heap, varmap, var_storedanything);
5292 /* Create the INTEGER variable, used to represent that a variable points
5293 to what an INTEGER "points to". */
5294 integer_tree = create_tmp_var_raw (ptr_type_node, "INTEGER");
5295 var_integer = new_var_info (integer_tree, integer_id, "INTEGER");
5296 insert_vi_for_tree (integer_tree, var_integer);
5297 var_integer->is_artificial_var = 1;
5298 var_integer->size = ~0;
5299 var_integer->fullsize = ~0;
5300 var_integer->offset = 0;
5301 var_integer->next = NULL;
5302 var_integer->is_special_var = 1;
5303 VEC_safe_push (varinfo_t, heap, varmap, var_integer);
5305 /* INTEGER = ANYTHING, because we don't know where a dereference of
5306 a random integer will point to. */
5307 lhs.type = SCALAR;
5308 lhs.var = integer_id;
5309 lhs.offset = 0;
5310 rhs.type = ADDRESSOF;
5311 rhs.var = anything_id;
5312 rhs.offset = 0;
5313 process_constraint (new_constraint (lhs, rhs));
5316 /* Initialize things necessary to perform PTA */
5318 static void
5319 init_alias_vars (void)
5321 use_field_sensitive = (MAX_FIELDS_FOR_FIELD_SENSITIVE > 1);
5323 bitmap_obstack_initialize (&pta_obstack);
5324 bitmap_obstack_initialize (&oldpta_obstack);
5325 bitmap_obstack_initialize (&predbitmap_obstack);
5327 constraint_pool = create_alloc_pool ("Constraint pool",
5328 sizeof (struct constraint), 30);
5329 variable_info_pool = create_alloc_pool ("Variable info pool",
5330 sizeof (struct variable_info), 30);
5331 constraints = VEC_alloc (constraint_t, heap, 8);
5332 varmap = VEC_alloc (varinfo_t, heap, 8);
5333 vi_for_tree = pointer_map_create ();
5335 memset (&stats, 0, sizeof (stats));
5336 shared_bitmap_table = htab_create (511, shared_bitmap_hash,
5337 shared_bitmap_eq, free);
5338 init_base_vars ();
5341 /* Remove the REF and ADDRESS edges from GRAPH, as well as all the
5342 predecessor edges. */
5344 static void
5345 remove_preds_and_fake_succs (constraint_graph_t graph)
5347 unsigned int i;
5349 /* Clear the implicit ref and address nodes from the successor
5350 lists. */
5351 for (i = 0; i < FIRST_REF_NODE; i++)
5353 if (graph->succs[i])
5354 bitmap_clear_range (graph->succs[i], FIRST_REF_NODE,
5355 FIRST_REF_NODE * 2);
5358 /* Free the successor list for the non-ref nodes. */
5359 for (i = FIRST_REF_NODE; i < graph->size; i++)
5361 if (graph->succs[i])
5362 BITMAP_FREE (graph->succs[i]);
5365 /* Now reallocate the size of the successor list as, and blow away
5366 the predecessor bitmaps. */
5367 graph->size = VEC_length (varinfo_t, varmap);
5368 graph->succs = XRESIZEVEC (bitmap, graph->succs, graph->size);
5370 free (graph->implicit_preds);
5371 graph->implicit_preds = NULL;
5372 free (graph->preds);
5373 graph->preds = NULL;
5374 bitmap_obstack_release (&predbitmap_obstack);
5377 /* Compute the set of variables we can't TBAA prune. */
5379 static void
5380 compute_tbaa_pruning (void)
5382 unsigned int size = VEC_length (varinfo_t, varmap);
5383 unsigned int i;
5384 bool any;
5386 changed_count = 0;
5387 changed = sbitmap_alloc (size);
5388 sbitmap_zero (changed);
5390 /* Mark all initial no_tbaa_pruning nodes as changed. */
5391 any = false;
5392 for (i = 0; i < size; ++i)
5394 varinfo_t ivi = get_varinfo (i);
5396 if (find (i) == i && ivi->no_tbaa_pruning)
5398 any = true;
5399 if ((graph->succs[i] && !bitmap_empty_p (graph->succs[i]))
5400 || VEC_length (constraint_t, graph->complex[i]) > 0)
5402 SET_BIT (changed, i);
5403 ++changed_count;
5408 while (changed_count > 0)
5410 struct topo_info *ti = init_topo_info ();
5411 ++stats.iterations;
5413 compute_topo_order (graph, ti);
5415 while (VEC_length (unsigned, ti->topo_order) != 0)
5417 bitmap_iterator bi;
5419 i = VEC_pop (unsigned, ti->topo_order);
5421 /* If this variable is not a representative, skip it. */
5422 if (find (i) != i)
5423 continue;
5425 /* If the node has changed, we need to process the complex
5426 constraints and outgoing edges again. */
5427 if (TEST_BIT (changed, i))
5429 unsigned int j;
5430 constraint_t c;
5431 VEC(constraint_t,heap) *complex = graph->complex[i];
5433 RESET_BIT (changed, i);
5434 --changed_count;
5436 /* Process the complex copy constraints. */
5437 for (j = 0; VEC_iterate (constraint_t, complex, j, c); ++j)
5439 if (c->lhs.type == SCALAR && c->rhs.type == SCALAR)
5441 varinfo_t lhsvi = get_varinfo (find (c->lhs.var));
5443 if (!lhsvi->no_tbaa_pruning)
5445 lhsvi->no_tbaa_pruning = true;
5446 if (!TEST_BIT (changed, lhsvi->id))
5448 SET_BIT (changed, lhsvi->id);
5449 ++changed_count;
5455 /* Propagate to all successors. */
5456 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i], 0, j, bi)
5458 unsigned int to = find (j);
5459 varinfo_t tovi = get_varinfo (to);
5461 /* Don't propagate to ourselves. */
5462 if (to == i)
5463 continue;
5465 if (!tovi->no_tbaa_pruning)
5467 tovi->no_tbaa_pruning = true;
5468 if (!TEST_BIT (changed, to))
5470 SET_BIT (changed, to);
5471 ++changed_count;
5478 free_topo_info (ti);
5481 sbitmap_free (changed);
5483 if (any)
5485 for (i = 0; i < size; ++i)
5487 varinfo_t ivi = get_varinfo (i);
5488 varinfo_t ivip = get_varinfo (find (i));
5490 if (ivip->no_tbaa_pruning)
5492 tree var = ivi->decl;
5494 if (TREE_CODE (var) == SSA_NAME)
5495 var = SSA_NAME_VAR (var);
5497 if (POINTER_TYPE_P (TREE_TYPE (var)))
5499 DECL_NO_TBAA_P (var) = 1;
5501 /* Tell the RTL layer that this pointer can alias
5502 anything. */
5503 DECL_POINTER_ALIAS_SET (var) = 0;
5510 /* Initialize the heapvar for statement mapping. */
5512 static void
5513 init_alias_heapvars (void)
5515 if (!heapvar_for_stmt)
5516 heapvar_for_stmt = htab_create_ggc (11, tree_map_hash, tree_map_eq,
5517 NULL);
5520 /* Delete the heapvar for statement mapping. */
5522 void
5523 delete_alias_heapvars (void)
5525 if (heapvar_for_stmt)
5526 htab_delete (heapvar_for_stmt);
5527 heapvar_for_stmt = NULL;
5530 /* Create points-to sets for the current function. See the comments
5531 at the start of the file for an algorithmic overview. */
5533 static void
5534 compute_points_to_sets (void)
5536 struct scc_info *si;
5537 basic_block bb;
5538 unsigned i;
5539 sbitmap dereferenced_ptrs;
5541 timevar_push (TV_TREE_PTA);
5543 init_alias_vars ();
5544 init_alias_heapvars ();
5546 intra_create_variable_infos ();
5548 /* A bitmap of SSA_NAME pointers that are dereferenced. This is
5549 used to track which points-to sets may be TBAA pruned. */
5550 dereferenced_ptrs = sbitmap_alloc (num_ssa_names);
5551 sbitmap_zero (dereferenced_ptrs);
5553 /* Now walk all statements and derive aliases. */
5554 FOR_EACH_BB (bb)
5556 gimple_stmt_iterator gsi;
5558 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5560 gimple phi = gsi_stmt (gsi);
5562 if (is_gimple_reg (gimple_phi_result (phi)))
5563 find_func_aliases (phi);
5566 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5568 gimple stmt = gsi_stmt (gsi);
5569 use_operand_p use_p;
5570 ssa_op_iter iter;
5572 /* Mark dereferenced pointers. This is used by TBAA pruning
5573 of the points-to sets and the alias warning machinery. */
5574 FOR_EACH_SSA_USE_OPERAND (use_p, stmt, iter, SSA_OP_USE)
5576 unsigned num_uses, num_loads, num_stores;
5577 tree op = USE_FROM_PTR (use_p);
5579 if (!POINTER_TYPE_P (TREE_TYPE (op)))
5580 continue;
5582 /* Determine whether OP is a dereferenced pointer. */
5583 count_uses_and_derefs (op, stmt,
5584 &num_uses, &num_loads, &num_stores);
5585 if (num_loads + num_stores > 0)
5586 SET_BIT (dereferenced_ptrs, SSA_NAME_VERSION (op));
5589 find_func_aliases (stmt);
5594 if (dump_file)
5596 fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
5597 dump_constraints (dump_file);
5600 if (dump_file)
5601 fprintf (dump_file,
5602 "\nCollapsing static cycles and doing variable "
5603 "substitution\n");
5605 init_graph (VEC_length (varinfo_t, varmap) * 2);
5607 if (dump_file)
5608 fprintf (dump_file, "Building predecessor graph\n");
5609 build_pred_graph ();
5611 if (dump_file)
5612 fprintf (dump_file, "Detecting pointer and location "
5613 "equivalences\n");
5614 si = perform_var_substitution (graph);
5616 if (dump_file)
5617 fprintf (dump_file, "Rewriting constraints and unifying "
5618 "variables\n");
5619 rewrite_constraints (graph, si);
5621 build_succ_graph ();
5622 free_var_substitution_info (si);
5624 if (dump_file && (dump_flags & TDF_GRAPH))
5625 dump_constraint_graph (dump_file);
5627 move_complex_constraints (graph);
5629 if (dump_file)
5630 fprintf (dump_file, "Uniting pointer but not location equivalent "
5631 "variables\n");
5632 unite_pointer_equivalences (graph);
5634 if (dump_file)
5635 fprintf (dump_file, "Finding indirect cycles\n");
5636 find_indirect_cycles (graph);
5638 /* Implicit nodes and predecessors are no longer necessary at this
5639 point. */
5640 remove_preds_and_fake_succs (graph);
5642 if (dump_file)
5643 fprintf (dump_file, "Solving graph\n");
5645 solve_graph (graph);
5647 compute_tbaa_pruning ();
5649 if (dump_file)
5650 dump_sa_points_to_info (dump_file);
5652 /* Compute the points-to sets for ESCAPED and CALLUSED used for
5653 call-clobber analysis. */
5654 find_what_var_points_to (var_escaped, &cfun->gimple_df->escaped, false);
5655 find_what_var_points_to (var_callused, &cfun->gimple_df->callused, false);
5657 /* Make sure the ESCAPED solution (which is used as placeholder in
5658 other solutions) does not reference itself. This simplifies
5659 points-to solution queries. */
5660 cfun->gimple_df->escaped.escaped = 0;
5662 /* Compute the points-to sets for pointer SSA_NAMEs. */
5663 for (i = 0; i < num_ssa_names; ++i)
5665 tree ptr = ssa_name (i);
5666 if (ptr
5667 && POINTER_TYPE_P (TREE_TYPE (ptr)))
5668 find_what_p_points_to (ptr, TEST_BIT (dereferenced_ptrs, i));
5670 sbitmap_free (dereferenced_ptrs);
5672 timevar_pop (TV_TREE_PTA);
5674 have_alias_info = true;
5678 /* Delete created points-to sets. */
5680 static void
5681 delete_points_to_sets (void)
5683 unsigned int i;
5685 htab_delete (shared_bitmap_table);
5686 if (dump_file && (dump_flags & TDF_STATS))
5687 fprintf (dump_file, "Points to sets created:%d\n",
5688 stats.points_to_sets_created);
5690 pointer_map_destroy (vi_for_tree);
5691 bitmap_obstack_release (&pta_obstack);
5692 VEC_free (constraint_t, heap, constraints);
5694 for (i = 0; i < graph->size; i++)
5695 VEC_free (constraint_t, heap, graph->complex[i]);
5696 free (graph->complex);
5698 free (graph->rep);
5699 free (graph->succs);
5700 free (graph->pe);
5701 free (graph->pe_rep);
5702 free (graph->indirect_cycles);
5703 free (graph);
5705 VEC_free (varinfo_t, heap, varmap);
5706 free_alloc_pool (variable_info_pool);
5707 free_alloc_pool (constraint_pool);
5708 have_alias_info = false;
5712 /* Compute points-to information for every SSA_NAME pointer in the
5713 current function and compute the transitive closure of escaped
5714 variables to re-initialize the call-clobber states of local variables. */
5716 unsigned int
5717 compute_may_aliases (void)
5719 /* For each pointer P_i, determine the sets of variables that P_i may
5720 point-to. Compute the reachability set of escaped and call-used
5721 variables. */
5722 compute_points_to_sets ();
5724 /* Debugging dumps. */
5725 if (dump_file)
5727 dump_alias_info (dump_file);
5729 if (dump_flags & TDF_DETAILS)
5730 dump_referenced_vars (dump_file);
5733 /* Deallocate memory used by aliasing data structures and the internal
5734 points-to solution. */
5735 delete_points_to_sets ();
5737 gcc_assert (!need_ssa_update_p (cfun));
5739 return 0;
5743 /* A dummy pass to cause points-to information to be computed via
5744 TODO_rebuild_alias. */
5746 struct gimple_opt_pass pass_build_alias =
5749 GIMPLE_PASS,
5750 "alias", /* name */
5751 NULL, /* gate */
5752 NULL, /* execute */
5753 NULL, /* sub */
5754 NULL, /* next */
5755 0, /* static_pass_number */
5756 TV_NONE, /* tv_id */
5757 PROP_cfg | PROP_ssa, /* properties_required */
5758 PROP_alias, /* properties_provided */
5759 0, /* properties_destroyed */
5760 0, /* todo_flags_start */
5761 TODO_rebuild_alias | TODO_dump_func /* todo_flags_finish */
5766 /* Return true if we should execute IPA PTA. */
5767 static bool
5768 gate_ipa_pta (void)
5770 return (flag_ipa_pta
5771 /* Don't bother doing anything if the program has errors. */
5772 && !(errorcount || sorrycount));
5775 /* Execute the driver for IPA PTA. */
5776 static unsigned int
5777 ipa_pta_execute (void)
5779 struct cgraph_node *node;
5780 struct scc_info *si;
5782 in_ipa_mode = 1;
5783 init_alias_heapvars ();
5784 init_alias_vars ();
5786 for (node = cgraph_nodes; node; node = node->next)
5788 unsigned int varid;
5790 varid = create_function_info_for (node->decl,
5791 cgraph_node_name (node));
5792 if (node->local.externally_visible)
5794 varinfo_t fi = get_varinfo (varid);
5795 for (; fi; fi = fi->next)
5796 make_constraint_from (fi, anything_id);
5799 for (node = cgraph_nodes; node; node = node->next)
5801 if (node->analyzed)
5803 struct function *func = DECL_STRUCT_FUNCTION (node->decl);
5804 basic_block bb;
5805 tree old_func_decl = current_function_decl;
5806 if (dump_file)
5807 fprintf (dump_file,
5808 "Generating constraints for %s\n",
5809 cgraph_node_name (node));
5810 push_cfun (func);
5811 current_function_decl = node->decl;
5813 FOR_EACH_BB_FN (bb, func)
5815 gimple_stmt_iterator gsi;
5817 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
5818 gsi_next (&gsi))
5820 gimple phi = gsi_stmt (gsi);
5822 if (is_gimple_reg (gimple_phi_result (phi)))
5823 find_func_aliases (phi);
5826 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
5827 find_func_aliases (gsi_stmt (gsi));
5829 current_function_decl = old_func_decl;
5830 pop_cfun ();
5832 else
5834 /* Make point to anything. */
5838 if (dump_file)
5840 fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
5841 dump_constraints (dump_file);
5844 if (dump_file)
5845 fprintf (dump_file,
5846 "\nCollapsing static cycles and doing variable "
5847 "substitution:\n");
5849 init_graph (VEC_length (varinfo_t, varmap) * 2);
5850 build_pred_graph ();
5851 si = perform_var_substitution (graph);
5852 rewrite_constraints (graph, si);
5854 build_succ_graph ();
5855 free_var_substitution_info (si);
5856 move_complex_constraints (graph);
5857 unite_pointer_equivalences (graph);
5858 find_indirect_cycles (graph);
5860 /* Implicit nodes and predecessors are no longer necessary at this
5861 point. */
5862 remove_preds_and_fake_succs (graph);
5864 if (dump_file)
5865 fprintf (dump_file, "\nSolving graph\n");
5867 solve_graph (graph);
5869 if (dump_file)
5870 dump_sa_points_to_info (dump_file);
5872 in_ipa_mode = 0;
5873 delete_alias_heapvars ();
5874 delete_points_to_sets ();
5875 return 0;
5878 struct simple_ipa_opt_pass pass_ipa_pta =
5881 SIMPLE_IPA_PASS,
5882 "pta", /* name */
5883 gate_ipa_pta, /* gate */
5884 ipa_pta_execute, /* execute */
5885 NULL, /* sub */
5886 NULL, /* next */
5887 0, /* static_pass_number */
5888 TV_IPA_PTA, /* tv_id */
5889 0, /* properties_required */
5890 0, /* properties_provided */
5891 0, /* properties_destroyed */
5892 0, /* todo_flags_start */
5893 TODO_update_ssa /* todo_flags_finish */
5898 #include "gt-tree-ssa-structalias.h"