* lto-symtab.c (lto_varpool_replace_node): Merge TLS models.
[official-gcc.git] / gcc / tree-ssa-structalias.c
blob4c43b75730d64c5f9fe9250c7facd79d41c2f70a
1 /* Tree based points-to analysis
2 Copyright (C) 2005-2015 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 "obstack.h"
26 #include "bitmap.h"
27 #include "sbitmap.h"
28 #include "flags.h"
29 #include "predict.h"
30 #include "vec.h"
31 #include "hashtab.h"
32 #include "hash-set.h"
33 #include "machmode.h"
34 #include "hard-reg-set.h"
35 #include "input.h"
36 #include "function.h"
37 #include "dominance.h"
38 #include "cfg.h"
39 #include "basic-block.h"
40 #include "double-int.h"
41 #include "alias.h"
42 #include "symtab.h"
43 #include "wide-int.h"
44 #include "inchash.h"
45 #include "tree.h"
46 #include "fold-const.h"
47 #include "stor-layout.h"
48 #include "stmt.h"
49 #include "hash-table.h"
50 #include "tree-ssa-alias.h"
51 #include "internal-fn.h"
52 #include "gimple-expr.h"
53 #include "is-a.h"
54 #include "gimple.h"
55 #include "gimple-iterator.h"
56 #include "gimple-ssa.h"
57 #include "hash-map.h"
58 #include "plugin-api.h"
59 #include "ipa-ref.h"
60 #include "cgraph.h"
61 #include "stringpool.h"
62 #include "tree-ssanames.h"
63 #include "tree-into-ssa.h"
64 #include "rtl.h"
65 #include "statistics.h"
66 #include "real.h"
67 #include "fixed-value.h"
68 #include "insn-config.h"
69 #include "expmed.h"
70 #include "dojump.h"
71 #include "explow.h"
72 #include "calls.h"
73 #include "emit-rtl.h"
74 #include "varasm.h"
75 #include "expr.h"
76 #include "tree-dfa.h"
77 #include "tree-inline.h"
78 #include "diagnostic-core.h"
79 #include "tree-pass.h"
80 #include "alloc-pool.h"
81 #include "splay-tree.h"
82 #include "params.h"
83 #include "tree-phinodes.h"
84 #include "ssa-iterators.h"
85 #include "tree-pretty-print.h"
86 #include "gimple-walk.h"
88 /* The idea behind this analyzer is to generate set constraints from the
89 program, then solve the resulting constraints in order to generate the
90 points-to sets.
92 Set constraints are a way of modeling program analysis problems that
93 involve sets. They consist of an inclusion constraint language,
94 describing the variables (each variable is a set) and operations that
95 are involved on the variables, and a set of rules that derive facts
96 from these operations. To solve a system of set constraints, you derive
97 all possible facts under the rules, which gives you the correct sets
98 as a consequence.
100 See "Efficient Field-sensitive pointer analysis for C" by "David
101 J. Pearce and Paul H. J. Kelly and Chris Hankin, at
102 http://citeseer.ist.psu.edu/pearce04efficient.html
104 Also see "Ultra-fast Aliasing Analysis using CLA: A Million Lines
105 of C Code in a Second" by ""Nevin Heintze and Olivier Tardieu" at
106 http://citeseer.ist.psu.edu/heintze01ultrafast.html
108 There are three types of real constraint expressions, DEREF,
109 ADDRESSOF, and SCALAR. Each constraint expression consists
110 of a constraint type, a variable, and an offset.
112 SCALAR is a constraint expression type used to represent x, whether
113 it appears on the LHS or the RHS of a statement.
114 DEREF is a constraint expression type used to represent *x, whether
115 it appears on the LHS or the RHS of a statement.
116 ADDRESSOF is a constraint expression used to represent &x, whether
117 it appears on the LHS or the RHS of a statement.
119 Each pointer variable in the program is assigned an integer id, and
120 each field of a structure variable is assigned an integer id as well.
122 Structure variables are linked to their list of fields through a "next
123 field" in each variable that points to the next field in offset
124 order.
125 Each variable for a structure field has
127 1. "size", that tells the size in bits of that field.
128 2. "fullsize, that tells the size in bits of the entire structure.
129 3. "offset", that tells the offset in bits from the beginning of the
130 structure to this field.
132 Thus,
133 struct f
135 int a;
136 int b;
137 } foo;
138 int *bar;
140 looks like
142 foo.a -> id 1, size 32, offset 0, fullsize 64, next foo.b
143 foo.b -> id 2, size 32, offset 32, fullsize 64, next NULL
144 bar -> id 3, size 32, offset 0, fullsize 32, next NULL
147 In order to solve the system of set constraints, the following is
148 done:
150 1. Each constraint variable x has a solution set associated with it,
151 Sol(x).
153 2. Constraints are separated into direct, copy, and complex.
154 Direct constraints are ADDRESSOF constraints that require no extra
155 processing, such as P = &Q
156 Copy constraints are those of the form P = Q.
157 Complex constraints are all the constraints involving dereferences
158 and offsets (including offsetted copies).
160 3. All direct constraints of the form P = &Q are processed, such
161 that Q is added to Sol(P)
163 4. All complex constraints for a given constraint variable are stored in a
164 linked list attached to that variable's node.
166 5. A directed graph is built out of the copy constraints. Each
167 constraint variable is a node in the graph, and an edge from
168 Q to P is added for each copy constraint of the form P = Q
170 6. The graph is then walked, and solution sets are
171 propagated along the copy edges, such that an edge from Q to P
172 causes Sol(P) <- Sol(P) union Sol(Q).
174 7. As we visit each node, all complex constraints associated with
175 that node are processed by adding appropriate copy edges to the graph, or the
176 appropriate variables to the solution set.
178 8. The process of walking the graph is iterated until no solution
179 sets change.
181 Prior to walking the graph in steps 6 and 7, We perform static
182 cycle elimination on the constraint graph, as well
183 as off-line variable substitution.
185 TODO: Adding offsets to pointer-to-structures can be handled (IE not punted
186 on and turned into anything), but isn't. You can just see what offset
187 inside the pointed-to struct it's going to access.
189 TODO: Constant bounded arrays can be handled as if they were structs of the
190 same number of elements.
192 TODO: Modeling heap and incoming pointers becomes much better if we
193 add fields to them as we discover them, which we could do.
195 TODO: We could handle unions, but to be honest, it's probably not
196 worth the pain or slowdown. */
198 /* IPA-PTA optimizations possible.
200 When the indirect function called is ANYTHING we can add disambiguation
201 based on the function signatures (or simply the parameter count which
202 is the varinfo size). We also do not need to consider functions that
203 do not have their address taken.
205 The is_global_var bit which marks escape points is overly conservative
206 in IPA mode. Split it to is_escape_point and is_global_var - only
207 externally visible globals are escape points in IPA mode. This is
208 also needed to fix the pt_solution_includes_global predicate
209 (and thus ptr_deref_may_alias_global_p).
211 The way we introduce DECL_PT_UID to avoid fixing up all points-to
212 sets in the translation unit when we copy a DECL during inlining
213 pessimizes precision. The advantage is that the DECL_PT_UID keeps
214 compile-time and memory usage overhead low - the points-to sets
215 do not grow or get unshared as they would during a fixup phase.
216 An alternative solution is to delay IPA PTA until after all
217 inlining transformations have been applied.
219 The way we propagate clobber/use information isn't optimized.
220 It should use a new complex constraint that properly filters
221 out local variables of the callee (though that would make
222 the sets invalid after inlining). OTOH we might as well
223 admit defeat to WHOPR and simply do all the clobber/use analysis
224 and propagation after PTA finished but before we threw away
225 points-to information for memory variables. WHOPR and PTA
226 do not play along well anyway - the whole constraint solving
227 would need to be done in WPA phase and it will be very interesting
228 to apply the results to local SSA names during LTRANS phase.
230 We probably should compute a per-function unit-ESCAPE solution
231 propagating it simply like the clobber / uses solutions. The
232 solution can go alongside the non-IPA espaced solution and be
233 used to query which vars escape the unit through a function.
235 We never put function decls in points-to sets so we do not
236 keep the set of called functions for indirect calls.
238 And probably more. */
240 static bool use_field_sensitive = true;
241 static int in_ipa_mode = 0;
243 /* Used for predecessor bitmaps. */
244 static bitmap_obstack predbitmap_obstack;
246 /* Used for points-to sets. */
247 static bitmap_obstack pta_obstack;
249 /* Used for oldsolution members of variables. */
250 static bitmap_obstack oldpta_obstack;
252 /* Used for per-solver-iteration bitmaps. */
253 static bitmap_obstack iteration_obstack;
255 static unsigned int create_variable_info_for (tree, const char *);
256 typedef struct constraint_graph *constraint_graph_t;
257 static void unify_nodes (constraint_graph_t, unsigned int, unsigned int, bool);
259 struct constraint;
260 typedef struct constraint *constraint_t;
263 #define EXECUTE_IF_IN_NONNULL_BITMAP(a, b, c, d) \
264 if (a) \
265 EXECUTE_IF_SET_IN_BITMAP (a, b, c, d)
267 static struct constraint_stats
269 unsigned int total_vars;
270 unsigned int nonpointer_vars;
271 unsigned int unified_vars_static;
272 unsigned int unified_vars_dynamic;
273 unsigned int iterations;
274 unsigned int num_edges;
275 unsigned int num_implicit_edges;
276 unsigned int points_to_sets_created;
277 } stats;
279 struct variable_info
281 /* ID of this variable */
282 unsigned int id;
284 /* True if this is a variable created by the constraint analysis, such as
285 heap variables and constraints we had to break up. */
286 unsigned int is_artificial_var : 1;
288 /* True if this is a special variable whose solution set should not be
289 changed. */
290 unsigned int is_special_var : 1;
292 /* True for variables whose size is not known or variable. */
293 unsigned int is_unknown_size_var : 1;
295 /* True for (sub-)fields that represent a whole variable. */
296 unsigned int is_full_var : 1;
298 /* True if this is a heap variable. */
299 unsigned int is_heap_var : 1;
301 /* True if this field may contain pointers. */
302 unsigned int may_have_pointers : 1;
304 /* True if this field has only restrict qualified pointers. */
305 unsigned int only_restrict_pointers : 1;
307 /* True if this represents a heap var created for a restrict qualified
308 pointer. */
309 unsigned int is_restrict_var : 1;
311 /* True if this represents a global variable. */
312 unsigned int is_global_var : 1;
314 /* True if this represents a IPA function info. */
315 unsigned int is_fn_info : 1;
317 /* ??? Store somewhere better. */
318 unsigned short ruid;
320 /* The ID of the variable for the next field in this structure
321 or zero for the last field in this structure. */
322 unsigned next;
324 /* The ID of the variable for the first field in this structure. */
325 unsigned head;
327 /* Offset of this variable, in bits, from the base variable */
328 unsigned HOST_WIDE_INT offset;
330 /* Size of the variable, in bits. */
331 unsigned HOST_WIDE_INT size;
333 /* Full size of the base variable, in bits. */
334 unsigned HOST_WIDE_INT fullsize;
336 /* Name of this variable */
337 const char *name;
339 /* Tree that this variable is associated with. */
340 tree decl;
342 /* Points-to set for this variable. */
343 bitmap solution;
345 /* Old points-to set for this variable. */
346 bitmap oldsolution;
348 typedef struct variable_info *varinfo_t;
350 static varinfo_t first_vi_for_offset (varinfo_t, unsigned HOST_WIDE_INT);
351 static varinfo_t first_or_preceding_vi_for_offset (varinfo_t,
352 unsigned HOST_WIDE_INT);
353 static varinfo_t lookup_vi_for_tree (tree);
354 static inline bool type_can_have_subvars (const_tree);
356 /* Pool of variable info structures. */
357 static alloc_pool variable_info_pool;
359 /* Map varinfo to final pt_solution. */
360 static hash_map<varinfo_t, pt_solution *> *final_solutions;
361 struct obstack final_solutions_obstack;
363 /* Table of variable info structures for constraint variables.
364 Indexed directly by variable info id. */
365 static vec<varinfo_t> varmap;
367 /* Return the varmap element N */
369 static inline varinfo_t
370 get_varinfo (unsigned int n)
372 return varmap[n];
375 /* Return the next variable in the list of sub-variables of VI
376 or NULL if VI is the last sub-variable. */
378 static inline varinfo_t
379 vi_next (varinfo_t vi)
381 return get_varinfo (vi->next);
384 /* Static IDs for the special variables. Variable ID zero is unused
385 and used as terminator for the sub-variable chain. */
386 enum { nothing_id = 1, anything_id = 2, string_id = 3,
387 escaped_id = 4, nonlocal_id = 5,
388 storedanything_id = 6, integer_id = 7 };
390 /* Return a new variable info structure consisting for a variable
391 named NAME, and using constraint graph node NODE. Append it
392 to the vector of variable info structures. */
394 static varinfo_t
395 new_var_info (tree t, const char *name)
397 unsigned index = varmap.length ();
398 varinfo_t ret = (varinfo_t) pool_alloc (variable_info_pool);
400 ret->id = index;
401 ret->name = name;
402 ret->decl = t;
403 /* Vars without decl are artificial and do not have sub-variables. */
404 ret->is_artificial_var = (t == NULL_TREE);
405 ret->is_special_var = false;
406 ret->is_unknown_size_var = false;
407 ret->is_full_var = (t == NULL_TREE);
408 ret->is_heap_var = false;
409 ret->may_have_pointers = true;
410 ret->only_restrict_pointers = false;
411 ret->is_restrict_var = false;
412 ret->ruid = 0;
413 ret->is_global_var = (t == NULL_TREE);
414 ret->is_fn_info = false;
415 if (t && DECL_P (t))
416 ret->is_global_var = (is_global_var (t)
417 /* We have to treat even local register variables
418 as escape points. */
419 || (TREE_CODE (t) == VAR_DECL
420 && DECL_HARD_REGISTER (t)));
421 ret->solution = BITMAP_ALLOC (&pta_obstack);
422 ret->oldsolution = NULL;
423 ret->next = 0;
424 ret->head = ret->id;
426 stats.total_vars++;
428 varmap.safe_push (ret);
430 return ret;
434 /* A map mapping call statements to per-stmt variables for uses
435 and clobbers specific to the call. */
436 static hash_map<gimple, varinfo_t> *call_stmt_vars;
438 /* Lookup or create the variable for the call statement CALL. */
440 static varinfo_t
441 get_call_vi (gcall *call)
443 varinfo_t vi, vi2;
445 bool existed;
446 varinfo_t *slot_p = &call_stmt_vars->get_or_insert (call, &existed);
447 if (existed)
448 return *slot_p;
450 vi = new_var_info (NULL_TREE, "CALLUSED");
451 vi->offset = 0;
452 vi->size = 1;
453 vi->fullsize = 2;
454 vi->is_full_var = true;
456 vi2 = new_var_info (NULL_TREE, "CALLCLOBBERED");
457 vi2->offset = 1;
458 vi2->size = 1;
459 vi2->fullsize = 2;
460 vi2->is_full_var = true;
462 vi->next = vi2->id;
464 *slot_p = vi;
465 return vi;
468 /* Lookup the variable for the call statement CALL representing
469 the uses. Returns NULL if there is nothing special about this call. */
471 static varinfo_t
472 lookup_call_use_vi (gcall *call)
474 varinfo_t *slot_p = call_stmt_vars->get (call);
475 if (slot_p)
476 return *slot_p;
478 return NULL;
481 /* Lookup the variable for the call statement CALL representing
482 the clobbers. Returns NULL if there is nothing special about this call. */
484 static varinfo_t
485 lookup_call_clobber_vi (gcall *call)
487 varinfo_t uses = lookup_call_use_vi (call);
488 if (!uses)
489 return NULL;
491 return vi_next (uses);
494 /* Lookup or create the variable for the call statement CALL representing
495 the uses. */
497 static varinfo_t
498 get_call_use_vi (gcall *call)
500 return get_call_vi (call);
503 /* Lookup or create the variable for the call statement CALL representing
504 the clobbers. */
506 static varinfo_t ATTRIBUTE_UNUSED
507 get_call_clobber_vi (gcall *call)
509 return vi_next (get_call_vi (call));
513 typedef enum {SCALAR, DEREF, ADDRESSOF} constraint_expr_type;
515 /* An expression that appears in a constraint. */
517 struct constraint_expr
519 /* Constraint type. */
520 constraint_expr_type type;
522 /* Variable we are referring to in the constraint. */
523 unsigned int var;
525 /* Offset, in bits, of this constraint from the beginning of
526 variables it ends up referring to.
528 IOW, in a deref constraint, we would deref, get the result set,
529 then add OFFSET to each member. */
530 HOST_WIDE_INT offset;
533 /* Use 0x8000... as special unknown offset. */
534 #define UNKNOWN_OFFSET HOST_WIDE_INT_MIN
536 typedef struct constraint_expr ce_s;
537 static void get_constraint_for_1 (tree, vec<ce_s> *, bool, bool);
538 static void get_constraint_for (tree, vec<ce_s> *);
539 static void get_constraint_for_rhs (tree, vec<ce_s> *);
540 static void do_deref (vec<ce_s> *);
542 /* Our set constraints are made up of two constraint expressions, one
543 LHS, and one RHS.
545 As described in the introduction, our set constraints each represent an
546 operation between set valued variables.
548 struct constraint
550 struct constraint_expr lhs;
551 struct constraint_expr rhs;
554 /* List of constraints that we use to build the constraint graph from. */
556 static vec<constraint_t> constraints;
557 static alloc_pool constraint_pool;
559 /* The constraint graph is represented as an array of bitmaps
560 containing successor nodes. */
562 struct constraint_graph
564 /* Size of this graph, which may be different than the number of
565 nodes in the variable map. */
566 unsigned int size;
568 /* Explicit successors of each node. */
569 bitmap *succs;
571 /* Implicit predecessors of each node (Used for variable
572 substitution). */
573 bitmap *implicit_preds;
575 /* Explicit predecessors of each node (Used for variable substitution). */
576 bitmap *preds;
578 /* Indirect cycle representatives, or -1 if the node has no indirect
579 cycles. */
580 int *indirect_cycles;
582 /* Representative node for a node. rep[a] == a unless the node has
583 been unified. */
584 unsigned int *rep;
586 /* Equivalence class representative for a label. This is used for
587 variable substitution. */
588 int *eq_rep;
590 /* Pointer equivalence label for a node. All nodes with the same
591 pointer equivalence label can be unified together at some point
592 (either during constraint optimization or after the constraint
593 graph is built). */
594 unsigned int *pe;
596 /* Pointer equivalence representative for a label. This is used to
597 handle nodes that are pointer equivalent but not location
598 equivalent. We can unite these once the addressof constraints
599 are transformed into initial points-to sets. */
600 int *pe_rep;
602 /* Pointer equivalence label for each node, used during variable
603 substitution. */
604 unsigned int *pointer_label;
606 /* Location equivalence label for each node, used during location
607 equivalence finding. */
608 unsigned int *loc_label;
610 /* Pointed-by set for each node, used during location equivalence
611 finding. This is pointed-by rather than pointed-to, because it
612 is constructed using the predecessor graph. */
613 bitmap *pointed_by;
615 /* Points to sets for pointer equivalence. This is *not* the actual
616 points-to sets for nodes. */
617 bitmap *points_to;
619 /* Bitmap of nodes where the bit is set if the node is a direct
620 node. Used for variable substitution. */
621 sbitmap direct_nodes;
623 /* Bitmap of nodes where the bit is set if the node is address
624 taken. Used for variable substitution. */
625 bitmap address_taken;
627 /* Vector of complex constraints for each graph node. Complex
628 constraints are those involving dereferences or offsets that are
629 not 0. */
630 vec<constraint_t> *complex;
633 static constraint_graph_t graph;
635 /* During variable substitution and the offline version of indirect
636 cycle finding, we create nodes to represent dereferences and
637 address taken constraints. These represent where these start and
638 end. */
639 #define FIRST_REF_NODE (varmap).length ()
640 #define LAST_REF_NODE (FIRST_REF_NODE + (FIRST_REF_NODE - 1))
642 /* Return the representative node for NODE, if NODE has been unioned
643 with another NODE.
644 This function performs path compression along the way to finding
645 the representative. */
647 static unsigned int
648 find (unsigned int node)
650 gcc_checking_assert (node < graph->size);
651 if (graph->rep[node] != node)
652 return graph->rep[node] = find (graph->rep[node]);
653 return node;
656 /* Union the TO and FROM nodes to the TO nodes.
657 Note that at some point in the future, we may want to do
658 union-by-rank, in which case we are going to have to return the
659 node we unified to. */
661 static bool
662 unite (unsigned int to, unsigned int from)
664 gcc_checking_assert (to < graph->size && from < graph->size);
665 if (to != from && graph->rep[from] != to)
667 graph->rep[from] = to;
668 return true;
670 return false;
673 /* Create a new constraint consisting of LHS and RHS expressions. */
675 static constraint_t
676 new_constraint (const struct constraint_expr lhs,
677 const struct constraint_expr rhs)
679 constraint_t ret = (constraint_t) pool_alloc (constraint_pool);
680 ret->lhs = lhs;
681 ret->rhs = rhs;
682 return ret;
685 /* Print out constraint C to FILE. */
687 static void
688 dump_constraint (FILE *file, constraint_t c)
690 if (c->lhs.type == ADDRESSOF)
691 fprintf (file, "&");
692 else if (c->lhs.type == DEREF)
693 fprintf (file, "*");
694 fprintf (file, "%s", get_varinfo (c->lhs.var)->name);
695 if (c->lhs.offset == UNKNOWN_OFFSET)
696 fprintf (file, " + UNKNOWN");
697 else if (c->lhs.offset != 0)
698 fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->lhs.offset);
699 fprintf (file, " = ");
700 if (c->rhs.type == ADDRESSOF)
701 fprintf (file, "&");
702 else if (c->rhs.type == DEREF)
703 fprintf (file, "*");
704 fprintf (file, "%s", get_varinfo (c->rhs.var)->name);
705 if (c->rhs.offset == UNKNOWN_OFFSET)
706 fprintf (file, " + UNKNOWN");
707 else if (c->rhs.offset != 0)
708 fprintf (file, " + " HOST_WIDE_INT_PRINT_DEC, c->rhs.offset);
712 void debug_constraint (constraint_t);
713 void debug_constraints (void);
714 void debug_constraint_graph (void);
715 void debug_solution_for_var (unsigned int);
716 void debug_sa_points_to_info (void);
718 /* Print out constraint C to stderr. */
720 DEBUG_FUNCTION void
721 debug_constraint (constraint_t c)
723 dump_constraint (stderr, c);
724 fprintf (stderr, "\n");
727 /* Print out all constraints to FILE */
729 static void
730 dump_constraints (FILE *file, int from)
732 int i;
733 constraint_t c;
734 for (i = from; constraints.iterate (i, &c); i++)
735 if (c)
737 dump_constraint (file, c);
738 fprintf (file, "\n");
742 /* Print out all constraints to stderr. */
744 DEBUG_FUNCTION void
745 debug_constraints (void)
747 dump_constraints (stderr, 0);
750 /* Print the constraint graph in dot format. */
752 static void
753 dump_constraint_graph (FILE *file)
755 unsigned int i;
757 /* Only print the graph if it has already been initialized: */
758 if (!graph)
759 return;
761 /* Prints the header of the dot file: */
762 fprintf (file, "strict digraph {\n");
763 fprintf (file, " node [\n shape = box\n ]\n");
764 fprintf (file, " edge [\n fontsize = \"12\"\n ]\n");
765 fprintf (file, "\n // List of nodes and complex constraints in "
766 "the constraint graph:\n");
768 /* The next lines print the nodes in the graph together with the
769 complex constraints attached to them. */
770 for (i = 1; i < graph->size; i++)
772 if (i == FIRST_REF_NODE)
773 continue;
774 if (find (i) != i)
775 continue;
776 if (i < FIRST_REF_NODE)
777 fprintf (file, "\"%s\"", get_varinfo (i)->name);
778 else
779 fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
780 if (graph->complex[i].exists ())
782 unsigned j;
783 constraint_t c;
784 fprintf (file, " [label=\"\\N\\n");
785 for (j = 0; graph->complex[i].iterate (j, &c); ++j)
787 dump_constraint (file, c);
788 fprintf (file, "\\l");
790 fprintf (file, "\"]");
792 fprintf (file, ";\n");
795 /* Go over the edges. */
796 fprintf (file, "\n // Edges in the constraint graph:\n");
797 for (i = 1; i < graph->size; i++)
799 unsigned j;
800 bitmap_iterator bi;
801 if (find (i) != i)
802 continue;
803 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i], 0, j, bi)
805 unsigned to = find (j);
806 if (i == to)
807 continue;
808 if (i < FIRST_REF_NODE)
809 fprintf (file, "\"%s\"", get_varinfo (i)->name);
810 else
811 fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
812 fprintf (file, " -> ");
813 if (to < FIRST_REF_NODE)
814 fprintf (file, "\"%s\"", get_varinfo (to)->name);
815 else
816 fprintf (file, "\"*%s\"", get_varinfo (to - FIRST_REF_NODE)->name);
817 fprintf (file, ";\n");
821 /* Prints the tail of the dot file. */
822 fprintf (file, "}\n");
825 /* Print out the constraint graph to stderr. */
827 DEBUG_FUNCTION void
828 debug_constraint_graph (void)
830 dump_constraint_graph (stderr);
833 /* SOLVER FUNCTIONS
835 The solver is a simple worklist solver, that works on the following
836 algorithm:
838 sbitmap changed_nodes = all zeroes;
839 changed_count = 0;
840 For each node that is not already collapsed:
841 changed_count++;
842 set bit in changed nodes
844 while (changed_count > 0)
846 compute topological ordering for constraint graph
848 find and collapse cycles in the constraint graph (updating
849 changed if necessary)
851 for each node (n) in the graph in topological order:
852 changed_count--;
854 Process each complex constraint associated with the node,
855 updating changed if necessary.
857 For each outgoing edge from n, propagate the solution from n to
858 the destination of the edge, updating changed as necessary.
860 } */
862 /* Return true if two constraint expressions A and B are equal. */
864 static bool
865 constraint_expr_equal (struct constraint_expr a, struct constraint_expr b)
867 return a.type == b.type && a.var == b.var && a.offset == b.offset;
870 /* Return true if constraint expression A is less than constraint expression
871 B. This is just arbitrary, but consistent, in order to give them an
872 ordering. */
874 static bool
875 constraint_expr_less (struct constraint_expr a, struct constraint_expr b)
877 if (a.type == b.type)
879 if (a.var == b.var)
880 return a.offset < b.offset;
881 else
882 return a.var < b.var;
884 else
885 return a.type < b.type;
888 /* Return true if constraint A is less than constraint B. This is just
889 arbitrary, but consistent, in order to give them an ordering. */
891 static bool
892 constraint_less (const constraint_t &a, const constraint_t &b)
894 if (constraint_expr_less (a->lhs, b->lhs))
895 return true;
896 else if (constraint_expr_less (b->lhs, a->lhs))
897 return false;
898 else
899 return constraint_expr_less (a->rhs, b->rhs);
902 /* Return true if two constraints A and B are equal. */
904 static bool
905 constraint_equal (struct constraint a, struct constraint b)
907 return constraint_expr_equal (a.lhs, b.lhs)
908 && constraint_expr_equal (a.rhs, b.rhs);
912 /* Find a constraint LOOKFOR in the sorted constraint vector VEC */
914 static constraint_t
915 constraint_vec_find (vec<constraint_t> vec,
916 struct constraint lookfor)
918 unsigned int place;
919 constraint_t found;
921 if (!vec.exists ())
922 return NULL;
924 place = vec.lower_bound (&lookfor, constraint_less);
925 if (place >= vec.length ())
926 return NULL;
927 found = vec[place];
928 if (!constraint_equal (*found, lookfor))
929 return NULL;
930 return found;
933 /* Union two constraint vectors, TO and FROM. Put the result in TO.
934 Returns true of TO set is changed. */
936 static bool
937 constraint_set_union (vec<constraint_t> *to,
938 vec<constraint_t> *from)
940 int i;
941 constraint_t c;
942 bool any_change = false;
944 FOR_EACH_VEC_ELT (*from, i, c)
946 if (constraint_vec_find (*to, *c) == NULL)
948 unsigned int place = to->lower_bound (c, constraint_less);
949 to->safe_insert (place, c);
950 any_change = true;
953 return any_change;
956 /* Expands the solution in SET to all sub-fields of variables included. */
958 static bitmap
959 solution_set_expand (bitmap set, bitmap *expanded)
961 bitmap_iterator bi;
962 unsigned j;
964 if (*expanded)
965 return *expanded;
967 *expanded = BITMAP_ALLOC (&iteration_obstack);
969 /* In a first pass expand to the head of the variables we need to
970 add all sub-fields off. This avoids quadratic behavior. */
971 EXECUTE_IF_SET_IN_BITMAP (set, 0, j, bi)
973 varinfo_t v = get_varinfo (j);
974 if (v->is_artificial_var
975 || v->is_full_var)
976 continue;
977 bitmap_set_bit (*expanded, v->head);
980 /* In the second pass now expand all head variables with subfields. */
981 EXECUTE_IF_SET_IN_BITMAP (*expanded, 0, j, bi)
983 varinfo_t v = get_varinfo (j);
984 if (v->head != j)
985 continue;
986 for (v = vi_next (v); v != NULL; v = vi_next (v))
987 bitmap_set_bit (*expanded, v->id);
990 /* And finally set the rest of the bits from SET. */
991 bitmap_ior_into (*expanded, set);
993 return *expanded;
996 /* Union solution sets TO and DELTA, and add INC to each member of DELTA in the
997 process. */
999 static bool
1000 set_union_with_increment (bitmap to, bitmap delta, HOST_WIDE_INT inc,
1001 bitmap *expanded_delta)
1003 bool changed = false;
1004 bitmap_iterator bi;
1005 unsigned int i;
1007 /* If the solution of DELTA contains anything it is good enough to transfer
1008 this to TO. */
1009 if (bitmap_bit_p (delta, anything_id))
1010 return bitmap_set_bit (to, anything_id);
1012 /* If the offset is unknown we have to expand the solution to
1013 all subfields. */
1014 if (inc == UNKNOWN_OFFSET)
1016 delta = solution_set_expand (delta, expanded_delta);
1017 changed |= bitmap_ior_into (to, delta);
1018 return changed;
1021 /* For non-zero offset union the offsetted solution into the destination. */
1022 EXECUTE_IF_SET_IN_BITMAP (delta, 0, i, bi)
1024 varinfo_t vi = get_varinfo (i);
1026 /* If this is a variable with just one field just set its bit
1027 in the result. */
1028 if (vi->is_artificial_var
1029 || vi->is_unknown_size_var
1030 || vi->is_full_var)
1031 changed |= bitmap_set_bit (to, i);
1032 else
1034 HOST_WIDE_INT fieldoffset = vi->offset + inc;
1035 unsigned HOST_WIDE_INT size = vi->size;
1037 /* If the offset makes the pointer point to before the
1038 variable use offset zero for the field lookup. */
1039 if (fieldoffset < 0)
1040 vi = get_varinfo (vi->head);
1041 else
1042 vi = first_or_preceding_vi_for_offset (vi, fieldoffset);
1046 changed |= bitmap_set_bit (to, vi->id);
1047 if (vi->is_full_var
1048 || vi->next == 0)
1049 break;
1051 /* We have to include all fields that overlap the current field
1052 shifted by inc. */
1053 vi = vi_next (vi);
1055 while (vi->offset < fieldoffset + size);
1059 return changed;
1062 /* Insert constraint C into the list of complex constraints for graph
1063 node VAR. */
1065 static void
1066 insert_into_complex (constraint_graph_t graph,
1067 unsigned int var, constraint_t c)
1069 vec<constraint_t> complex = graph->complex[var];
1070 unsigned int place = complex.lower_bound (c, constraint_less);
1072 /* Only insert constraints that do not already exist. */
1073 if (place >= complex.length ()
1074 || !constraint_equal (*c, *complex[place]))
1075 graph->complex[var].safe_insert (place, c);
1079 /* Condense two variable nodes into a single variable node, by moving
1080 all associated info from FROM to TO. Returns true if TO node's
1081 constraint set changes after the merge. */
1083 static bool
1084 merge_node_constraints (constraint_graph_t graph, unsigned int to,
1085 unsigned int from)
1087 unsigned int i;
1088 constraint_t c;
1089 bool any_change = false;
1091 gcc_checking_assert (find (from) == to);
1093 /* Move all complex constraints from src node into to node */
1094 FOR_EACH_VEC_ELT (graph->complex[from], i, c)
1096 /* In complex constraints for node FROM, we may have either
1097 a = *FROM, and *FROM = a, or an offseted constraint which are
1098 always added to the rhs node's constraints. */
1100 if (c->rhs.type == DEREF)
1101 c->rhs.var = to;
1102 else if (c->lhs.type == DEREF)
1103 c->lhs.var = to;
1104 else
1105 c->rhs.var = to;
1108 any_change = constraint_set_union (&graph->complex[to],
1109 &graph->complex[from]);
1110 graph->complex[from].release ();
1111 return any_change;
1115 /* Remove edges involving NODE from GRAPH. */
1117 static void
1118 clear_edges_for_node (constraint_graph_t graph, unsigned int node)
1120 if (graph->succs[node])
1121 BITMAP_FREE (graph->succs[node]);
1124 /* Merge GRAPH nodes FROM and TO into node TO. */
1126 static void
1127 merge_graph_nodes (constraint_graph_t graph, unsigned int to,
1128 unsigned int from)
1130 if (graph->indirect_cycles[from] != -1)
1132 /* If we have indirect cycles with the from node, and we have
1133 none on the to node, the to node has indirect cycles from the
1134 from node now that they are unified.
1135 If indirect cycles exist on both, unify the nodes that they
1136 are in a cycle with, since we know they are in a cycle with
1137 each other. */
1138 if (graph->indirect_cycles[to] == -1)
1139 graph->indirect_cycles[to] = graph->indirect_cycles[from];
1142 /* Merge all the successor edges. */
1143 if (graph->succs[from])
1145 if (!graph->succs[to])
1146 graph->succs[to] = BITMAP_ALLOC (&pta_obstack);
1147 bitmap_ior_into (graph->succs[to],
1148 graph->succs[from]);
1151 clear_edges_for_node (graph, from);
1155 /* Add an indirect graph edge to GRAPH, going from TO to FROM if
1156 it doesn't exist in the graph already. */
1158 static void
1159 add_implicit_graph_edge (constraint_graph_t graph, unsigned int to,
1160 unsigned int from)
1162 if (to == from)
1163 return;
1165 if (!graph->implicit_preds[to])
1166 graph->implicit_preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1168 if (bitmap_set_bit (graph->implicit_preds[to], from))
1169 stats.num_implicit_edges++;
1172 /* Add a predecessor graph edge to GRAPH, going from TO to FROM if
1173 it doesn't exist in the graph already.
1174 Return false if the edge already existed, true otherwise. */
1176 static void
1177 add_pred_graph_edge (constraint_graph_t graph, unsigned int to,
1178 unsigned int from)
1180 if (!graph->preds[to])
1181 graph->preds[to] = BITMAP_ALLOC (&predbitmap_obstack);
1182 bitmap_set_bit (graph->preds[to], from);
1185 /* Add a graph edge to GRAPH, going from FROM to TO if
1186 it doesn't exist in the graph already.
1187 Return false if the edge already existed, true otherwise. */
1189 static bool
1190 add_graph_edge (constraint_graph_t graph, unsigned int to,
1191 unsigned int from)
1193 if (to == from)
1195 return false;
1197 else
1199 bool r = false;
1201 if (!graph->succs[from])
1202 graph->succs[from] = BITMAP_ALLOC (&pta_obstack);
1203 if (bitmap_set_bit (graph->succs[from], to))
1205 r = true;
1206 if (to < FIRST_REF_NODE && from < FIRST_REF_NODE)
1207 stats.num_edges++;
1209 return r;
1214 /* Initialize the constraint graph structure to contain SIZE nodes. */
1216 static void
1217 init_graph (unsigned int size)
1219 unsigned int j;
1221 graph = XCNEW (struct constraint_graph);
1222 graph->size = size;
1223 graph->succs = XCNEWVEC (bitmap, graph->size);
1224 graph->indirect_cycles = XNEWVEC (int, graph->size);
1225 graph->rep = XNEWVEC (unsigned int, graph->size);
1226 /* ??? Macros do not support template types with multiple arguments,
1227 so we use a typedef to work around it. */
1228 typedef vec<constraint_t> vec_constraint_t_heap;
1229 graph->complex = XCNEWVEC (vec_constraint_t_heap, size);
1230 graph->pe = XCNEWVEC (unsigned int, graph->size);
1231 graph->pe_rep = XNEWVEC (int, graph->size);
1233 for (j = 0; j < graph->size; j++)
1235 graph->rep[j] = j;
1236 graph->pe_rep[j] = -1;
1237 graph->indirect_cycles[j] = -1;
1241 /* Build the constraint graph, adding only predecessor edges right now. */
1243 static void
1244 build_pred_graph (void)
1246 int i;
1247 constraint_t c;
1248 unsigned int j;
1250 graph->implicit_preds = XCNEWVEC (bitmap, graph->size);
1251 graph->preds = XCNEWVEC (bitmap, graph->size);
1252 graph->pointer_label = XCNEWVEC (unsigned int, graph->size);
1253 graph->loc_label = XCNEWVEC (unsigned int, graph->size);
1254 graph->pointed_by = XCNEWVEC (bitmap, graph->size);
1255 graph->points_to = XCNEWVEC (bitmap, graph->size);
1256 graph->eq_rep = XNEWVEC (int, graph->size);
1257 graph->direct_nodes = sbitmap_alloc (graph->size);
1258 graph->address_taken = BITMAP_ALLOC (&predbitmap_obstack);
1259 bitmap_clear (graph->direct_nodes);
1261 for (j = 1; j < FIRST_REF_NODE; j++)
1263 if (!get_varinfo (j)->is_special_var)
1264 bitmap_set_bit (graph->direct_nodes, j);
1267 for (j = 0; j < graph->size; j++)
1268 graph->eq_rep[j] = -1;
1270 for (j = 0; j < varmap.length (); j++)
1271 graph->indirect_cycles[j] = -1;
1273 FOR_EACH_VEC_ELT (constraints, i, c)
1275 struct constraint_expr lhs = c->lhs;
1276 struct constraint_expr rhs = c->rhs;
1277 unsigned int lhsvar = lhs.var;
1278 unsigned int rhsvar = rhs.var;
1280 if (lhs.type == DEREF)
1282 /* *x = y. */
1283 if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1284 add_pred_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1286 else if (rhs.type == DEREF)
1288 /* x = *y */
1289 if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1290 add_pred_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1291 else
1292 bitmap_clear_bit (graph->direct_nodes, lhsvar);
1294 else if (rhs.type == ADDRESSOF)
1296 varinfo_t v;
1298 /* x = &y */
1299 if (graph->points_to[lhsvar] == NULL)
1300 graph->points_to[lhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1301 bitmap_set_bit (graph->points_to[lhsvar], rhsvar);
1303 if (graph->pointed_by[rhsvar] == NULL)
1304 graph->pointed_by[rhsvar] = BITMAP_ALLOC (&predbitmap_obstack);
1305 bitmap_set_bit (graph->pointed_by[rhsvar], lhsvar);
1307 /* Implicitly, *x = y */
1308 add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1310 /* All related variables are no longer direct nodes. */
1311 bitmap_clear_bit (graph->direct_nodes, rhsvar);
1312 v = get_varinfo (rhsvar);
1313 if (!v->is_full_var)
1315 v = get_varinfo (v->head);
1318 bitmap_clear_bit (graph->direct_nodes, v->id);
1319 v = vi_next (v);
1321 while (v != NULL);
1323 bitmap_set_bit (graph->address_taken, rhsvar);
1325 else if (lhsvar > anything_id
1326 && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1328 /* x = y */
1329 add_pred_graph_edge (graph, lhsvar, rhsvar);
1330 /* Implicitly, *x = *y */
1331 add_implicit_graph_edge (graph, FIRST_REF_NODE + lhsvar,
1332 FIRST_REF_NODE + rhsvar);
1334 else if (lhs.offset != 0 || rhs.offset != 0)
1336 if (rhs.offset != 0)
1337 bitmap_clear_bit (graph->direct_nodes, lhs.var);
1338 else if (lhs.offset != 0)
1339 bitmap_clear_bit (graph->direct_nodes, rhs.var);
1344 /* Build the constraint graph, adding successor edges. */
1346 static void
1347 build_succ_graph (void)
1349 unsigned i, t;
1350 constraint_t c;
1352 FOR_EACH_VEC_ELT (constraints, i, c)
1354 struct constraint_expr lhs;
1355 struct constraint_expr rhs;
1356 unsigned int lhsvar;
1357 unsigned int rhsvar;
1359 if (!c)
1360 continue;
1362 lhs = c->lhs;
1363 rhs = c->rhs;
1364 lhsvar = find (lhs.var);
1365 rhsvar = find (rhs.var);
1367 if (lhs.type == DEREF)
1369 if (rhs.offset == 0 && lhs.offset == 0 && rhs.type == SCALAR)
1370 add_graph_edge (graph, FIRST_REF_NODE + lhsvar, rhsvar);
1372 else if (rhs.type == DEREF)
1374 if (rhs.offset == 0 && lhs.offset == 0 && lhs.type == SCALAR)
1375 add_graph_edge (graph, lhsvar, FIRST_REF_NODE + rhsvar);
1377 else if (rhs.type == ADDRESSOF)
1379 /* x = &y */
1380 gcc_checking_assert (find (rhs.var) == rhs.var);
1381 bitmap_set_bit (get_varinfo (lhsvar)->solution, rhsvar);
1383 else if (lhsvar > anything_id
1384 && lhsvar != rhsvar && lhs.offset == 0 && rhs.offset == 0)
1386 add_graph_edge (graph, lhsvar, rhsvar);
1390 /* Add edges from STOREDANYTHING to all non-direct nodes that can
1391 receive pointers. */
1392 t = find (storedanything_id);
1393 for (i = integer_id + 1; i < FIRST_REF_NODE; ++i)
1395 if (!bitmap_bit_p (graph->direct_nodes, i)
1396 && get_varinfo (i)->may_have_pointers)
1397 add_graph_edge (graph, find (i), t);
1400 /* Everything stored to ANYTHING also potentially escapes. */
1401 add_graph_edge (graph, find (escaped_id), t);
1405 /* Changed variables on the last iteration. */
1406 static bitmap changed;
1408 /* Strongly Connected Component visitation info. */
1410 struct scc_info
1412 sbitmap visited;
1413 sbitmap deleted;
1414 unsigned int *dfs;
1415 unsigned int *node_mapping;
1416 int current_index;
1417 vec<unsigned> scc_stack;
1421 /* Recursive routine to find strongly connected components in GRAPH.
1422 SI is the SCC info to store the information in, and N is the id of current
1423 graph node we are processing.
1425 This is Tarjan's strongly connected component finding algorithm, as
1426 modified by Nuutila to keep only non-root nodes on the stack.
1427 The algorithm can be found in "On finding the strongly connected
1428 connected components in a directed graph" by Esko Nuutila and Eljas
1429 Soisalon-Soininen, in Information Processing Letters volume 49,
1430 number 1, pages 9-14. */
1432 static void
1433 scc_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
1435 unsigned int i;
1436 bitmap_iterator bi;
1437 unsigned int my_dfs;
1439 bitmap_set_bit (si->visited, n);
1440 si->dfs[n] = si->current_index ++;
1441 my_dfs = si->dfs[n];
1443 /* Visit all the successors. */
1444 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[n], 0, i, bi)
1446 unsigned int w;
1448 if (i > LAST_REF_NODE)
1449 break;
1451 w = find (i);
1452 if (bitmap_bit_p (si->deleted, w))
1453 continue;
1455 if (!bitmap_bit_p (si->visited, w))
1456 scc_visit (graph, si, w);
1458 unsigned int t = find (w);
1459 gcc_checking_assert (find (n) == n);
1460 if (si->dfs[t] < si->dfs[n])
1461 si->dfs[n] = si->dfs[t];
1464 /* See if any components have been identified. */
1465 if (si->dfs[n] == my_dfs)
1467 if (si->scc_stack.length () > 0
1468 && si->dfs[si->scc_stack.last ()] >= my_dfs)
1470 bitmap scc = BITMAP_ALLOC (NULL);
1471 unsigned int lowest_node;
1472 bitmap_iterator bi;
1474 bitmap_set_bit (scc, n);
1476 while (si->scc_stack.length () != 0
1477 && si->dfs[si->scc_stack.last ()] >= my_dfs)
1479 unsigned int w = si->scc_stack.pop ();
1481 bitmap_set_bit (scc, w);
1484 lowest_node = bitmap_first_set_bit (scc);
1485 gcc_assert (lowest_node < FIRST_REF_NODE);
1487 /* Collapse the SCC nodes into a single node, and mark the
1488 indirect cycles. */
1489 EXECUTE_IF_SET_IN_BITMAP (scc, 0, i, bi)
1491 if (i < FIRST_REF_NODE)
1493 if (unite (lowest_node, i))
1494 unify_nodes (graph, lowest_node, i, false);
1496 else
1498 unite (lowest_node, i);
1499 graph->indirect_cycles[i - FIRST_REF_NODE] = lowest_node;
1503 bitmap_set_bit (si->deleted, n);
1505 else
1506 si->scc_stack.safe_push (n);
1509 /* Unify node FROM into node TO, updating the changed count if
1510 necessary when UPDATE_CHANGED is true. */
1512 static void
1513 unify_nodes (constraint_graph_t graph, unsigned int to, unsigned int from,
1514 bool update_changed)
1516 gcc_checking_assert (to != from && find (to) == to);
1518 if (dump_file && (dump_flags & TDF_DETAILS))
1519 fprintf (dump_file, "Unifying %s to %s\n",
1520 get_varinfo (from)->name,
1521 get_varinfo (to)->name);
1523 if (update_changed)
1524 stats.unified_vars_dynamic++;
1525 else
1526 stats.unified_vars_static++;
1528 merge_graph_nodes (graph, to, from);
1529 if (merge_node_constraints (graph, to, from))
1531 if (update_changed)
1532 bitmap_set_bit (changed, to);
1535 /* Mark TO as changed if FROM was changed. If TO was already marked
1536 as changed, decrease the changed count. */
1538 if (update_changed
1539 && bitmap_clear_bit (changed, from))
1540 bitmap_set_bit (changed, to);
1541 varinfo_t fromvi = get_varinfo (from);
1542 if (fromvi->solution)
1544 /* If the solution changes because of the merging, we need to mark
1545 the variable as changed. */
1546 varinfo_t tovi = get_varinfo (to);
1547 if (bitmap_ior_into (tovi->solution, fromvi->solution))
1549 if (update_changed)
1550 bitmap_set_bit (changed, to);
1553 BITMAP_FREE (fromvi->solution);
1554 if (fromvi->oldsolution)
1555 BITMAP_FREE (fromvi->oldsolution);
1557 if (stats.iterations > 0
1558 && tovi->oldsolution)
1559 BITMAP_FREE (tovi->oldsolution);
1561 if (graph->succs[to])
1562 bitmap_clear_bit (graph->succs[to], to);
1565 /* Information needed to compute the topological ordering of a graph. */
1567 struct topo_info
1569 /* sbitmap of visited nodes. */
1570 sbitmap visited;
1571 /* Array that stores the topological order of the graph, *in
1572 reverse*. */
1573 vec<unsigned> topo_order;
1577 /* Initialize and return a topological info structure. */
1579 static struct topo_info *
1580 init_topo_info (void)
1582 size_t size = graph->size;
1583 struct topo_info *ti = XNEW (struct topo_info);
1584 ti->visited = sbitmap_alloc (size);
1585 bitmap_clear (ti->visited);
1586 ti->topo_order.create (1);
1587 return ti;
1591 /* Free the topological sort info pointed to by TI. */
1593 static void
1594 free_topo_info (struct topo_info *ti)
1596 sbitmap_free (ti->visited);
1597 ti->topo_order.release ();
1598 free (ti);
1601 /* Visit the graph in topological order, and store the order in the
1602 topo_info structure. */
1604 static void
1605 topo_visit (constraint_graph_t graph, struct topo_info *ti,
1606 unsigned int n)
1608 bitmap_iterator bi;
1609 unsigned int j;
1611 bitmap_set_bit (ti->visited, n);
1613 if (graph->succs[n])
1614 EXECUTE_IF_SET_IN_BITMAP (graph->succs[n], 0, j, bi)
1616 if (!bitmap_bit_p (ti->visited, j))
1617 topo_visit (graph, ti, j);
1620 ti->topo_order.safe_push (n);
1623 /* Process a constraint C that represents x = *(y + off), using DELTA as the
1624 starting solution for y. */
1626 static void
1627 do_sd_constraint (constraint_graph_t graph, constraint_t c,
1628 bitmap delta, bitmap *expanded_delta)
1630 unsigned int lhs = c->lhs.var;
1631 bool flag = false;
1632 bitmap sol = get_varinfo (lhs)->solution;
1633 unsigned int j;
1634 bitmap_iterator bi;
1635 HOST_WIDE_INT roffset = c->rhs.offset;
1637 /* Our IL does not allow this. */
1638 gcc_checking_assert (c->lhs.offset == 0);
1640 /* If the solution of Y contains anything it is good enough to transfer
1641 this to the LHS. */
1642 if (bitmap_bit_p (delta, anything_id))
1644 flag |= bitmap_set_bit (sol, anything_id);
1645 goto done;
1648 /* If we do not know at with offset the rhs is dereferenced compute
1649 the reachability set of DELTA, conservatively assuming it is
1650 dereferenced at all valid offsets. */
1651 if (roffset == UNKNOWN_OFFSET)
1653 delta = solution_set_expand (delta, expanded_delta);
1654 /* No further offset processing is necessary. */
1655 roffset = 0;
1658 /* For each variable j in delta (Sol(y)), add
1659 an edge in the graph from j to x, and union Sol(j) into Sol(x). */
1660 EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1662 varinfo_t v = get_varinfo (j);
1663 HOST_WIDE_INT fieldoffset = v->offset + roffset;
1664 unsigned HOST_WIDE_INT size = v->size;
1665 unsigned int t;
1667 if (v->is_full_var)
1669 else if (roffset != 0)
1671 if (fieldoffset < 0)
1672 v = get_varinfo (v->head);
1673 else
1674 v = first_or_preceding_vi_for_offset (v, fieldoffset);
1677 /* We have to include all fields that overlap the current field
1678 shifted by roffset. */
1681 t = find (v->id);
1683 /* Adding edges from the special vars is pointless.
1684 They don't have sets that can change. */
1685 if (get_varinfo (t)->is_special_var)
1686 flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1687 /* Merging the solution from ESCAPED needlessly increases
1688 the set. Use ESCAPED as representative instead. */
1689 else if (v->id == escaped_id)
1690 flag |= bitmap_set_bit (sol, escaped_id);
1691 else if (v->may_have_pointers
1692 && add_graph_edge (graph, lhs, t))
1693 flag |= bitmap_ior_into (sol, get_varinfo (t)->solution);
1695 if (v->is_full_var
1696 || v->next == 0)
1697 break;
1699 v = vi_next (v);
1701 while (v->offset < fieldoffset + size);
1704 done:
1705 /* If the LHS solution changed, mark the var as changed. */
1706 if (flag)
1708 get_varinfo (lhs)->solution = sol;
1709 bitmap_set_bit (changed, lhs);
1713 /* Process a constraint C that represents *(x + off) = y using DELTA
1714 as the starting solution for x. */
1716 static void
1717 do_ds_constraint (constraint_t c, bitmap delta, bitmap *expanded_delta)
1719 unsigned int rhs = c->rhs.var;
1720 bitmap sol = get_varinfo (rhs)->solution;
1721 unsigned int j;
1722 bitmap_iterator bi;
1723 HOST_WIDE_INT loff = c->lhs.offset;
1724 bool escaped_p = false;
1726 /* Our IL does not allow this. */
1727 gcc_checking_assert (c->rhs.offset == 0);
1729 /* If the solution of y contains ANYTHING simply use the ANYTHING
1730 solution. This avoids needlessly increasing the points-to sets. */
1731 if (bitmap_bit_p (sol, anything_id))
1732 sol = get_varinfo (find (anything_id))->solution;
1734 /* If the solution for x contains ANYTHING we have to merge the
1735 solution of y into all pointer variables which we do via
1736 STOREDANYTHING. */
1737 if (bitmap_bit_p (delta, anything_id))
1739 unsigned t = find (storedanything_id);
1740 if (add_graph_edge (graph, t, rhs))
1742 if (bitmap_ior_into (get_varinfo (t)->solution, sol))
1743 bitmap_set_bit (changed, t);
1745 return;
1748 /* If we do not know at with offset the rhs is dereferenced compute
1749 the reachability set of DELTA, conservatively assuming it is
1750 dereferenced at all valid offsets. */
1751 if (loff == UNKNOWN_OFFSET)
1753 delta = solution_set_expand (delta, expanded_delta);
1754 loff = 0;
1757 /* For each member j of delta (Sol(x)), add an edge from y to j and
1758 union Sol(y) into Sol(j) */
1759 EXECUTE_IF_SET_IN_BITMAP (delta, 0, j, bi)
1761 varinfo_t v = get_varinfo (j);
1762 unsigned int t;
1763 HOST_WIDE_INT fieldoffset = v->offset + loff;
1764 unsigned HOST_WIDE_INT size = v->size;
1766 if (v->is_full_var)
1768 else if (loff != 0)
1770 if (fieldoffset < 0)
1771 v = get_varinfo (v->head);
1772 else
1773 v = first_or_preceding_vi_for_offset (v, fieldoffset);
1776 /* We have to include all fields that overlap the current field
1777 shifted by loff. */
1780 if (v->may_have_pointers)
1782 /* If v is a global variable then this is an escape point. */
1783 if (v->is_global_var
1784 && !escaped_p)
1786 t = find (escaped_id);
1787 if (add_graph_edge (graph, t, rhs)
1788 && bitmap_ior_into (get_varinfo (t)->solution, sol))
1789 bitmap_set_bit (changed, t);
1790 /* Enough to let rhs escape once. */
1791 escaped_p = true;
1794 if (v->is_special_var)
1795 break;
1797 t = find (v->id);
1798 if (add_graph_edge (graph, t, rhs)
1799 && bitmap_ior_into (get_varinfo (t)->solution, sol))
1800 bitmap_set_bit (changed, t);
1803 if (v->is_full_var
1804 || v->next == 0)
1805 break;
1807 v = vi_next (v);
1809 while (v->offset < fieldoffset + size);
1813 /* Handle a non-simple (simple meaning requires no iteration),
1814 constraint (IE *x = &y, x = *y, *x = y, and x = y with offsets involved). */
1816 static void
1817 do_complex_constraint (constraint_graph_t graph, constraint_t c, bitmap delta,
1818 bitmap *expanded_delta)
1820 if (c->lhs.type == DEREF)
1822 if (c->rhs.type == ADDRESSOF)
1824 gcc_unreachable ();
1826 else
1828 /* *x = y */
1829 do_ds_constraint (c, delta, expanded_delta);
1832 else if (c->rhs.type == DEREF)
1834 /* x = *y */
1835 if (!(get_varinfo (c->lhs.var)->is_special_var))
1836 do_sd_constraint (graph, c, delta, expanded_delta);
1838 else
1840 bitmap tmp;
1841 bool flag = false;
1843 gcc_checking_assert (c->rhs.type == SCALAR && c->lhs.type == SCALAR
1844 && c->rhs.offset != 0 && c->lhs.offset == 0);
1845 tmp = get_varinfo (c->lhs.var)->solution;
1847 flag = set_union_with_increment (tmp, delta, c->rhs.offset,
1848 expanded_delta);
1850 if (flag)
1851 bitmap_set_bit (changed, c->lhs.var);
1855 /* Initialize and return a new SCC info structure. */
1857 static struct scc_info *
1858 init_scc_info (size_t size)
1860 struct scc_info *si = XNEW (struct scc_info);
1861 size_t i;
1863 si->current_index = 0;
1864 si->visited = sbitmap_alloc (size);
1865 bitmap_clear (si->visited);
1866 si->deleted = sbitmap_alloc (size);
1867 bitmap_clear (si->deleted);
1868 si->node_mapping = XNEWVEC (unsigned int, size);
1869 si->dfs = XCNEWVEC (unsigned int, size);
1871 for (i = 0; i < size; i++)
1872 si->node_mapping[i] = i;
1874 si->scc_stack.create (1);
1875 return si;
1878 /* Free an SCC info structure pointed to by SI */
1880 static void
1881 free_scc_info (struct scc_info *si)
1883 sbitmap_free (si->visited);
1884 sbitmap_free (si->deleted);
1885 free (si->node_mapping);
1886 free (si->dfs);
1887 si->scc_stack.release ();
1888 free (si);
1892 /* Find indirect cycles in GRAPH that occur, using strongly connected
1893 components, and note them in the indirect cycles map.
1895 This technique comes from Ben Hardekopf and Calvin Lin,
1896 "It Pays to be Lazy: Fast and Accurate Pointer Analysis for Millions of
1897 Lines of Code", submitted to PLDI 2007. */
1899 static void
1900 find_indirect_cycles (constraint_graph_t graph)
1902 unsigned int i;
1903 unsigned int size = graph->size;
1904 struct scc_info *si = init_scc_info (size);
1906 for (i = 0; i < MIN (LAST_REF_NODE, size); i ++ )
1907 if (!bitmap_bit_p (si->visited, i) && find (i) == i)
1908 scc_visit (graph, si, i);
1910 free_scc_info (si);
1913 /* Compute a topological ordering for GRAPH, and store the result in the
1914 topo_info structure TI. */
1916 static void
1917 compute_topo_order (constraint_graph_t graph,
1918 struct topo_info *ti)
1920 unsigned int i;
1921 unsigned int size = graph->size;
1923 for (i = 0; i != size; ++i)
1924 if (!bitmap_bit_p (ti->visited, i) && find (i) == i)
1925 topo_visit (graph, ti, i);
1928 /* Structure used to for hash value numbering of pointer equivalence
1929 classes. */
1931 typedef struct equiv_class_label
1933 hashval_t hashcode;
1934 unsigned int equivalence_class;
1935 bitmap labels;
1936 } *equiv_class_label_t;
1937 typedef const struct equiv_class_label *const_equiv_class_label_t;
1939 /* Equiv_class_label hashtable helpers. */
1941 struct equiv_class_hasher : typed_free_remove <equiv_class_label>
1943 typedef equiv_class_label value_type;
1944 typedef equiv_class_label compare_type;
1945 static inline hashval_t hash (const value_type *);
1946 static inline bool equal (const value_type *, const compare_type *);
1949 /* Hash function for a equiv_class_label_t */
1951 inline hashval_t
1952 equiv_class_hasher::hash (const value_type *ecl)
1954 return ecl->hashcode;
1957 /* Equality function for two equiv_class_label_t's. */
1959 inline bool
1960 equiv_class_hasher::equal (const value_type *eql1, const compare_type *eql2)
1962 return (eql1->hashcode == eql2->hashcode
1963 && bitmap_equal_p (eql1->labels, eql2->labels));
1966 /* A hashtable for mapping a bitmap of labels->pointer equivalence
1967 classes. */
1968 static hash_table<equiv_class_hasher> *pointer_equiv_class_table;
1970 /* A hashtable for mapping a bitmap of labels->location equivalence
1971 classes. */
1972 static hash_table<equiv_class_hasher> *location_equiv_class_table;
1974 /* Lookup a equivalence class in TABLE by the bitmap of LABELS with
1975 hash HAS it contains. Sets *REF_LABELS to the bitmap LABELS
1976 is equivalent to. */
1978 static equiv_class_label *
1979 equiv_class_lookup_or_add (hash_table<equiv_class_hasher> *table,
1980 bitmap labels)
1982 equiv_class_label **slot;
1983 equiv_class_label ecl;
1985 ecl.labels = labels;
1986 ecl.hashcode = bitmap_hash (labels);
1987 slot = table->find_slot (&ecl, INSERT);
1988 if (!*slot)
1990 *slot = XNEW (struct equiv_class_label);
1991 (*slot)->labels = labels;
1992 (*slot)->hashcode = ecl.hashcode;
1993 (*slot)->equivalence_class = 0;
1996 return *slot;
1999 /* Perform offline variable substitution.
2001 This is a worst case quadratic time way of identifying variables
2002 that must have equivalent points-to sets, including those caused by
2003 static cycles, and single entry subgraphs, in the constraint graph.
2005 The technique is described in "Exploiting Pointer and Location
2006 Equivalence to Optimize Pointer Analysis. In the 14th International
2007 Static Analysis Symposium (SAS), August 2007." It is known as the
2008 "HU" algorithm, and is equivalent to value numbering the collapsed
2009 constraint graph including evaluating unions.
2011 The general method of finding equivalence classes is as follows:
2012 Add fake nodes (REF nodes) and edges for *a = b and a = *b constraints.
2013 Initialize all non-REF nodes to be direct nodes.
2014 For each constraint a = a U {b}, we set pts(a) = pts(a) u {fresh
2015 variable}
2016 For each constraint containing the dereference, we also do the same
2017 thing.
2019 We then compute SCC's in the graph and unify nodes in the same SCC,
2020 including pts sets.
2022 For each non-collapsed node x:
2023 Visit all unvisited explicit incoming edges.
2024 Ignoring all non-pointers, set pts(x) = Union of pts(a) for y
2025 where y->x.
2026 Lookup the equivalence class for pts(x).
2027 If we found one, equivalence_class(x) = found class.
2028 Otherwise, equivalence_class(x) = new class, and new_class is
2029 added to the lookup table.
2031 All direct nodes with the same equivalence class can be replaced
2032 with a single representative node.
2033 All unlabeled nodes (label == 0) are not pointers and all edges
2034 involving them can be eliminated.
2035 We perform these optimizations during rewrite_constraints
2037 In addition to pointer equivalence class finding, we also perform
2038 location equivalence class finding. This is the set of variables
2039 that always appear together in points-to sets. We use this to
2040 compress the size of the points-to sets. */
2042 /* Current maximum pointer equivalence class id. */
2043 static int pointer_equiv_class;
2045 /* Current maximum location equivalence class id. */
2046 static int location_equiv_class;
2048 /* Recursive routine to find strongly connected components in GRAPH,
2049 and label it's nodes with DFS numbers. */
2051 static void
2052 condense_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
2054 unsigned int i;
2055 bitmap_iterator bi;
2056 unsigned int my_dfs;
2058 gcc_checking_assert (si->node_mapping[n] == n);
2059 bitmap_set_bit (si->visited, n);
2060 si->dfs[n] = si->current_index ++;
2061 my_dfs = si->dfs[n];
2063 /* Visit all the successors. */
2064 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
2066 unsigned int w = si->node_mapping[i];
2068 if (bitmap_bit_p (si->deleted, w))
2069 continue;
2071 if (!bitmap_bit_p (si->visited, w))
2072 condense_visit (graph, si, w);
2074 unsigned int t = si->node_mapping[w];
2075 gcc_checking_assert (si->node_mapping[n] == n);
2076 if (si->dfs[t] < si->dfs[n])
2077 si->dfs[n] = si->dfs[t];
2080 /* Visit all the implicit predecessors. */
2081 EXECUTE_IF_IN_NONNULL_BITMAP (graph->implicit_preds[n], 0, i, bi)
2083 unsigned int w = si->node_mapping[i];
2085 if (bitmap_bit_p (si->deleted, w))
2086 continue;
2088 if (!bitmap_bit_p (si->visited, w))
2089 condense_visit (graph, si, w);
2091 unsigned int t = si->node_mapping[w];
2092 gcc_assert (si->node_mapping[n] == n);
2093 if (si->dfs[t] < si->dfs[n])
2094 si->dfs[n] = si->dfs[t];
2097 /* See if any components have been identified. */
2098 if (si->dfs[n] == my_dfs)
2100 while (si->scc_stack.length () != 0
2101 && si->dfs[si->scc_stack.last ()] >= my_dfs)
2103 unsigned int w = si->scc_stack.pop ();
2104 si->node_mapping[w] = n;
2106 if (!bitmap_bit_p (graph->direct_nodes, w))
2107 bitmap_clear_bit (graph->direct_nodes, n);
2109 /* Unify our nodes. */
2110 if (graph->preds[w])
2112 if (!graph->preds[n])
2113 graph->preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2114 bitmap_ior_into (graph->preds[n], graph->preds[w]);
2116 if (graph->implicit_preds[w])
2118 if (!graph->implicit_preds[n])
2119 graph->implicit_preds[n] = BITMAP_ALLOC (&predbitmap_obstack);
2120 bitmap_ior_into (graph->implicit_preds[n],
2121 graph->implicit_preds[w]);
2123 if (graph->points_to[w])
2125 if (!graph->points_to[n])
2126 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2127 bitmap_ior_into (graph->points_to[n],
2128 graph->points_to[w]);
2131 bitmap_set_bit (si->deleted, n);
2133 else
2134 si->scc_stack.safe_push (n);
2137 /* Label pointer equivalences.
2139 This performs a value numbering of the constraint graph to
2140 discover which variables will always have the same points-to sets
2141 under the current set of constraints.
2143 The way it value numbers is to store the set of points-to bits
2144 generated by the constraints and graph edges. This is just used as a
2145 hash and equality comparison. The *actual set of points-to bits* is
2146 completely irrelevant, in that we don't care about being able to
2147 extract them later.
2149 The equality values (currently bitmaps) just have to satisfy a few
2150 constraints, the main ones being:
2151 1. The combining operation must be order independent.
2152 2. The end result of a given set of operations must be unique iff the
2153 combination of input values is unique
2154 3. Hashable. */
2156 static void
2157 label_visit (constraint_graph_t graph, struct scc_info *si, unsigned int n)
2159 unsigned int i, first_pred;
2160 bitmap_iterator bi;
2162 bitmap_set_bit (si->visited, n);
2164 /* Label and union our incoming edges's points to sets. */
2165 first_pred = -1U;
2166 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[n], 0, i, bi)
2168 unsigned int w = si->node_mapping[i];
2169 if (!bitmap_bit_p (si->visited, w))
2170 label_visit (graph, si, w);
2172 /* Skip unused edges */
2173 if (w == n || graph->pointer_label[w] == 0)
2174 continue;
2176 if (graph->points_to[w])
2178 if (!graph->points_to[n])
2180 if (first_pred == -1U)
2181 first_pred = w;
2182 else
2184 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2185 bitmap_ior (graph->points_to[n],
2186 graph->points_to[first_pred],
2187 graph->points_to[w]);
2190 else
2191 bitmap_ior_into (graph->points_to[n], graph->points_to[w]);
2195 /* Indirect nodes get fresh variables and a new pointer equiv class. */
2196 if (!bitmap_bit_p (graph->direct_nodes, n))
2198 if (!graph->points_to[n])
2200 graph->points_to[n] = BITMAP_ALLOC (&predbitmap_obstack);
2201 if (first_pred != -1U)
2202 bitmap_copy (graph->points_to[n], graph->points_to[first_pred]);
2204 bitmap_set_bit (graph->points_to[n], FIRST_REF_NODE + n);
2205 graph->pointer_label[n] = pointer_equiv_class++;
2206 equiv_class_label_t ecl;
2207 ecl = equiv_class_lookup_or_add (pointer_equiv_class_table,
2208 graph->points_to[n]);
2209 ecl->equivalence_class = graph->pointer_label[n];
2210 return;
2213 /* If there was only a single non-empty predecessor the pointer equiv
2214 class is the same. */
2215 if (!graph->points_to[n])
2217 if (first_pred != -1U)
2219 graph->pointer_label[n] = graph->pointer_label[first_pred];
2220 graph->points_to[n] = graph->points_to[first_pred];
2222 return;
2225 if (!bitmap_empty_p (graph->points_to[n]))
2227 equiv_class_label_t ecl;
2228 ecl = equiv_class_lookup_or_add (pointer_equiv_class_table,
2229 graph->points_to[n]);
2230 if (ecl->equivalence_class == 0)
2231 ecl->equivalence_class = pointer_equiv_class++;
2232 else
2234 BITMAP_FREE (graph->points_to[n]);
2235 graph->points_to[n] = ecl->labels;
2237 graph->pointer_label[n] = ecl->equivalence_class;
2241 /* Print the pred graph in dot format. */
2243 static void
2244 dump_pred_graph (struct scc_info *si, FILE *file)
2246 unsigned int i;
2248 /* Only print the graph if it has already been initialized: */
2249 if (!graph)
2250 return;
2252 /* Prints the header of the dot file: */
2253 fprintf (file, "strict digraph {\n");
2254 fprintf (file, " node [\n shape = box\n ]\n");
2255 fprintf (file, " edge [\n fontsize = \"12\"\n ]\n");
2256 fprintf (file, "\n // List of nodes and complex constraints in "
2257 "the constraint graph:\n");
2259 /* The next lines print the nodes in the graph together with the
2260 complex constraints attached to them. */
2261 for (i = 1; i < graph->size; i++)
2263 if (i == FIRST_REF_NODE)
2264 continue;
2265 if (si->node_mapping[i] != i)
2266 continue;
2267 if (i < FIRST_REF_NODE)
2268 fprintf (file, "\"%s\"", get_varinfo (i)->name);
2269 else
2270 fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
2271 if (graph->points_to[i]
2272 && !bitmap_empty_p (graph->points_to[i]))
2274 fprintf (file, "[label=\"%s = {", get_varinfo (i)->name);
2275 unsigned j;
2276 bitmap_iterator bi;
2277 EXECUTE_IF_SET_IN_BITMAP (graph->points_to[i], 0, j, bi)
2278 fprintf (file, " %d", j);
2279 fprintf (file, " }\"]");
2281 fprintf (file, ";\n");
2284 /* Go over the edges. */
2285 fprintf (file, "\n // Edges in the constraint graph:\n");
2286 for (i = 1; i < graph->size; i++)
2288 unsigned j;
2289 bitmap_iterator bi;
2290 if (si->node_mapping[i] != i)
2291 continue;
2292 EXECUTE_IF_IN_NONNULL_BITMAP (graph->preds[i], 0, j, bi)
2294 unsigned from = si->node_mapping[j];
2295 if (from < FIRST_REF_NODE)
2296 fprintf (file, "\"%s\"", get_varinfo (from)->name);
2297 else
2298 fprintf (file, "\"*%s\"", get_varinfo (from - FIRST_REF_NODE)->name);
2299 fprintf (file, " -> ");
2300 if (i < FIRST_REF_NODE)
2301 fprintf (file, "\"%s\"", get_varinfo (i)->name);
2302 else
2303 fprintf (file, "\"*%s\"", get_varinfo (i - FIRST_REF_NODE)->name);
2304 fprintf (file, ";\n");
2308 /* Prints the tail of the dot file. */
2309 fprintf (file, "}\n");
2312 /* Perform offline variable substitution, discovering equivalence
2313 classes, and eliminating non-pointer variables. */
2315 static struct scc_info *
2316 perform_var_substitution (constraint_graph_t graph)
2318 unsigned int i;
2319 unsigned int size = graph->size;
2320 struct scc_info *si = init_scc_info (size);
2322 bitmap_obstack_initialize (&iteration_obstack);
2323 pointer_equiv_class_table = new hash_table<equiv_class_hasher> (511);
2324 location_equiv_class_table
2325 = new hash_table<equiv_class_hasher> (511);
2326 pointer_equiv_class = 1;
2327 location_equiv_class = 1;
2329 /* Condense the nodes, which means to find SCC's, count incoming
2330 predecessors, and unite nodes in SCC's. */
2331 for (i = 1; i < FIRST_REF_NODE; i++)
2332 if (!bitmap_bit_p (si->visited, si->node_mapping[i]))
2333 condense_visit (graph, si, si->node_mapping[i]);
2335 if (dump_file && (dump_flags & TDF_GRAPH))
2337 fprintf (dump_file, "\n\n// The constraint graph before var-substitution "
2338 "in dot format:\n");
2339 dump_pred_graph (si, dump_file);
2340 fprintf (dump_file, "\n\n");
2343 bitmap_clear (si->visited);
2344 /* Actually the label the nodes for pointer equivalences */
2345 for (i = 1; i < FIRST_REF_NODE; i++)
2346 if (!bitmap_bit_p (si->visited, si->node_mapping[i]))
2347 label_visit (graph, si, si->node_mapping[i]);
2349 /* Calculate location equivalence labels. */
2350 for (i = 1; i < FIRST_REF_NODE; i++)
2352 bitmap pointed_by;
2353 bitmap_iterator bi;
2354 unsigned int j;
2356 if (!graph->pointed_by[i])
2357 continue;
2358 pointed_by = BITMAP_ALLOC (&iteration_obstack);
2360 /* Translate the pointed-by mapping for pointer equivalence
2361 labels. */
2362 EXECUTE_IF_SET_IN_BITMAP (graph->pointed_by[i], 0, j, bi)
2364 bitmap_set_bit (pointed_by,
2365 graph->pointer_label[si->node_mapping[j]]);
2367 /* The original pointed_by is now dead. */
2368 BITMAP_FREE (graph->pointed_by[i]);
2370 /* Look up the location equivalence label if one exists, or make
2371 one otherwise. */
2372 equiv_class_label_t ecl;
2373 ecl = equiv_class_lookup_or_add (location_equiv_class_table, pointed_by);
2374 if (ecl->equivalence_class == 0)
2375 ecl->equivalence_class = location_equiv_class++;
2376 else
2378 if (dump_file && (dump_flags & TDF_DETAILS))
2379 fprintf (dump_file, "Found location equivalence for node %s\n",
2380 get_varinfo (i)->name);
2381 BITMAP_FREE (pointed_by);
2383 graph->loc_label[i] = ecl->equivalence_class;
2387 if (dump_file && (dump_flags & TDF_DETAILS))
2388 for (i = 1; i < FIRST_REF_NODE; i++)
2390 unsigned j = si->node_mapping[i];
2391 if (j != i)
2393 fprintf (dump_file, "%s node id %d ",
2394 bitmap_bit_p (graph->direct_nodes, i)
2395 ? "Direct" : "Indirect", i);
2396 if (i < FIRST_REF_NODE)
2397 fprintf (dump_file, "\"%s\"", get_varinfo (i)->name);
2398 else
2399 fprintf (dump_file, "\"*%s\"",
2400 get_varinfo (i - FIRST_REF_NODE)->name);
2401 fprintf (dump_file, " mapped to SCC leader node id %d ", j);
2402 if (j < FIRST_REF_NODE)
2403 fprintf (dump_file, "\"%s\"\n", get_varinfo (j)->name);
2404 else
2405 fprintf (dump_file, "\"*%s\"\n",
2406 get_varinfo (j - FIRST_REF_NODE)->name);
2408 else
2410 fprintf (dump_file,
2411 "Equivalence classes for %s node id %d ",
2412 bitmap_bit_p (graph->direct_nodes, i)
2413 ? "direct" : "indirect", i);
2414 if (i < FIRST_REF_NODE)
2415 fprintf (dump_file, "\"%s\"", get_varinfo (i)->name);
2416 else
2417 fprintf (dump_file, "\"*%s\"",
2418 get_varinfo (i - FIRST_REF_NODE)->name);
2419 fprintf (dump_file,
2420 ": pointer %d, location %d\n",
2421 graph->pointer_label[i], graph->loc_label[i]);
2425 /* Quickly eliminate our non-pointer variables. */
2427 for (i = 1; i < FIRST_REF_NODE; i++)
2429 unsigned int node = si->node_mapping[i];
2431 if (graph->pointer_label[node] == 0)
2433 if (dump_file && (dump_flags & TDF_DETAILS))
2434 fprintf (dump_file,
2435 "%s is a non-pointer variable, eliminating edges.\n",
2436 get_varinfo (node)->name);
2437 stats.nonpointer_vars++;
2438 clear_edges_for_node (graph, node);
2442 return si;
2445 /* Free information that was only necessary for variable
2446 substitution. */
2448 static void
2449 free_var_substitution_info (struct scc_info *si)
2451 free_scc_info (si);
2452 free (graph->pointer_label);
2453 free (graph->loc_label);
2454 free (graph->pointed_by);
2455 free (graph->points_to);
2456 free (graph->eq_rep);
2457 sbitmap_free (graph->direct_nodes);
2458 delete pointer_equiv_class_table;
2459 pointer_equiv_class_table = NULL;
2460 delete location_equiv_class_table;
2461 location_equiv_class_table = NULL;
2462 bitmap_obstack_release (&iteration_obstack);
2465 /* Return an existing node that is equivalent to NODE, which has
2466 equivalence class LABEL, if one exists. Return NODE otherwise. */
2468 static unsigned int
2469 find_equivalent_node (constraint_graph_t graph,
2470 unsigned int node, unsigned int label)
2472 /* If the address version of this variable is unused, we can
2473 substitute it for anything else with the same label.
2474 Otherwise, we know the pointers are equivalent, but not the
2475 locations, and we can unite them later. */
2477 if (!bitmap_bit_p (graph->address_taken, node))
2479 gcc_checking_assert (label < graph->size);
2481 if (graph->eq_rep[label] != -1)
2483 /* Unify the two variables since we know they are equivalent. */
2484 if (unite (graph->eq_rep[label], node))
2485 unify_nodes (graph, graph->eq_rep[label], node, false);
2486 return graph->eq_rep[label];
2488 else
2490 graph->eq_rep[label] = node;
2491 graph->pe_rep[label] = node;
2494 else
2496 gcc_checking_assert (label < graph->size);
2497 graph->pe[node] = label;
2498 if (graph->pe_rep[label] == -1)
2499 graph->pe_rep[label] = node;
2502 return node;
2505 /* Unite pointer equivalent but not location equivalent nodes in
2506 GRAPH. This may only be performed once variable substitution is
2507 finished. */
2509 static void
2510 unite_pointer_equivalences (constraint_graph_t graph)
2512 unsigned int i;
2514 /* Go through the pointer equivalences and unite them to their
2515 representative, if they aren't already. */
2516 for (i = 1; i < FIRST_REF_NODE; i++)
2518 unsigned int label = graph->pe[i];
2519 if (label)
2521 int label_rep = graph->pe_rep[label];
2523 if (label_rep == -1)
2524 continue;
2526 label_rep = find (label_rep);
2527 if (label_rep >= 0 && unite (label_rep, find (i)))
2528 unify_nodes (graph, label_rep, i, false);
2533 /* Move complex constraints to the GRAPH nodes they belong to. */
2535 static void
2536 move_complex_constraints (constraint_graph_t graph)
2538 int i;
2539 constraint_t c;
2541 FOR_EACH_VEC_ELT (constraints, i, c)
2543 if (c)
2545 struct constraint_expr lhs = c->lhs;
2546 struct constraint_expr rhs = c->rhs;
2548 if (lhs.type == DEREF)
2550 insert_into_complex (graph, lhs.var, c);
2552 else if (rhs.type == DEREF)
2554 if (!(get_varinfo (lhs.var)->is_special_var))
2555 insert_into_complex (graph, rhs.var, c);
2557 else if (rhs.type != ADDRESSOF && lhs.var > anything_id
2558 && (lhs.offset != 0 || rhs.offset != 0))
2560 insert_into_complex (graph, rhs.var, c);
2567 /* Optimize and rewrite complex constraints while performing
2568 collapsing of equivalent nodes. SI is the SCC_INFO that is the
2569 result of perform_variable_substitution. */
2571 static void
2572 rewrite_constraints (constraint_graph_t graph,
2573 struct scc_info *si)
2575 int i;
2576 constraint_t c;
2578 #ifdef ENABLE_CHECKING
2579 for (unsigned int j = 0; j < graph->size; j++)
2580 gcc_assert (find (j) == j);
2581 #endif
2583 FOR_EACH_VEC_ELT (constraints, i, c)
2585 struct constraint_expr lhs = c->lhs;
2586 struct constraint_expr rhs = c->rhs;
2587 unsigned int lhsvar = find (lhs.var);
2588 unsigned int rhsvar = find (rhs.var);
2589 unsigned int lhsnode, rhsnode;
2590 unsigned int lhslabel, rhslabel;
2592 lhsnode = si->node_mapping[lhsvar];
2593 rhsnode = si->node_mapping[rhsvar];
2594 lhslabel = graph->pointer_label[lhsnode];
2595 rhslabel = graph->pointer_label[rhsnode];
2597 /* See if it is really a non-pointer variable, and if so, ignore
2598 the constraint. */
2599 if (lhslabel == 0)
2601 if (dump_file && (dump_flags & TDF_DETAILS))
2604 fprintf (dump_file, "%s is a non-pointer variable,"
2605 "ignoring constraint:",
2606 get_varinfo (lhs.var)->name);
2607 dump_constraint (dump_file, c);
2608 fprintf (dump_file, "\n");
2610 constraints[i] = NULL;
2611 continue;
2614 if (rhslabel == 0)
2616 if (dump_file && (dump_flags & TDF_DETAILS))
2619 fprintf (dump_file, "%s is a non-pointer variable,"
2620 "ignoring constraint:",
2621 get_varinfo (rhs.var)->name);
2622 dump_constraint (dump_file, c);
2623 fprintf (dump_file, "\n");
2625 constraints[i] = NULL;
2626 continue;
2629 lhsvar = find_equivalent_node (graph, lhsvar, lhslabel);
2630 rhsvar = find_equivalent_node (graph, rhsvar, rhslabel);
2631 c->lhs.var = lhsvar;
2632 c->rhs.var = rhsvar;
2636 /* Eliminate indirect cycles involving NODE. Return true if NODE was
2637 part of an SCC, false otherwise. */
2639 static bool
2640 eliminate_indirect_cycles (unsigned int node)
2642 if (graph->indirect_cycles[node] != -1
2643 && !bitmap_empty_p (get_varinfo (node)->solution))
2645 unsigned int i;
2646 auto_vec<unsigned> queue;
2647 int queuepos;
2648 unsigned int to = find (graph->indirect_cycles[node]);
2649 bitmap_iterator bi;
2651 /* We can't touch the solution set and call unify_nodes
2652 at the same time, because unify_nodes is going to do
2653 bitmap unions into it. */
2655 EXECUTE_IF_SET_IN_BITMAP (get_varinfo (node)->solution, 0, i, bi)
2657 if (find (i) == i && i != to)
2659 if (unite (to, i))
2660 queue.safe_push (i);
2664 for (queuepos = 0;
2665 queue.iterate (queuepos, &i);
2666 queuepos++)
2668 unify_nodes (graph, to, i, true);
2670 return true;
2672 return false;
2675 /* Solve the constraint graph GRAPH using our worklist solver.
2676 This is based on the PW* family of solvers from the "Efficient Field
2677 Sensitive Pointer Analysis for C" paper.
2678 It works by iterating over all the graph nodes, processing the complex
2679 constraints and propagating the copy constraints, until everything stops
2680 changed. This corresponds to steps 6-8 in the solving list given above. */
2682 static void
2683 solve_graph (constraint_graph_t graph)
2685 unsigned int size = graph->size;
2686 unsigned int i;
2687 bitmap pts;
2689 changed = BITMAP_ALLOC (NULL);
2691 /* Mark all initial non-collapsed nodes as changed. */
2692 for (i = 1; i < size; i++)
2694 varinfo_t ivi = get_varinfo (i);
2695 if (find (i) == i && !bitmap_empty_p (ivi->solution)
2696 && ((graph->succs[i] && !bitmap_empty_p (graph->succs[i]))
2697 || graph->complex[i].length () > 0))
2698 bitmap_set_bit (changed, i);
2701 /* Allocate a bitmap to be used to store the changed bits. */
2702 pts = BITMAP_ALLOC (&pta_obstack);
2704 while (!bitmap_empty_p (changed))
2706 unsigned int i;
2707 struct topo_info *ti = init_topo_info ();
2708 stats.iterations++;
2710 bitmap_obstack_initialize (&iteration_obstack);
2712 compute_topo_order (graph, ti);
2714 while (ti->topo_order.length () != 0)
2717 i = ti->topo_order.pop ();
2719 /* If this variable is not a representative, skip it. */
2720 if (find (i) != i)
2721 continue;
2723 /* In certain indirect cycle cases, we may merge this
2724 variable to another. */
2725 if (eliminate_indirect_cycles (i) && find (i) != i)
2726 continue;
2728 /* If the node has changed, we need to process the
2729 complex constraints and outgoing edges again. */
2730 if (bitmap_clear_bit (changed, i))
2732 unsigned int j;
2733 constraint_t c;
2734 bitmap solution;
2735 vec<constraint_t> complex = graph->complex[i];
2736 varinfo_t vi = get_varinfo (i);
2737 bool solution_empty;
2739 /* Compute the changed set of solution bits. If anything
2740 is in the solution just propagate that. */
2741 if (bitmap_bit_p (vi->solution, anything_id))
2743 /* If anything is also in the old solution there is
2744 nothing to do.
2745 ??? But we shouldn't ended up with "changed" set ... */
2746 if (vi->oldsolution
2747 && bitmap_bit_p (vi->oldsolution, anything_id))
2748 continue;
2749 bitmap_copy (pts, get_varinfo (find (anything_id))->solution);
2751 else if (vi->oldsolution)
2752 bitmap_and_compl (pts, vi->solution, vi->oldsolution);
2753 else
2754 bitmap_copy (pts, vi->solution);
2756 if (bitmap_empty_p (pts))
2757 continue;
2759 if (vi->oldsolution)
2760 bitmap_ior_into (vi->oldsolution, pts);
2761 else
2763 vi->oldsolution = BITMAP_ALLOC (&oldpta_obstack);
2764 bitmap_copy (vi->oldsolution, pts);
2767 solution = vi->solution;
2768 solution_empty = bitmap_empty_p (solution);
2770 /* Process the complex constraints */
2771 bitmap expanded_pts = NULL;
2772 FOR_EACH_VEC_ELT (complex, j, c)
2774 /* XXX: This is going to unsort the constraints in
2775 some cases, which will occasionally add duplicate
2776 constraints during unification. This does not
2777 affect correctness. */
2778 c->lhs.var = find (c->lhs.var);
2779 c->rhs.var = find (c->rhs.var);
2781 /* The only complex constraint that can change our
2782 solution to non-empty, given an empty solution,
2783 is a constraint where the lhs side is receiving
2784 some set from elsewhere. */
2785 if (!solution_empty || c->lhs.type != DEREF)
2786 do_complex_constraint (graph, c, pts, &expanded_pts);
2788 BITMAP_FREE (expanded_pts);
2790 solution_empty = bitmap_empty_p (solution);
2792 if (!solution_empty)
2794 bitmap_iterator bi;
2795 unsigned eff_escaped_id = find (escaped_id);
2797 /* Propagate solution to all successors. */
2798 EXECUTE_IF_IN_NONNULL_BITMAP (graph->succs[i],
2799 0, j, bi)
2801 bitmap tmp;
2802 bool flag;
2804 unsigned int to = find (j);
2805 tmp = get_varinfo (to)->solution;
2806 flag = false;
2808 /* Don't try to propagate to ourselves. */
2809 if (to == i)
2810 continue;
2812 /* If we propagate from ESCAPED use ESCAPED as
2813 placeholder. */
2814 if (i == eff_escaped_id)
2815 flag = bitmap_set_bit (tmp, escaped_id);
2816 else
2817 flag = bitmap_ior_into (tmp, pts);
2819 if (flag)
2820 bitmap_set_bit (changed, to);
2825 free_topo_info (ti);
2826 bitmap_obstack_release (&iteration_obstack);
2829 BITMAP_FREE (pts);
2830 BITMAP_FREE (changed);
2831 bitmap_obstack_release (&oldpta_obstack);
2834 /* Map from trees to variable infos. */
2835 static hash_map<tree, varinfo_t> *vi_for_tree;
2838 /* Insert ID as the variable id for tree T in the vi_for_tree map. */
2840 static void
2841 insert_vi_for_tree (tree t, varinfo_t vi)
2843 gcc_assert (vi);
2844 gcc_assert (!vi_for_tree->put (t, vi));
2847 /* Find the variable info for tree T in VI_FOR_TREE. If T does not
2848 exist in the map, return NULL, otherwise, return the varinfo we found. */
2850 static varinfo_t
2851 lookup_vi_for_tree (tree t)
2853 varinfo_t *slot = vi_for_tree->get (t);
2854 if (slot == NULL)
2855 return NULL;
2857 return *slot;
2860 /* Return a printable name for DECL */
2862 static const char *
2863 alias_get_name (tree decl)
2865 const char *res = NULL;
2866 char *temp;
2867 int num_printed = 0;
2869 if (!dump_file)
2870 return "NULL";
2872 if (TREE_CODE (decl) == SSA_NAME)
2874 res = get_name (decl);
2875 if (res)
2876 num_printed = asprintf (&temp, "%s_%u", res, SSA_NAME_VERSION (decl));
2877 else
2878 num_printed = asprintf (&temp, "_%u", SSA_NAME_VERSION (decl));
2879 if (num_printed > 0)
2881 res = ggc_strdup (temp);
2882 free (temp);
2885 else if (DECL_P (decl))
2887 if (DECL_ASSEMBLER_NAME_SET_P (decl))
2888 res = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));
2889 else
2891 res = get_name (decl);
2892 if (!res)
2894 num_printed = asprintf (&temp, "D.%u", DECL_UID (decl));
2895 if (num_printed > 0)
2897 res = ggc_strdup (temp);
2898 free (temp);
2903 if (res != NULL)
2904 return res;
2906 return "NULL";
2909 /* Find the variable id for tree T in the map.
2910 If T doesn't exist in the map, create an entry for it and return it. */
2912 static varinfo_t
2913 get_vi_for_tree (tree t)
2915 varinfo_t *slot = vi_for_tree->get (t);
2916 if (slot == NULL)
2917 return get_varinfo (create_variable_info_for (t, alias_get_name (t)));
2919 return *slot;
2922 /* Get a scalar constraint expression for a new temporary variable. */
2924 static struct constraint_expr
2925 new_scalar_tmp_constraint_exp (const char *name)
2927 struct constraint_expr tmp;
2928 varinfo_t vi;
2930 vi = new_var_info (NULL_TREE, name);
2931 vi->offset = 0;
2932 vi->size = -1;
2933 vi->fullsize = -1;
2934 vi->is_full_var = 1;
2936 tmp.var = vi->id;
2937 tmp.type = SCALAR;
2938 tmp.offset = 0;
2940 return tmp;
2943 /* Get a constraint expression vector from an SSA_VAR_P node.
2944 If address_p is true, the result will be taken its address of. */
2946 static void
2947 get_constraint_for_ssa_var (tree t, vec<ce_s> *results, bool address_p)
2949 struct constraint_expr cexpr;
2950 varinfo_t vi;
2952 /* We allow FUNCTION_DECLs here even though it doesn't make much sense. */
2953 gcc_assert (TREE_CODE (t) == SSA_NAME || DECL_P (t));
2955 /* For parameters, get at the points-to set for the actual parm
2956 decl. */
2957 if (TREE_CODE (t) == SSA_NAME
2958 && SSA_NAME_IS_DEFAULT_DEF (t)
2959 && (TREE_CODE (SSA_NAME_VAR (t)) == PARM_DECL
2960 || TREE_CODE (SSA_NAME_VAR (t)) == RESULT_DECL))
2962 get_constraint_for_ssa_var (SSA_NAME_VAR (t), results, address_p);
2963 return;
2966 /* For global variables resort to the alias target. */
2967 if (TREE_CODE (t) == VAR_DECL
2968 && (TREE_STATIC (t) || DECL_EXTERNAL (t)))
2970 varpool_node *node = varpool_node::get (t);
2971 if (node && node->alias && node->analyzed)
2973 node = node->ultimate_alias_target ();
2974 t = node->decl;
2978 vi = get_vi_for_tree (t);
2979 cexpr.var = vi->id;
2980 cexpr.type = SCALAR;
2981 cexpr.offset = 0;
2983 /* If we are not taking the address of the constraint expr, add all
2984 sub-fiels of the variable as well. */
2985 if (!address_p
2986 && !vi->is_full_var)
2988 for (; vi; vi = vi_next (vi))
2990 cexpr.var = vi->id;
2991 results->safe_push (cexpr);
2993 return;
2996 results->safe_push (cexpr);
2999 /* Process constraint T, performing various simplifications and then
3000 adding it to our list of overall constraints. */
3002 static void
3003 process_constraint (constraint_t t)
3005 struct constraint_expr rhs = t->rhs;
3006 struct constraint_expr lhs = t->lhs;
3008 gcc_assert (rhs.var < varmap.length ());
3009 gcc_assert (lhs.var < varmap.length ());
3011 /* If we didn't get any useful constraint from the lhs we get
3012 &ANYTHING as fallback from get_constraint_for. Deal with
3013 it here by turning it into *ANYTHING. */
3014 if (lhs.type == ADDRESSOF
3015 && lhs.var == anything_id)
3016 lhs.type = DEREF;
3018 /* ADDRESSOF on the lhs is invalid. */
3019 gcc_assert (lhs.type != ADDRESSOF);
3021 /* We shouldn't add constraints from things that cannot have pointers.
3022 It's not completely trivial to avoid in the callers, so do it here. */
3023 if (rhs.type != ADDRESSOF
3024 && !get_varinfo (rhs.var)->may_have_pointers)
3025 return;
3027 /* Likewise adding to the solution of a non-pointer var isn't useful. */
3028 if (!get_varinfo (lhs.var)->may_have_pointers)
3029 return;
3031 /* This can happen in our IR with things like n->a = *p */
3032 if (rhs.type == DEREF && lhs.type == DEREF && rhs.var != anything_id)
3034 /* Split into tmp = *rhs, *lhs = tmp */
3035 struct constraint_expr tmplhs;
3036 tmplhs = new_scalar_tmp_constraint_exp ("doubledereftmp");
3037 process_constraint (new_constraint (tmplhs, rhs));
3038 process_constraint (new_constraint (lhs, tmplhs));
3040 else if (rhs.type == ADDRESSOF && lhs.type == DEREF)
3042 /* Split into tmp = &rhs, *lhs = tmp */
3043 struct constraint_expr tmplhs;
3044 tmplhs = new_scalar_tmp_constraint_exp ("derefaddrtmp");
3045 process_constraint (new_constraint (tmplhs, rhs));
3046 process_constraint (new_constraint (lhs, tmplhs));
3048 else
3050 gcc_assert (rhs.type != ADDRESSOF || rhs.offset == 0);
3051 constraints.safe_push (t);
3056 /* Return the position, in bits, of FIELD_DECL from the beginning of its
3057 structure. */
3059 static HOST_WIDE_INT
3060 bitpos_of_field (const tree fdecl)
3062 if (!tree_fits_shwi_p (DECL_FIELD_OFFSET (fdecl))
3063 || !tree_fits_shwi_p (DECL_FIELD_BIT_OFFSET (fdecl)))
3064 return -1;
3066 return (tree_to_shwi (DECL_FIELD_OFFSET (fdecl)) * BITS_PER_UNIT
3067 + tree_to_shwi (DECL_FIELD_BIT_OFFSET (fdecl)));
3071 /* Get constraint expressions for offsetting PTR by OFFSET. Stores the
3072 resulting constraint expressions in *RESULTS. */
3074 static void
3075 get_constraint_for_ptr_offset (tree ptr, tree offset,
3076 vec<ce_s> *results)
3078 struct constraint_expr c;
3079 unsigned int j, n;
3080 HOST_WIDE_INT rhsoffset;
3082 /* If we do not do field-sensitive PTA adding offsets to pointers
3083 does not change the points-to solution. */
3084 if (!use_field_sensitive)
3086 get_constraint_for_rhs (ptr, results);
3087 return;
3090 /* If the offset is not a non-negative integer constant that fits
3091 in a HOST_WIDE_INT, we have to fall back to a conservative
3092 solution which includes all sub-fields of all pointed-to
3093 variables of ptr. */
3094 if (offset == NULL_TREE
3095 || TREE_CODE (offset) != INTEGER_CST)
3096 rhsoffset = UNKNOWN_OFFSET;
3097 else
3099 /* Sign-extend the offset. */
3100 offset_int soffset = offset_int::from (offset, SIGNED);
3101 if (!wi::fits_shwi_p (soffset))
3102 rhsoffset = UNKNOWN_OFFSET;
3103 else
3105 /* Make sure the bit-offset also fits. */
3106 HOST_WIDE_INT rhsunitoffset = soffset.to_shwi ();
3107 rhsoffset = rhsunitoffset * BITS_PER_UNIT;
3108 if (rhsunitoffset != rhsoffset / BITS_PER_UNIT)
3109 rhsoffset = UNKNOWN_OFFSET;
3113 get_constraint_for_rhs (ptr, results);
3114 if (rhsoffset == 0)
3115 return;
3117 /* As we are eventually appending to the solution do not use
3118 vec::iterate here. */
3119 n = results->length ();
3120 for (j = 0; j < n; j++)
3122 varinfo_t curr;
3123 c = (*results)[j];
3124 curr = get_varinfo (c.var);
3126 if (c.type == ADDRESSOF
3127 /* If this varinfo represents a full variable just use it. */
3128 && curr->is_full_var)
3130 else if (c.type == ADDRESSOF
3131 /* If we do not know the offset add all subfields. */
3132 && rhsoffset == UNKNOWN_OFFSET)
3134 varinfo_t temp = get_varinfo (curr->head);
3137 struct constraint_expr c2;
3138 c2.var = temp->id;
3139 c2.type = ADDRESSOF;
3140 c2.offset = 0;
3141 if (c2.var != c.var)
3142 results->safe_push (c2);
3143 temp = vi_next (temp);
3145 while (temp);
3147 else if (c.type == ADDRESSOF)
3149 varinfo_t temp;
3150 unsigned HOST_WIDE_INT offset = curr->offset + rhsoffset;
3152 /* If curr->offset + rhsoffset is less than zero adjust it. */
3153 if (rhsoffset < 0
3154 && curr->offset < offset)
3155 offset = 0;
3157 /* We have to include all fields that overlap the current
3158 field shifted by rhsoffset. And we include at least
3159 the last or the first field of the variable to represent
3160 reachability of off-bound addresses, in particular &object + 1,
3161 conservatively correct. */
3162 temp = first_or_preceding_vi_for_offset (curr, offset);
3163 c.var = temp->id;
3164 c.offset = 0;
3165 temp = vi_next (temp);
3166 while (temp
3167 && temp->offset < offset + curr->size)
3169 struct constraint_expr c2;
3170 c2.var = temp->id;
3171 c2.type = ADDRESSOF;
3172 c2.offset = 0;
3173 results->safe_push (c2);
3174 temp = vi_next (temp);
3177 else if (c.type == SCALAR)
3179 gcc_assert (c.offset == 0);
3180 c.offset = rhsoffset;
3182 else
3183 /* We shouldn't get any DEREFs here. */
3184 gcc_unreachable ();
3186 (*results)[j] = c;
3191 /* Given a COMPONENT_REF T, return the constraint_expr vector for it.
3192 If address_p is true the result will be taken its address of.
3193 If lhs_p is true then the constraint expression is assumed to be used
3194 as the lhs. */
3196 static void
3197 get_constraint_for_component_ref (tree t, vec<ce_s> *results,
3198 bool address_p, bool lhs_p)
3200 tree orig_t = t;
3201 HOST_WIDE_INT bitsize = -1;
3202 HOST_WIDE_INT bitmaxsize = -1;
3203 HOST_WIDE_INT bitpos;
3204 tree forzero;
3206 /* Some people like to do cute things like take the address of
3207 &0->a.b */
3208 forzero = t;
3209 while (handled_component_p (forzero)
3210 || INDIRECT_REF_P (forzero)
3211 || TREE_CODE (forzero) == MEM_REF)
3212 forzero = TREE_OPERAND (forzero, 0);
3214 if (CONSTANT_CLASS_P (forzero) && integer_zerop (forzero))
3216 struct constraint_expr temp;
3218 temp.offset = 0;
3219 temp.var = integer_id;
3220 temp.type = SCALAR;
3221 results->safe_push (temp);
3222 return;
3225 t = get_ref_base_and_extent (t, &bitpos, &bitsize, &bitmaxsize);
3227 /* Pretend to take the address of the base, we'll take care of
3228 adding the required subset of sub-fields below. */
3229 get_constraint_for_1 (t, results, true, lhs_p);
3230 gcc_assert (results->length () == 1);
3231 struct constraint_expr &result = results->last ();
3233 if (result.type == SCALAR
3234 && get_varinfo (result.var)->is_full_var)
3235 /* For single-field vars do not bother about the offset. */
3236 result.offset = 0;
3237 else if (result.type == SCALAR)
3239 /* In languages like C, you can access one past the end of an
3240 array. You aren't allowed to dereference it, so we can
3241 ignore this constraint. When we handle pointer subtraction,
3242 we may have to do something cute here. */
3244 if ((unsigned HOST_WIDE_INT)bitpos < get_varinfo (result.var)->fullsize
3245 && bitmaxsize != 0)
3247 /* It's also not true that the constraint will actually start at the
3248 right offset, it may start in some padding. We only care about
3249 setting the constraint to the first actual field it touches, so
3250 walk to find it. */
3251 struct constraint_expr cexpr = result;
3252 varinfo_t curr;
3253 results->pop ();
3254 cexpr.offset = 0;
3255 for (curr = get_varinfo (cexpr.var); curr; curr = vi_next (curr))
3257 if (ranges_overlap_p (curr->offset, curr->size,
3258 bitpos, bitmaxsize))
3260 cexpr.var = curr->id;
3261 results->safe_push (cexpr);
3262 if (address_p)
3263 break;
3266 /* If we are going to take the address of this field then
3267 to be able to compute reachability correctly add at least
3268 the last field of the variable. */
3269 if (address_p && results->length () == 0)
3271 curr = get_varinfo (cexpr.var);
3272 while (curr->next != 0)
3273 curr = vi_next (curr);
3274 cexpr.var = curr->id;
3275 results->safe_push (cexpr);
3277 else if (results->length () == 0)
3278 /* Assert that we found *some* field there. The user couldn't be
3279 accessing *only* padding. */
3280 /* Still the user could access one past the end of an array
3281 embedded in a struct resulting in accessing *only* padding. */
3282 /* Or accessing only padding via type-punning to a type
3283 that has a filed just in padding space. */
3285 cexpr.type = SCALAR;
3286 cexpr.var = anything_id;
3287 cexpr.offset = 0;
3288 results->safe_push (cexpr);
3291 else if (bitmaxsize == 0)
3293 if (dump_file && (dump_flags & TDF_DETAILS))
3294 fprintf (dump_file, "Access to zero-sized part of variable,"
3295 "ignoring\n");
3297 else
3298 if (dump_file && (dump_flags & TDF_DETAILS))
3299 fprintf (dump_file, "Access to past the end of variable, ignoring\n");
3301 else if (result.type == DEREF)
3303 /* If we do not know exactly where the access goes say so. Note
3304 that only for non-structure accesses we know that we access
3305 at most one subfiled of any variable. */
3306 if (bitpos == -1
3307 || bitsize != bitmaxsize
3308 || AGGREGATE_TYPE_P (TREE_TYPE (orig_t))
3309 || result.offset == UNKNOWN_OFFSET)
3310 result.offset = UNKNOWN_OFFSET;
3311 else
3312 result.offset += bitpos;
3314 else if (result.type == ADDRESSOF)
3316 /* We can end up here for component references on a
3317 VIEW_CONVERT_EXPR <>(&foobar). */
3318 result.type = SCALAR;
3319 result.var = anything_id;
3320 result.offset = 0;
3322 else
3323 gcc_unreachable ();
3327 /* Dereference the constraint expression CONS, and return the result.
3328 DEREF (ADDRESSOF) = SCALAR
3329 DEREF (SCALAR) = DEREF
3330 DEREF (DEREF) = (temp = DEREF1; result = DEREF(temp))
3331 This is needed so that we can handle dereferencing DEREF constraints. */
3333 static void
3334 do_deref (vec<ce_s> *constraints)
3336 struct constraint_expr *c;
3337 unsigned int i = 0;
3339 FOR_EACH_VEC_ELT (*constraints, i, c)
3341 if (c->type == SCALAR)
3342 c->type = DEREF;
3343 else if (c->type == ADDRESSOF)
3344 c->type = SCALAR;
3345 else if (c->type == DEREF)
3347 struct constraint_expr tmplhs;
3348 tmplhs = new_scalar_tmp_constraint_exp ("dereftmp");
3349 process_constraint (new_constraint (tmplhs, *c));
3350 c->var = tmplhs.var;
3352 else
3353 gcc_unreachable ();
3357 /* Given a tree T, return the constraint expression for taking the
3358 address of it. */
3360 static void
3361 get_constraint_for_address_of (tree t, vec<ce_s> *results)
3363 struct constraint_expr *c;
3364 unsigned int i;
3366 get_constraint_for_1 (t, results, true, true);
3368 FOR_EACH_VEC_ELT (*results, i, c)
3370 if (c->type == DEREF)
3371 c->type = SCALAR;
3372 else
3373 c->type = ADDRESSOF;
3377 /* Given a tree T, return the constraint expression for it. */
3379 static void
3380 get_constraint_for_1 (tree t, vec<ce_s> *results, bool address_p,
3381 bool lhs_p)
3383 struct constraint_expr temp;
3385 /* x = integer is all glommed to a single variable, which doesn't
3386 point to anything by itself. That is, of course, unless it is an
3387 integer constant being treated as a pointer, in which case, we
3388 will return that this is really the addressof anything. This
3389 happens below, since it will fall into the default case. The only
3390 case we know something about an integer treated like a pointer is
3391 when it is the NULL pointer, and then we just say it points to
3392 NULL.
3394 Do not do that if -fno-delete-null-pointer-checks though, because
3395 in that case *NULL does not fail, so it _should_ alias *anything.
3396 It is not worth adding a new option or renaming the existing one,
3397 since this case is relatively obscure. */
3398 if ((TREE_CODE (t) == INTEGER_CST
3399 && integer_zerop (t))
3400 /* The only valid CONSTRUCTORs in gimple with pointer typed
3401 elements are zero-initializer. But in IPA mode we also
3402 process global initializers, so verify at least. */
3403 || (TREE_CODE (t) == CONSTRUCTOR
3404 && CONSTRUCTOR_NELTS (t) == 0))
3406 if (flag_delete_null_pointer_checks)
3407 temp.var = nothing_id;
3408 else
3409 temp.var = nonlocal_id;
3410 temp.type = ADDRESSOF;
3411 temp.offset = 0;
3412 results->safe_push (temp);
3413 return;
3416 /* String constants are read-only, ideally we'd have a CONST_DECL
3417 for those. */
3418 if (TREE_CODE (t) == STRING_CST)
3420 temp.var = string_id;
3421 temp.type = SCALAR;
3422 temp.offset = 0;
3423 results->safe_push (temp);
3424 return;
3427 switch (TREE_CODE_CLASS (TREE_CODE (t)))
3429 case tcc_expression:
3431 switch (TREE_CODE (t))
3433 case ADDR_EXPR:
3434 get_constraint_for_address_of (TREE_OPERAND (t, 0), results);
3435 return;
3436 default:;
3438 break;
3440 case tcc_reference:
3442 switch (TREE_CODE (t))
3444 case MEM_REF:
3446 struct constraint_expr cs;
3447 varinfo_t vi, curr;
3448 get_constraint_for_ptr_offset (TREE_OPERAND (t, 0),
3449 TREE_OPERAND (t, 1), results);
3450 do_deref (results);
3452 /* If we are not taking the address then make sure to process
3453 all subvariables we might access. */
3454 if (address_p)
3455 return;
3457 cs = results->last ();
3458 if (cs.type == DEREF
3459 && type_can_have_subvars (TREE_TYPE (t)))
3461 /* For dereferences this means we have to defer it
3462 to solving time. */
3463 results->last ().offset = UNKNOWN_OFFSET;
3464 return;
3466 if (cs.type != SCALAR)
3467 return;
3469 vi = get_varinfo (cs.var);
3470 curr = vi_next (vi);
3471 if (!vi->is_full_var
3472 && curr)
3474 unsigned HOST_WIDE_INT size;
3475 if (tree_fits_uhwi_p (TYPE_SIZE (TREE_TYPE (t))))
3476 size = tree_to_uhwi (TYPE_SIZE (TREE_TYPE (t)));
3477 else
3478 size = -1;
3479 for (; curr; curr = vi_next (curr))
3481 if (curr->offset - vi->offset < size)
3483 cs.var = curr->id;
3484 results->safe_push (cs);
3486 else
3487 break;
3490 return;
3492 case ARRAY_REF:
3493 case ARRAY_RANGE_REF:
3494 case COMPONENT_REF:
3495 get_constraint_for_component_ref (t, results, address_p, lhs_p);
3496 return;
3497 case VIEW_CONVERT_EXPR:
3498 get_constraint_for_1 (TREE_OPERAND (t, 0), results, address_p,
3499 lhs_p);
3500 return;
3501 /* We are missing handling for TARGET_MEM_REF here. */
3502 default:;
3504 break;
3506 case tcc_exceptional:
3508 switch (TREE_CODE (t))
3510 case SSA_NAME:
3512 get_constraint_for_ssa_var (t, results, address_p);
3513 return;
3515 case CONSTRUCTOR:
3517 unsigned int i;
3518 tree val;
3519 auto_vec<ce_s> tmp;
3520 FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (t), i, val)
3522 struct constraint_expr *rhsp;
3523 unsigned j;
3524 get_constraint_for_1 (val, &tmp, address_p, lhs_p);
3525 FOR_EACH_VEC_ELT (tmp, j, rhsp)
3526 results->safe_push (*rhsp);
3527 tmp.truncate (0);
3529 /* We do not know whether the constructor was complete,
3530 so technically we have to add &NOTHING or &ANYTHING
3531 like we do for an empty constructor as well. */
3532 return;
3534 default:;
3536 break;
3538 case tcc_declaration:
3540 get_constraint_for_ssa_var (t, results, address_p);
3541 return;
3543 case tcc_constant:
3545 /* We cannot refer to automatic variables through constants. */
3546 temp.type = ADDRESSOF;
3547 temp.var = nonlocal_id;
3548 temp.offset = 0;
3549 results->safe_push (temp);
3550 return;
3552 default:;
3555 /* The default fallback is a constraint from anything. */
3556 temp.type = ADDRESSOF;
3557 temp.var = anything_id;
3558 temp.offset = 0;
3559 results->safe_push (temp);
3562 /* Given a gimple tree T, return the constraint expression vector for it. */
3564 static void
3565 get_constraint_for (tree t, vec<ce_s> *results)
3567 gcc_assert (results->length () == 0);
3569 get_constraint_for_1 (t, results, false, true);
3572 /* Given a gimple tree T, return the constraint expression vector for it
3573 to be used as the rhs of a constraint. */
3575 static void
3576 get_constraint_for_rhs (tree t, vec<ce_s> *results)
3578 gcc_assert (results->length () == 0);
3580 get_constraint_for_1 (t, results, false, false);
3584 /* Efficiently generates constraints from all entries in *RHSC to all
3585 entries in *LHSC. */
3587 static void
3588 process_all_all_constraints (vec<ce_s> lhsc,
3589 vec<ce_s> rhsc)
3591 struct constraint_expr *lhsp, *rhsp;
3592 unsigned i, j;
3594 if (lhsc.length () <= 1 || rhsc.length () <= 1)
3596 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
3597 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
3598 process_constraint (new_constraint (*lhsp, *rhsp));
3600 else
3602 struct constraint_expr tmp;
3603 tmp = new_scalar_tmp_constraint_exp ("allalltmp");
3604 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
3605 process_constraint (new_constraint (tmp, *rhsp));
3606 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
3607 process_constraint (new_constraint (*lhsp, tmp));
3611 /* Handle aggregate copies by expanding into copies of the respective
3612 fields of the structures. */
3614 static void
3615 do_structure_copy (tree lhsop, tree rhsop)
3617 struct constraint_expr *lhsp, *rhsp;
3618 auto_vec<ce_s> lhsc;
3619 auto_vec<ce_s> rhsc;
3620 unsigned j;
3622 get_constraint_for (lhsop, &lhsc);
3623 get_constraint_for_rhs (rhsop, &rhsc);
3624 lhsp = &lhsc[0];
3625 rhsp = &rhsc[0];
3626 if (lhsp->type == DEREF
3627 || (lhsp->type == ADDRESSOF && lhsp->var == anything_id)
3628 || rhsp->type == DEREF)
3630 if (lhsp->type == DEREF)
3632 gcc_assert (lhsc.length () == 1);
3633 lhsp->offset = UNKNOWN_OFFSET;
3635 if (rhsp->type == DEREF)
3637 gcc_assert (rhsc.length () == 1);
3638 rhsp->offset = UNKNOWN_OFFSET;
3640 process_all_all_constraints (lhsc, rhsc);
3642 else if (lhsp->type == SCALAR
3643 && (rhsp->type == SCALAR
3644 || rhsp->type == ADDRESSOF))
3646 HOST_WIDE_INT lhssize, lhsmaxsize, lhsoffset;
3647 HOST_WIDE_INT rhssize, rhsmaxsize, rhsoffset;
3648 unsigned k = 0;
3649 get_ref_base_and_extent (lhsop, &lhsoffset, &lhssize, &lhsmaxsize);
3650 get_ref_base_and_extent (rhsop, &rhsoffset, &rhssize, &rhsmaxsize);
3651 for (j = 0; lhsc.iterate (j, &lhsp);)
3653 varinfo_t lhsv, rhsv;
3654 rhsp = &rhsc[k];
3655 lhsv = get_varinfo (lhsp->var);
3656 rhsv = get_varinfo (rhsp->var);
3657 if (lhsv->may_have_pointers
3658 && (lhsv->is_full_var
3659 || rhsv->is_full_var
3660 || ranges_overlap_p (lhsv->offset + rhsoffset, lhsv->size,
3661 rhsv->offset + lhsoffset, rhsv->size)))
3662 process_constraint (new_constraint (*lhsp, *rhsp));
3663 if (!rhsv->is_full_var
3664 && (lhsv->is_full_var
3665 || (lhsv->offset + rhsoffset + lhsv->size
3666 > rhsv->offset + lhsoffset + rhsv->size)))
3668 ++k;
3669 if (k >= rhsc.length ())
3670 break;
3672 else
3673 ++j;
3676 else
3677 gcc_unreachable ();
3680 /* Create constraints ID = { rhsc }. */
3682 static void
3683 make_constraints_to (unsigned id, vec<ce_s> rhsc)
3685 struct constraint_expr *c;
3686 struct constraint_expr includes;
3687 unsigned int j;
3689 includes.var = id;
3690 includes.offset = 0;
3691 includes.type = SCALAR;
3693 FOR_EACH_VEC_ELT (rhsc, j, c)
3694 process_constraint (new_constraint (includes, *c));
3697 /* Create a constraint ID = OP. */
3699 static void
3700 make_constraint_to (unsigned id, tree op)
3702 auto_vec<ce_s> rhsc;
3703 get_constraint_for_rhs (op, &rhsc);
3704 make_constraints_to (id, rhsc);
3707 /* Create a constraint ID = &FROM. */
3709 static void
3710 make_constraint_from (varinfo_t vi, int from)
3712 struct constraint_expr lhs, rhs;
3714 lhs.var = vi->id;
3715 lhs.offset = 0;
3716 lhs.type = SCALAR;
3718 rhs.var = from;
3719 rhs.offset = 0;
3720 rhs.type = ADDRESSOF;
3721 process_constraint (new_constraint (lhs, rhs));
3724 /* Create a constraint ID = FROM. */
3726 static void
3727 make_copy_constraint (varinfo_t vi, int from)
3729 struct constraint_expr lhs, rhs;
3731 lhs.var = vi->id;
3732 lhs.offset = 0;
3733 lhs.type = SCALAR;
3735 rhs.var = from;
3736 rhs.offset = 0;
3737 rhs.type = SCALAR;
3738 process_constraint (new_constraint (lhs, rhs));
3741 /* Make constraints necessary to make OP escape. */
3743 static void
3744 make_escape_constraint (tree op)
3746 make_constraint_to (escaped_id, op);
3749 /* Add constraints to that the solution of VI is transitively closed. */
3751 static void
3752 make_transitive_closure_constraints (varinfo_t vi)
3754 struct constraint_expr lhs, rhs;
3756 /* VAR = *VAR; */
3757 lhs.type = SCALAR;
3758 lhs.var = vi->id;
3759 lhs.offset = 0;
3760 rhs.type = DEREF;
3761 rhs.var = vi->id;
3762 rhs.offset = UNKNOWN_OFFSET;
3763 process_constraint (new_constraint (lhs, rhs));
3766 /* Temporary storage for fake var decls. */
3767 struct obstack fake_var_decl_obstack;
3769 /* Build a fake VAR_DECL acting as referrer to a DECL_UID. */
3771 static tree
3772 build_fake_var_decl (tree type)
3774 tree decl = (tree) XOBNEW (&fake_var_decl_obstack, struct tree_var_decl);
3775 memset (decl, 0, sizeof (struct tree_var_decl));
3776 TREE_SET_CODE (decl, VAR_DECL);
3777 TREE_TYPE (decl) = type;
3778 DECL_UID (decl) = allocate_decl_uid ();
3779 SET_DECL_PT_UID (decl, -1);
3780 layout_decl (decl, 0);
3781 return decl;
3784 /* Create a new artificial heap variable with NAME.
3785 Return the created variable. */
3787 static varinfo_t
3788 make_heapvar (const char *name)
3790 varinfo_t vi;
3791 tree heapvar;
3793 heapvar = build_fake_var_decl (ptr_type_node);
3794 DECL_EXTERNAL (heapvar) = 1;
3796 vi = new_var_info (heapvar, name);
3797 vi->is_artificial_var = true;
3798 vi->is_heap_var = true;
3799 vi->is_unknown_size_var = true;
3800 vi->offset = 0;
3801 vi->fullsize = ~0;
3802 vi->size = ~0;
3803 vi->is_full_var = true;
3804 insert_vi_for_tree (heapvar, vi);
3806 return vi;
3809 /* Create a new artificial heap variable with NAME and make a
3810 constraint from it to LHS. Set flags according to a tag used
3811 for tracking restrict pointers. */
3813 static varinfo_t
3814 make_constraint_from_restrict (varinfo_t lhs, const char *name)
3816 varinfo_t vi = make_heapvar (name);
3817 vi->is_restrict_var = 1;
3818 vi->is_global_var = 1;
3819 vi->may_have_pointers = 1;
3820 make_constraint_from (lhs, vi->id);
3821 return vi;
3824 /* Create a new artificial heap variable with NAME and make a
3825 constraint from it to LHS. Set flags according to a tag used
3826 for tracking restrict pointers and make the artificial heap
3827 point to global memory. */
3829 static varinfo_t
3830 make_constraint_from_global_restrict (varinfo_t lhs, const char *name)
3832 varinfo_t vi = make_constraint_from_restrict (lhs, name);
3833 make_copy_constraint (vi, nonlocal_id);
3834 return vi;
3837 /* In IPA mode there are varinfos for different aspects of reach
3838 function designator. One for the points-to set of the return
3839 value, one for the variables that are clobbered by the function,
3840 one for its uses and one for each parameter (including a single
3841 glob for remaining variadic arguments). */
3843 enum { fi_clobbers = 1, fi_uses = 2,
3844 fi_static_chain = 3, fi_result = 4, fi_parm_base = 5 };
3846 /* Get a constraint for the requested part of a function designator FI
3847 when operating in IPA mode. */
3849 static struct constraint_expr
3850 get_function_part_constraint (varinfo_t fi, unsigned part)
3852 struct constraint_expr c;
3854 gcc_assert (in_ipa_mode);
3856 if (fi->id == anything_id)
3858 /* ??? We probably should have a ANYFN special variable. */
3859 c.var = anything_id;
3860 c.offset = 0;
3861 c.type = SCALAR;
3863 else if (TREE_CODE (fi->decl) == FUNCTION_DECL)
3865 varinfo_t ai = first_vi_for_offset (fi, part);
3866 if (ai)
3867 c.var = ai->id;
3868 else
3869 c.var = anything_id;
3870 c.offset = 0;
3871 c.type = SCALAR;
3873 else
3875 c.var = fi->id;
3876 c.offset = part;
3877 c.type = DEREF;
3880 return c;
3883 /* For non-IPA mode, generate constraints necessary for a call on the
3884 RHS. */
3886 static void
3887 handle_rhs_call (gcall *stmt, vec<ce_s> *results)
3889 struct constraint_expr rhsc;
3890 unsigned i;
3891 bool returns_uses = false;
3893 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3895 tree arg = gimple_call_arg (stmt, i);
3896 int flags = gimple_call_arg_flags (stmt, i);
3898 /* If the argument is not used we can ignore it. */
3899 if (flags & EAF_UNUSED)
3900 continue;
3902 /* As we compute ESCAPED context-insensitive we do not gain
3903 any precision with just EAF_NOCLOBBER but not EAF_NOESCAPE
3904 set. The argument would still get clobbered through the
3905 escape solution. */
3906 if ((flags & EAF_NOCLOBBER)
3907 && (flags & EAF_NOESCAPE))
3909 varinfo_t uses = get_call_use_vi (stmt);
3910 if (!(flags & EAF_DIRECT))
3912 varinfo_t tem = new_var_info (NULL_TREE, "callarg");
3913 make_constraint_to (tem->id, arg);
3914 make_transitive_closure_constraints (tem);
3915 make_copy_constraint (uses, tem->id);
3917 else
3918 make_constraint_to (uses->id, arg);
3919 returns_uses = true;
3921 else if (flags & EAF_NOESCAPE)
3923 struct constraint_expr lhs, rhs;
3924 varinfo_t uses = get_call_use_vi (stmt);
3925 varinfo_t clobbers = get_call_clobber_vi (stmt);
3926 varinfo_t tem = new_var_info (NULL_TREE, "callarg");
3927 make_constraint_to (tem->id, arg);
3928 if (!(flags & EAF_DIRECT))
3929 make_transitive_closure_constraints (tem);
3930 make_copy_constraint (uses, tem->id);
3931 make_copy_constraint (clobbers, tem->id);
3932 /* Add *tem = nonlocal, do not add *tem = callused as
3933 EAF_NOESCAPE parameters do not escape to other parameters
3934 and all other uses appear in NONLOCAL as well. */
3935 lhs.type = DEREF;
3936 lhs.var = tem->id;
3937 lhs.offset = 0;
3938 rhs.type = SCALAR;
3939 rhs.var = nonlocal_id;
3940 rhs.offset = 0;
3941 process_constraint (new_constraint (lhs, rhs));
3942 returns_uses = true;
3944 else
3945 make_escape_constraint (arg);
3948 /* If we added to the calls uses solution make sure we account for
3949 pointers to it to be returned. */
3950 if (returns_uses)
3952 rhsc.var = get_call_use_vi (stmt)->id;
3953 rhsc.offset = 0;
3954 rhsc.type = SCALAR;
3955 results->safe_push (rhsc);
3958 /* The static chain escapes as well. */
3959 if (gimple_call_chain (stmt))
3960 make_escape_constraint (gimple_call_chain (stmt));
3962 /* And if we applied NRV the address of the return slot escapes as well. */
3963 if (gimple_call_return_slot_opt_p (stmt)
3964 && gimple_call_lhs (stmt) != NULL_TREE
3965 && TREE_ADDRESSABLE (TREE_TYPE (gimple_call_lhs (stmt))))
3967 auto_vec<ce_s> tmpc;
3968 struct constraint_expr lhsc, *c;
3969 get_constraint_for_address_of (gimple_call_lhs (stmt), &tmpc);
3970 lhsc.var = escaped_id;
3971 lhsc.offset = 0;
3972 lhsc.type = SCALAR;
3973 FOR_EACH_VEC_ELT (tmpc, i, c)
3974 process_constraint (new_constraint (lhsc, *c));
3977 /* Regular functions return nonlocal memory. */
3978 rhsc.var = nonlocal_id;
3979 rhsc.offset = 0;
3980 rhsc.type = SCALAR;
3981 results->safe_push (rhsc);
3984 /* For non-IPA mode, generate constraints necessary for a call
3985 that returns a pointer and assigns it to LHS. This simply makes
3986 the LHS point to global and escaped variables. */
3988 static void
3989 handle_lhs_call (gcall *stmt, tree lhs, int flags, vec<ce_s> rhsc,
3990 tree fndecl)
3992 auto_vec<ce_s> lhsc;
3994 get_constraint_for (lhs, &lhsc);
3995 /* If the store is to a global decl make sure to
3996 add proper escape constraints. */
3997 lhs = get_base_address (lhs);
3998 if (lhs
3999 && DECL_P (lhs)
4000 && is_global_var (lhs))
4002 struct constraint_expr tmpc;
4003 tmpc.var = escaped_id;
4004 tmpc.offset = 0;
4005 tmpc.type = SCALAR;
4006 lhsc.safe_push (tmpc);
4009 /* If the call returns an argument unmodified override the rhs
4010 constraints. */
4011 if (flags & ERF_RETURNS_ARG
4012 && (flags & ERF_RETURN_ARG_MASK) < gimple_call_num_args (stmt))
4014 tree arg;
4015 rhsc.create (0);
4016 arg = gimple_call_arg (stmt, flags & ERF_RETURN_ARG_MASK);
4017 get_constraint_for (arg, &rhsc);
4018 process_all_all_constraints (lhsc, rhsc);
4019 rhsc.release ();
4021 else if (flags & ERF_NOALIAS)
4023 varinfo_t vi;
4024 struct constraint_expr tmpc;
4025 rhsc.create (0);
4026 vi = make_heapvar ("HEAP");
4027 /* We are marking allocated storage local, we deal with it becoming
4028 global by escaping and setting of vars_contains_escaped_heap. */
4029 DECL_EXTERNAL (vi->decl) = 0;
4030 vi->is_global_var = 0;
4031 /* If this is not a real malloc call assume the memory was
4032 initialized and thus may point to global memory. All
4033 builtin functions with the malloc attribute behave in a sane way. */
4034 if (!fndecl
4035 || DECL_BUILT_IN_CLASS (fndecl) != BUILT_IN_NORMAL)
4036 make_constraint_from (vi, nonlocal_id);
4037 tmpc.var = vi->id;
4038 tmpc.offset = 0;
4039 tmpc.type = ADDRESSOF;
4040 rhsc.safe_push (tmpc);
4041 process_all_all_constraints (lhsc, rhsc);
4042 rhsc.release ();
4044 else
4045 process_all_all_constraints (lhsc, rhsc);
4048 /* For non-IPA mode, generate constraints necessary for a call of a
4049 const function that returns a pointer in the statement STMT. */
4051 static void
4052 handle_const_call (gcall *stmt, vec<ce_s> *results)
4054 struct constraint_expr rhsc;
4055 unsigned int k;
4057 /* Treat nested const functions the same as pure functions as far
4058 as the static chain is concerned. */
4059 if (gimple_call_chain (stmt))
4061 varinfo_t uses = get_call_use_vi (stmt);
4062 make_transitive_closure_constraints (uses);
4063 make_constraint_to (uses->id, gimple_call_chain (stmt));
4064 rhsc.var = uses->id;
4065 rhsc.offset = 0;
4066 rhsc.type = SCALAR;
4067 results->safe_push (rhsc);
4070 /* May return arguments. */
4071 for (k = 0; k < gimple_call_num_args (stmt); ++k)
4073 tree arg = gimple_call_arg (stmt, k);
4074 auto_vec<ce_s> argc;
4075 unsigned i;
4076 struct constraint_expr *argp;
4077 get_constraint_for_rhs (arg, &argc);
4078 FOR_EACH_VEC_ELT (argc, i, argp)
4079 results->safe_push (*argp);
4082 /* May return addresses of globals. */
4083 rhsc.var = nonlocal_id;
4084 rhsc.offset = 0;
4085 rhsc.type = ADDRESSOF;
4086 results->safe_push (rhsc);
4089 /* For non-IPA mode, generate constraints necessary for a call to a
4090 pure function in statement STMT. */
4092 static void
4093 handle_pure_call (gcall *stmt, vec<ce_s> *results)
4095 struct constraint_expr rhsc;
4096 unsigned i;
4097 varinfo_t uses = NULL;
4099 /* Memory reached from pointer arguments is call-used. */
4100 for (i = 0; i < gimple_call_num_args (stmt); ++i)
4102 tree arg = gimple_call_arg (stmt, i);
4103 if (!uses)
4105 uses = get_call_use_vi (stmt);
4106 make_transitive_closure_constraints (uses);
4108 make_constraint_to (uses->id, arg);
4111 /* The static chain is used as well. */
4112 if (gimple_call_chain (stmt))
4114 if (!uses)
4116 uses = get_call_use_vi (stmt);
4117 make_transitive_closure_constraints (uses);
4119 make_constraint_to (uses->id, gimple_call_chain (stmt));
4122 /* Pure functions may return call-used and nonlocal memory. */
4123 if (uses)
4125 rhsc.var = uses->id;
4126 rhsc.offset = 0;
4127 rhsc.type = SCALAR;
4128 results->safe_push (rhsc);
4130 rhsc.var = nonlocal_id;
4131 rhsc.offset = 0;
4132 rhsc.type = SCALAR;
4133 results->safe_push (rhsc);
4137 /* Return the varinfo for the callee of CALL. */
4139 static varinfo_t
4140 get_fi_for_callee (gcall *call)
4142 tree decl, fn = gimple_call_fn (call);
4144 if (fn && TREE_CODE (fn) == OBJ_TYPE_REF)
4145 fn = OBJ_TYPE_REF_EXPR (fn);
4147 /* If we can directly resolve the function being called, do so.
4148 Otherwise, it must be some sort of indirect expression that
4149 we should still be able to handle. */
4150 decl = gimple_call_addr_fndecl (fn);
4151 if (decl)
4152 return get_vi_for_tree (decl);
4154 /* If the function is anything other than a SSA name pointer we have no
4155 clue and should be getting ANYFN (well, ANYTHING for now). */
4156 if (!fn || TREE_CODE (fn) != SSA_NAME)
4157 return get_varinfo (anything_id);
4159 if (SSA_NAME_IS_DEFAULT_DEF (fn)
4160 && (TREE_CODE (SSA_NAME_VAR (fn)) == PARM_DECL
4161 || TREE_CODE (SSA_NAME_VAR (fn)) == RESULT_DECL))
4162 fn = SSA_NAME_VAR (fn);
4164 return get_vi_for_tree (fn);
4167 /* Create constraints for the builtin call T. Return true if the call
4168 was handled, otherwise false. */
4170 static bool
4171 find_func_aliases_for_builtin_call (struct function *fn, gcall *t)
4173 tree fndecl = gimple_call_fndecl (t);
4174 auto_vec<ce_s, 2> lhsc;
4175 auto_vec<ce_s, 4> rhsc;
4176 varinfo_t fi;
4178 if (gimple_call_builtin_p (t, BUILT_IN_NORMAL))
4179 /* ??? All builtins that are handled here need to be handled
4180 in the alias-oracle query functions explicitly! */
4181 switch (DECL_FUNCTION_CODE (fndecl))
4183 /* All the following functions return a pointer to the same object
4184 as their first argument points to. The functions do not add
4185 to the ESCAPED solution. The functions make the first argument
4186 pointed to memory point to what the second argument pointed to
4187 memory points to. */
4188 case BUILT_IN_STRCPY:
4189 case BUILT_IN_STRNCPY:
4190 case BUILT_IN_BCOPY:
4191 case BUILT_IN_MEMCPY:
4192 case BUILT_IN_MEMMOVE:
4193 case BUILT_IN_MEMPCPY:
4194 case BUILT_IN_STPCPY:
4195 case BUILT_IN_STPNCPY:
4196 case BUILT_IN_STRCAT:
4197 case BUILT_IN_STRNCAT:
4198 case BUILT_IN_STRCPY_CHK:
4199 case BUILT_IN_STRNCPY_CHK:
4200 case BUILT_IN_MEMCPY_CHK:
4201 case BUILT_IN_MEMMOVE_CHK:
4202 case BUILT_IN_MEMPCPY_CHK:
4203 case BUILT_IN_STPCPY_CHK:
4204 case BUILT_IN_STPNCPY_CHK:
4205 case BUILT_IN_STRCAT_CHK:
4206 case BUILT_IN_STRNCAT_CHK:
4207 case BUILT_IN_TM_MEMCPY:
4208 case BUILT_IN_TM_MEMMOVE:
4210 tree res = gimple_call_lhs (t);
4211 tree dest = gimple_call_arg (t, (DECL_FUNCTION_CODE (fndecl)
4212 == BUILT_IN_BCOPY ? 1 : 0));
4213 tree src = gimple_call_arg (t, (DECL_FUNCTION_CODE (fndecl)
4214 == BUILT_IN_BCOPY ? 0 : 1));
4215 if (res != NULL_TREE)
4217 get_constraint_for (res, &lhsc);
4218 if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_MEMPCPY
4219 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPCPY
4220 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPNCPY
4221 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_MEMPCPY_CHK
4222 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPCPY_CHK
4223 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_STPNCPY_CHK)
4224 get_constraint_for_ptr_offset (dest, NULL_TREE, &rhsc);
4225 else
4226 get_constraint_for (dest, &rhsc);
4227 process_all_all_constraints (lhsc, rhsc);
4228 lhsc.truncate (0);
4229 rhsc.truncate (0);
4231 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4232 get_constraint_for_ptr_offset (src, NULL_TREE, &rhsc);
4233 do_deref (&lhsc);
4234 do_deref (&rhsc);
4235 process_all_all_constraints (lhsc, rhsc);
4236 return true;
4238 case BUILT_IN_MEMSET:
4239 case BUILT_IN_MEMSET_CHK:
4240 case BUILT_IN_TM_MEMSET:
4242 tree res = gimple_call_lhs (t);
4243 tree dest = gimple_call_arg (t, 0);
4244 unsigned i;
4245 ce_s *lhsp;
4246 struct constraint_expr ac;
4247 if (res != NULL_TREE)
4249 get_constraint_for (res, &lhsc);
4250 get_constraint_for (dest, &rhsc);
4251 process_all_all_constraints (lhsc, rhsc);
4252 lhsc.truncate (0);
4254 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4255 do_deref (&lhsc);
4256 if (flag_delete_null_pointer_checks
4257 && integer_zerop (gimple_call_arg (t, 1)))
4259 ac.type = ADDRESSOF;
4260 ac.var = nothing_id;
4262 else
4264 ac.type = SCALAR;
4265 ac.var = integer_id;
4267 ac.offset = 0;
4268 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
4269 process_constraint (new_constraint (*lhsp, ac));
4270 return true;
4272 case BUILT_IN_POSIX_MEMALIGN:
4274 tree ptrptr = gimple_call_arg (t, 0);
4275 get_constraint_for (ptrptr, &lhsc);
4276 do_deref (&lhsc);
4277 varinfo_t vi = make_heapvar ("HEAP");
4278 /* We are marking allocated storage local, we deal with it becoming
4279 global by escaping and setting of vars_contains_escaped_heap. */
4280 DECL_EXTERNAL (vi->decl) = 0;
4281 vi->is_global_var = 0;
4282 struct constraint_expr tmpc;
4283 tmpc.var = vi->id;
4284 tmpc.offset = 0;
4285 tmpc.type = ADDRESSOF;
4286 rhsc.safe_push (tmpc);
4287 process_all_all_constraints (lhsc, rhsc);
4288 return true;
4290 case BUILT_IN_ASSUME_ALIGNED:
4292 tree res = gimple_call_lhs (t);
4293 tree dest = gimple_call_arg (t, 0);
4294 if (res != NULL_TREE)
4296 get_constraint_for (res, &lhsc);
4297 get_constraint_for (dest, &rhsc);
4298 process_all_all_constraints (lhsc, rhsc);
4300 return true;
4302 /* All the following functions do not return pointers, do not
4303 modify the points-to sets of memory reachable from their
4304 arguments and do not add to the ESCAPED solution. */
4305 case BUILT_IN_SINCOS:
4306 case BUILT_IN_SINCOSF:
4307 case BUILT_IN_SINCOSL:
4308 case BUILT_IN_FREXP:
4309 case BUILT_IN_FREXPF:
4310 case BUILT_IN_FREXPL:
4311 case BUILT_IN_GAMMA_R:
4312 case BUILT_IN_GAMMAF_R:
4313 case BUILT_IN_GAMMAL_R:
4314 case BUILT_IN_LGAMMA_R:
4315 case BUILT_IN_LGAMMAF_R:
4316 case BUILT_IN_LGAMMAL_R:
4317 case BUILT_IN_MODF:
4318 case BUILT_IN_MODFF:
4319 case BUILT_IN_MODFL:
4320 case BUILT_IN_REMQUO:
4321 case BUILT_IN_REMQUOF:
4322 case BUILT_IN_REMQUOL:
4323 case BUILT_IN_FREE:
4324 return true;
4325 case BUILT_IN_STRDUP:
4326 case BUILT_IN_STRNDUP:
4327 case BUILT_IN_REALLOC:
4328 if (gimple_call_lhs (t))
4330 handle_lhs_call (t, gimple_call_lhs (t),
4331 gimple_call_return_flags (t) | ERF_NOALIAS,
4332 vNULL, fndecl);
4333 get_constraint_for_ptr_offset (gimple_call_lhs (t),
4334 NULL_TREE, &lhsc);
4335 get_constraint_for_ptr_offset (gimple_call_arg (t, 0),
4336 NULL_TREE, &rhsc);
4337 do_deref (&lhsc);
4338 do_deref (&rhsc);
4339 process_all_all_constraints (lhsc, rhsc);
4340 lhsc.truncate (0);
4341 rhsc.truncate (0);
4342 /* For realloc the resulting pointer can be equal to the
4343 argument as well. But only doing this wouldn't be
4344 correct because with ptr == 0 realloc behaves like malloc. */
4345 if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_REALLOC)
4347 get_constraint_for (gimple_call_lhs (t), &lhsc);
4348 get_constraint_for (gimple_call_arg (t, 0), &rhsc);
4349 process_all_all_constraints (lhsc, rhsc);
4351 return true;
4353 break;
4354 /* String / character search functions return a pointer into the
4355 source string or NULL. */
4356 case BUILT_IN_INDEX:
4357 case BUILT_IN_STRCHR:
4358 case BUILT_IN_STRRCHR:
4359 case BUILT_IN_MEMCHR:
4360 case BUILT_IN_STRSTR:
4361 case BUILT_IN_STRPBRK:
4362 if (gimple_call_lhs (t))
4364 tree src = gimple_call_arg (t, 0);
4365 get_constraint_for_ptr_offset (src, NULL_TREE, &rhsc);
4366 constraint_expr nul;
4367 nul.var = nothing_id;
4368 nul.offset = 0;
4369 nul.type = ADDRESSOF;
4370 rhsc.safe_push (nul);
4371 get_constraint_for (gimple_call_lhs (t), &lhsc);
4372 process_all_all_constraints (lhsc, rhsc);
4374 return true;
4375 /* Trampolines are special - they set up passing the static
4376 frame. */
4377 case BUILT_IN_INIT_TRAMPOLINE:
4379 tree tramp = gimple_call_arg (t, 0);
4380 tree nfunc = gimple_call_arg (t, 1);
4381 tree frame = gimple_call_arg (t, 2);
4382 unsigned i;
4383 struct constraint_expr lhs, *rhsp;
4384 if (in_ipa_mode)
4386 varinfo_t nfi = NULL;
4387 gcc_assert (TREE_CODE (nfunc) == ADDR_EXPR);
4388 nfi = lookup_vi_for_tree (TREE_OPERAND (nfunc, 0));
4389 if (nfi)
4391 lhs = get_function_part_constraint (nfi, fi_static_chain);
4392 get_constraint_for (frame, &rhsc);
4393 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
4394 process_constraint (new_constraint (lhs, *rhsp));
4395 rhsc.truncate (0);
4397 /* Make the frame point to the function for
4398 the trampoline adjustment call. */
4399 get_constraint_for (tramp, &lhsc);
4400 do_deref (&lhsc);
4401 get_constraint_for (nfunc, &rhsc);
4402 process_all_all_constraints (lhsc, rhsc);
4404 return true;
4407 /* Else fallthru to generic handling which will let
4408 the frame escape. */
4409 break;
4411 case BUILT_IN_ADJUST_TRAMPOLINE:
4413 tree tramp = gimple_call_arg (t, 0);
4414 tree res = gimple_call_lhs (t);
4415 if (in_ipa_mode && res)
4417 get_constraint_for (res, &lhsc);
4418 get_constraint_for (tramp, &rhsc);
4419 do_deref (&rhsc);
4420 process_all_all_constraints (lhsc, rhsc);
4422 return true;
4424 CASE_BUILT_IN_TM_STORE (1):
4425 CASE_BUILT_IN_TM_STORE (2):
4426 CASE_BUILT_IN_TM_STORE (4):
4427 CASE_BUILT_IN_TM_STORE (8):
4428 CASE_BUILT_IN_TM_STORE (FLOAT):
4429 CASE_BUILT_IN_TM_STORE (DOUBLE):
4430 CASE_BUILT_IN_TM_STORE (LDOUBLE):
4431 CASE_BUILT_IN_TM_STORE (M64):
4432 CASE_BUILT_IN_TM_STORE (M128):
4433 CASE_BUILT_IN_TM_STORE (M256):
4435 tree addr = gimple_call_arg (t, 0);
4436 tree src = gimple_call_arg (t, 1);
4438 get_constraint_for (addr, &lhsc);
4439 do_deref (&lhsc);
4440 get_constraint_for (src, &rhsc);
4441 process_all_all_constraints (lhsc, rhsc);
4442 return true;
4444 CASE_BUILT_IN_TM_LOAD (1):
4445 CASE_BUILT_IN_TM_LOAD (2):
4446 CASE_BUILT_IN_TM_LOAD (4):
4447 CASE_BUILT_IN_TM_LOAD (8):
4448 CASE_BUILT_IN_TM_LOAD (FLOAT):
4449 CASE_BUILT_IN_TM_LOAD (DOUBLE):
4450 CASE_BUILT_IN_TM_LOAD (LDOUBLE):
4451 CASE_BUILT_IN_TM_LOAD (M64):
4452 CASE_BUILT_IN_TM_LOAD (M128):
4453 CASE_BUILT_IN_TM_LOAD (M256):
4455 tree dest = gimple_call_lhs (t);
4456 tree addr = gimple_call_arg (t, 0);
4458 get_constraint_for (dest, &lhsc);
4459 get_constraint_for (addr, &rhsc);
4460 do_deref (&rhsc);
4461 process_all_all_constraints (lhsc, rhsc);
4462 return true;
4464 /* Variadic argument handling needs to be handled in IPA
4465 mode as well. */
4466 case BUILT_IN_VA_START:
4468 tree valist = gimple_call_arg (t, 0);
4469 struct constraint_expr rhs, *lhsp;
4470 unsigned i;
4471 get_constraint_for (valist, &lhsc);
4472 do_deref (&lhsc);
4473 /* The va_list gets access to pointers in variadic
4474 arguments. Which we know in the case of IPA analysis
4475 and otherwise are just all nonlocal variables. */
4476 if (in_ipa_mode)
4478 fi = lookup_vi_for_tree (fn->decl);
4479 rhs = get_function_part_constraint (fi, ~0);
4480 rhs.type = ADDRESSOF;
4482 else
4484 rhs.var = nonlocal_id;
4485 rhs.type = ADDRESSOF;
4486 rhs.offset = 0;
4488 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
4489 process_constraint (new_constraint (*lhsp, rhs));
4490 /* va_list is clobbered. */
4491 make_constraint_to (get_call_clobber_vi (t)->id, valist);
4492 return true;
4494 /* va_end doesn't have any effect that matters. */
4495 case BUILT_IN_VA_END:
4496 return true;
4497 /* Alternate return. Simply give up for now. */
4498 case BUILT_IN_RETURN:
4500 fi = NULL;
4501 if (!in_ipa_mode
4502 || !(fi = get_vi_for_tree (fn->decl)))
4503 make_constraint_from (get_varinfo (escaped_id), anything_id);
4504 else if (in_ipa_mode
4505 && fi != NULL)
4507 struct constraint_expr lhs, rhs;
4508 lhs = get_function_part_constraint (fi, fi_result);
4509 rhs.var = anything_id;
4510 rhs.offset = 0;
4511 rhs.type = SCALAR;
4512 process_constraint (new_constraint (lhs, rhs));
4514 return true;
4516 /* printf-style functions may have hooks to set pointers to
4517 point to somewhere into the generated string. Leave them
4518 for a later exercise... */
4519 default:
4520 /* Fallthru to general call handling. */;
4523 return false;
4526 /* Create constraints for the call T. */
4528 static void
4529 find_func_aliases_for_call (struct function *fn, gcall *t)
4531 tree fndecl = gimple_call_fndecl (t);
4532 varinfo_t fi;
4534 if (fndecl != NULL_TREE
4535 && DECL_BUILT_IN (fndecl)
4536 && find_func_aliases_for_builtin_call (fn, t))
4537 return;
4539 fi = get_fi_for_callee (t);
4540 if (!in_ipa_mode
4541 || (fndecl && !fi->is_fn_info))
4543 auto_vec<ce_s, 16> rhsc;
4544 int flags = gimple_call_flags (t);
4546 /* Const functions can return their arguments and addresses
4547 of global memory but not of escaped memory. */
4548 if (flags & (ECF_CONST|ECF_NOVOPS))
4550 if (gimple_call_lhs (t))
4551 handle_const_call (t, &rhsc);
4553 /* Pure functions can return addresses in and of memory
4554 reachable from their arguments, but they are not an escape
4555 point for reachable memory of their arguments. */
4556 else if (flags & (ECF_PURE|ECF_LOOPING_CONST_OR_PURE))
4557 handle_pure_call (t, &rhsc);
4558 else
4559 handle_rhs_call (t, &rhsc);
4560 if (gimple_call_lhs (t))
4561 handle_lhs_call (t, gimple_call_lhs (t),
4562 gimple_call_return_flags (t), rhsc, fndecl);
4564 else
4566 auto_vec<ce_s, 2> rhsc;
4567 tree lhsop;
4568 unsigned j;
4570 /* Assign all the passed arguments to the appropriate incoming
4571 parameters of the function. */
4572 for (j = 0; j < gimple_call_num_args (t); j++)
4574 struct constraint_expr lhs ;
4575 struct constraint_expr *rhsp;
4576 tree arg = gimple_call_arg (t, j);
4578 get_constraint_for_rhs (arg, &rhsc);
4579 lhs = get_function_part_constraint (fi, fi_parm_base + j);
4580 while (rhsc.length () != 0)
4582 rhsp = &rhsc.last ();
4583 process_constraint (new_constraint (lhs, *rhsp));
4584 rhsc.pop ();
4588 /* If we are returning a value, assign it to the result. */
4589 lhsop = gimple_call_lhs (t);
4590 if (lhsop)
4592 auto_vec<ce_s, 2> lhsc;
4593 struct constraint_expr rhs;
4594 struct constraint_expr *lhsp;
4596 get_constraint_for (lhsop, &lhsc);
4597 rhs = get_function_part_constraint (fi, fi_result);
4598 if (fndecl
4599 && DECL_RESULT (fndecl)
4600 && DECL_BY_REFERENCE (DECL_RESULT (fndecl)))
4602 auto_vec<ce_s, 2> tem;
4603 tem.quick_push (rhs);
4604 do_deref (&tem);
4605 gcc_checking_assert (tem.length () == 1);
4606 rhs = tem[0];
4608 FOR_EACH_VEC_ELT (lhsc, j, lhsp)
4609 process_constraint (new_constraint (*lhsp, rhs));
4612 /* If we pass the result decl by reference, honor that. */
4613 if (lhsop
4614 && fndecl
4615 && DECL_RESULT (fndecl)
4616 && DECL_BY_REFERENCE (DECL_RESULT (fndecl)))
4618 struct constraint_expr lhs;
4619 struct constraint_expr *rhsp;
4621 get_constraint_for_address_of (lhsop, &rhsc);
4622 lhs = get_function_part_constraint (fi, fi_result);
4623 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
4624 process_constraint (new_constraint (lhs, *rhsp));
4625 rhsc.truncate (0);
4628 /* If we use a static chain, pass it along. */
4629 if (gimple_call_chain (t))
4631 struct constraint_expr lhs;
4632 struct constraint_expr *rhsp;
4634 get_constraint_for (gimple_call_chain (t), &rhsc);
4635 lhs = get_function_part_constraint (fi, fi_static_chain);
4636 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
4637 process_constraint (new_constraint (lhs, *rhsp));
4642 /* Walk statement T setting up aliasing constraints according to the
4643 references found in T. This function is the main part of the
4644 constraint builder. AI points to auxiliary alias information used
4645 when building alias sets and computing alias grouping heuristics. */
4647 static void
4648 find_func_aliases (struct function *fn, gimple origt)
4650 gimple t = origt;
4651 auto_vec<ce_s, 16> lhsc;
4652 auto_vec<ce_s, 16> rhsc;
4653 struct constraint_expr *c;
4654 varinfo_t fi;
4656 /* Now build constraints expressions. */
4657 if (gimple_code (t) == GIMPLE_PHI)
4659 size_t i;
4660 unsigned int j;
4662 /* For a phi node, assign all the arguments to
4663 the result. */
4664 get_constraint_for (gimple_phi_result (t), &lhsc);
4665 for (i = 0; i < gimple_phi_num_args (t); i++)
4667 tree strippedrhs = PHI_ARG_DEF (t, i);
4669 STRIP_NOPS (strippedrhs);
4670 get_constraint_for_rhs (gimple_phi_arg_def (t, i), &rhsc);
4672 FOR_EACH_VEC_ELT (lhsc, j, c)
4674 struct constraint_expr *c2;
4675 while (rhsc.length () > 0)
4677 c2 = &rhsc.last ();
4678 process_constraint (new_constraint (*c, *c2));
4679 rhsc.pop ();
4684 /* In IPA mode, we need to generate constraints to pass call
4685 arguments through their calls. There are two cases,
4686 either a GIMPLE_CALL returning a value, or just a plain
4687 GIMPLE_CALL when we are not.
4689 In non-ipa mode, we need to generate constraints for each
4690 pointer passed by address. */
4691 else if (is_gimple_call (t))
4692 find_func_aliases_for_call (fn, as_a <gcall *> (t));
4694 /* Otherwise, just a regular assignment statement. Only care about
4695 operations with pointer result, others are dealt with as escape
4696 points if they have pointer operands. */
4697 else if (is_gimple_assign (t))
4699 /* Otherwise, just a regular assignment statement. */
4700 tree lhsop = gimple_assign_lhs (t);
4701 tree rhsop = (gimple_num_ops (t) == 2) ? gimple_assign_rhs1 (t) : NULL;
4703 if (rhsop && TREE_CLOBBER_P (rhsop))
4704 /* Ignore clobbers, they don't actually store anything into
4705 the LHS. */
4707 else if (rhsop && AGGREGATE_TYPE_P (TREE_TYPE (lhsop)))
4708 do_structure_copy (lhsop, rhsop);
4709 else
4711 enum tree_code code = gimple_assign_rhs_code (t);
4713 get_constraint_for (lhsop, &lhsc);
4715 if (FLOAT_TYPE_P (TREE_TYPE (lhsop)))
4716 /* If the operation produces a floating point result then
4717 assume the value is not produced to transfer a pointer. */
4719 else if (code == POINTER_PLUS_EXPR)
4720 get_constraint_for_ptr_offset (gimple_assign_rhs1 (t),
4721 gimple_assign_rhs2 (t), &rhsc);
4722 else if (code == BIT_AND_EXPR
4723 && TREE_CODE (gimple_assign_rhs2 (t)) == INTEGER_CST)
4725 /* Aligning a pointer via a BIT_AND_EXPR is offsetting
4726 the pointer. Handle it by offsetting it by UNKNOWN. */
4727 get_constraint_for_ptr_offset (gimple_assign_rhs1 (t),
4728 NULL_TREE, &rhsc);
4730 else if ((CONVERT_EXPR_CODE_P (code)
4731 && !(POINTER_TYPE_P (gimple_expr_type (t))
4732 && !POINTER_TYPE_P (TREE_TYPE (rhsop))))
4733 || gimple_assign_single_p (t))
4734 get_constraint_for_rhs (rhsop, &rhsc);
4735 else if (code == COND_EXPR)
4737 /* The result is a merge of both COND_EXPR arms. */
4738 auto_vec<ce_s, 2> tmp;
4739 struct constraint_expr *rhsp;
4740 unsigned i;
4741 get_constraint_for_rhs (gimple_assign_rhs2 (t), &rhsc);
4742 get_constraint_for_rhs (gimple_assign_rhs3 (t), &tmp);
4743 FOR_EACH_VEC_ELT (tmp, i, rhsp)
4744 rhsc.safe_push (*rhsp);
4746 else if (truth_value_p (code))
4747 /* Truth value results are not pointer (parts). Or at least
4748 very very unreasonable obfuscation of a part. */
4750 else
4752 /* All other operations are merges. */
4753 auto_vec<ce_s, 4> tmp;
4754 struct constraint_expr *rhsp;
4755 unsigned i, j;
4756 get_constraint_for_rhs (gimple_assign_rhs1 (t), &rhsc);
4757 for (i = 2; i < gimple_num_ops (t); ++i)
4759 get_constraint_for_rhs (gimple_op (t, i), &tmp);
4760 FOR_EACH_VEC_ELT (tmp, j, rhsp)
4761 rhsc.safe_push (*rhsp);
4762 tmp.truncate (0);
4765 process_all_all_constraints (lhsc, rhsc);
4767 /* If there is a store to a global variable the rhs escapes. */
4768 if ((lhsop = get_base_address (lhsop)) != NULL_TREE
4769 && DECL_P (lhsop)
4770 && is_global_var (lhsop)
4771 && (!in_ipa_mode
4772 || DECL_EXTERNAL (lhsop) || TREE_PUBLIC (lhsop)))
4773 make_escape_constraint (rhsop);
4775 /* Handle escapes through return. */
4776 else if (gimple_code (t) == GIMPLE_RETURN
4777 && gimple_return_retval (as_a <greturn *> (t)) != NULL_TREE)
4779 greturn *return_stmt = as_a <greturn *> (t);
4780 fi = NULL;
4781 if (!in_ipa_mode
4782 || !(fi = get_vi_for_tree (fn->decl)))
4783 make_escape_constraint (gimple_return_retval (return_stmt));
4784 else if (in_ipa_mode
4785 && fi != NULL)
4787 struct constraint_expr lhs ;
4788 struct constraint_expr *rhsp;
4789 unsigned i;
4791 lhs = get_function_part_constraint (fi, fi_result);
4792 get_constraint_for_rhs (gimple_return_retval (return_stmt), &rhsc);
4793 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
4794 process_constraint (new_constraint (lhs, *rhsp));
4797 /* Handle asms conservatively by adding escape constraints to everything. */
4798 else if (gasm *asm_stmt = dyn_cast <gasm *> (t))
4800 unsigned i, noutputs;
4801 const char **oconstraints;
4802 const char *constraint;
4803 bool allows_mem, allows_reg, is_inout;
4805 noutputs = gimple_asm_noutputs (asm_stmt);
4806 oconstraints = XALLOCAVEC (const char *, noutputs);
4808 for (i = 0; i < noutputs; ++i)
4810 tree link = gimple_asm_output_op (asm_stmt, i);
4811 tree op = TREE_VALUE (link);
4813 constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
4814 oconstraints[i] = constraint;
4815 parse_output_constraint (&constraint, i, 0, 0, &allows_mem,
4816 &allows_reg, &is_inout);
4818 /* A memory constraint makes the address of the operand escape. */
4819 if (!allows_reg && allows_mem)
4820 make_escape_constraint (build_fold_addr_expr (op));
4822 /* The asm may read global memory, so outputs may point to
4823 any global memory. */
4824 if (op)
4826 auto_vec<ce_s, 2> lhsc;
4827 struct constraint_expr rhsc, *lhsp;
4828 unsigned j;
4829 get_constraint_for (op, &lhsc);
4830 rhsc.var = nonlocal_id;
4831 rhsc.offset = 0;
4832 rhsc.type = SCALAR;
4833 FOR_EACH_VEC_ELT (lhsc, j, lhsp)
4834 process_constraint (new_constraint (*lhsp, rhsc));
4837 for (i = 0; i < gimple_asm_ninputs (asm_stmt); ++i)
4839 tree link = gimple_asm_input_op (asm_stmt, i);
4840 tree op = TREE_VALUE (link);
4842 constraint = TREE_STRING_POINTER (TREE_VALUE (TREE_PURPOSE (link)));
4844 parse_input_constraint (&constraint, 0, 0, noutputs, 0, oconstraints,
4845 &allows_mem, &allows_reg);
4847 /* A memory constraint makes the address of the operand escape. */
4848 if (!allows_reg && allows_mem)
4849 make_escape_constraint (build_fold_addr_expr (op));
4850 /* Strictly we'd only need the constraint to ESCAPED if
4851 the asm clobbers memory, otherwise using something
4852 along the lines of per-call clobbers/uses would be enough. */
4853 else if (op)
4854 make_escape_constraint (op);
4860 /* Create a constraint adding to the clobber set of FI the memory
4861 pointed to by PTR. */
4863 static void
4864 process_ipa_clobber (varinfo_t fi, tree ptr)
4866 vec<ce_s> ptrc = vNULL;
4867 struct constraint_expr *c, lhs;
4868 unsigned i;
4869 get_constraint_for_rhs (ptr, &ptrc);
4870 lhs = get_function_part_constraint (fi, fi_clobbers);
4871 FOR_EACH_VEC_ELT (ptrc, i, c)
4872 process_constraint (new_constraint (lhs, *c));
4873 ptrc.release ();
4876 /* Walk statement T setting up clobber and use constraints according to the
4877 references found in T. This function is a main part of the
4878 IPA constraint builder. */
4880 static void
4881 find_func_clobbers (struct function *fn, gimple origt)
4883 gimple t = origt;
4884 auto_vec<ce_s, 16> lhsc;
4885 auto_vec<ce_s, 16> rhsc;
4886 varinfo_t fi;
4888 /* Add constraints for clobbered/used in IPA mode.
4889 We are not interested in what automatic variables are clobbered
4890 or used as we only use the information in the caller to which
4891 they do not escape. */
4892 gcc_assert (in_ipa_mode);
4894 /* If the stmt refers to memory in any way it better had a VUSE. */
4895 if (gimple_vuse (t) == NULL_TREE)
4896 return;
4898 /* We'd better have function information for the current function. */
4899 fi = lookup_vi_for_tree (fn->decl);
4900 gcc_assert (fi != NULL);
4902 /* Account for stores in assignments and calls. */
4903 if (gimple_vdef (t) != NULL_TREE
4904 && gimple_has_lhs (t))
4906 tree lhs = gimple_get_lhs (t);
4907 tree tem = lhs;
4908 while (handled_component_p (tem))
4909 tem = TREE_OPERAND (tem, 0);
4910 if ((DECL_P (tem)
4911 && !auto_var_in_fn_p (tem, fn->decl))
4912 || INDIRECT_REF_P (tem)
4913 || (TREE_CODE (tem) == MEM_REF
4914 && !(TREE_CODE (TREE_OPERAND (tem, 0)) == ADDR_EXPR
4915 && auto_var_in_fn_p
4916 (TREE_OPERAND (TREE_OPERAND (tem, 0), 0), fn->decl))))
4918 struct constraint_expr lhsc, *rhsp;
4919 unsigned i;
4920 lhsc = get_function_part_constraint (fi, fi_clobbers);
4921 get_constraint_for_address_of (lhs, &rhsc);
4922 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
4923 process_constraint (new_constraint (lhsc, *rhsp));
4924 rhsc.truncate (0);
4928 /* Account for uses in assigments and returns. */
4929 if (gimple_assign_single_p (t)
4930 || (gimple_code (t) == GIMPLE_RETURN
4931 && gimple_return_retval (as_a <greturn *> (t)) != NULL_TREE))
4933 tree rhs = (gimple_assign_single_p (t)
4934 ? gimple_assign_rhs1 (t)
4935 : gimple_return_retval (as_a <greturn *> (t)));
4936 tree tem = rhs;
4937 while (handled_component_p (tem))
4938 tem = TREE_OPERAND (tem, 0);
4939 if ((DECL_P (tem)
4940 && !auto_var_in_fn_p (tem, fn->decl))
4941 || INDIRECT_REF_P (tem)
4942 || (TREE_CODE (tem) == MEM_REF
4943 && !(TREE_CODE (TREE_OPERAND (tem, 0)) == ADDR_EXPR
4944 && auto_var_in_fn_p
4945 (TREE_OPERAND (TREE_OPERAND (tem, 0), 0), fn->decl))))
4947 struct constraint_expr lhs, *rhsp;
4948 unsigned i;
4949 lhs = get_function_part_constraint (fi, fi_uses);
4950 get_constraint_for_address_of (rhs, &rhsc);
4951 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
4952 process_constraint (new_constraint (lhs, *rhsp));
4953 rhsc.truncate (0);
4957 if (gcall *call_stmt = dyn_cast <gcall *> (t))
4959 varinfo_t cfi = NULL;
4960 tree decl = gimple_call_fndecl (t);
4961 struct constraint_expr lhs, rhs;
4962 unsigned i, j;
4964 /* For builtins we do not have separate function info. For those
4965 we do not generate escapes for we have to generate clobbers/uses. */
4966 if (gimple_call_builtin_p (t, BUILT_IN_NORMAL))
4967 switch (DECL_FUNCTION_CODE (decl))
4969 /* The following functions use and clobber memory pointed to
4970 by their arguments. */
4971 case BUILT_IN_STRCPY:
4972 case BUILT_IN_STRNCPY:
4973 case BUILT_IN_BCOPY:
4974 case BUILT_IN_MEMCPY:
4975 case BUILT_IN_MEMMOVE:
4976 case BUILT_IN_MEMPCPY:
4977 case BUILT_IN_STPCPY:
4978 case BUILT_IN_STPNCPY:
4979 case BUILT_IN_STRCAT:
4980 case BUILT_IN_STRNCAT:
4981 case BUILT_IN_STRCPY_CHK:
4982 case BUILT_IN_STRNCPY_CHK:
4983 case BUILT_IN_MEMCPY_CHK:
4984 case BUILT_IN_MEMMOVE_CHK:
4985 case BUILT_IN_MEMPCPY_CHK:
4986 case BUILT_IN_STPCPY_CHK:
4987 case BUILT_IN_STPNCPY_CHK:
4988 case BUILT_IN_STRCAT_CHK:
4989 case BUILT_IN_STRNCAT_CHK:
4991 tree dest = gimple_call_arg (t, (DECL_FUNCTION_CODE (decl)
4992 == BUILT_IN_BCOPY ? 1 : 0));
4993 tree src = gimple_call_arg (t, (DECL_FUNCTION_CODE (decl)
4994 == BUILT_IN_BCOPY ? 0 : 1));
4995 unsigned i;
4996 struct constraint_expr *rhsp, *lhsp;
4997 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
4998 lhs = get_function_part_constraint (fi, fi_clobbers);
4999 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
5000 process_constraint (new_constraint (lhs, *lhsp));
5001 get_constraint_for_ptr_offset (src, NULL_TREE, &rhsc);
5002 lhs = get_function_part_constraint (fi, fi_uses);
5003 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
5004 process_constraint (new_constraint (lhs, *rhsp));
5005 return;
5007 /* The following function clobbers memory pointed to by
5008 its argument. */
5009 case BUILT_IN_MEMSET:
5010 case BUILT_IN_MEMSET_CHK:
5011 case BUILT_IN_POSIX_MEMALIGN:
5013 tree dest = gimple_call_arg (t, 0);
5014 unsigned i;
5015 ce_s *lhsp;
5016 get_constraint_for_ptr_offset (dest, NULL_TREE, &lhsc);
5017 lhs = get_function_part_constraint (fi, fi_clobbers);
5018 FOR_EACH_VEC_ELT (lhsc, i, lhsp)
5019 process_constraint (new_constraint (lhs, *lhsp));
5020 return;
5022 /* The following functions clobber their second and third
5023 arguments. */
5024 case BUILT_IN_SINCOS:
5025 case BUILT_IN_SINCOSF:
5026 case BUILT_IN_SINCOSL:
5028 process_ipa_clobber (fi, gimple_call_arg (t, 1));
5029 process_ipa_clobber (fi, gimple_call_arg (t, 2));
5030 return;
5032 /* The following functions clobber their second argument. */
5033 case BUILT_IN_FREXP:
5034 case BUILT_IN_FREXPF:
5035 case BUILT_IN_FREXPL:
5036 case BUILT_IN_LGAMMA_R:
5037 case BUILT_IN_LGAMMAF_R:
5038 case BUILT_IN_LGAMMAL_R:
5039 case BUILT_IN_GAMMA_R:
5040 case BUILT_IN_GAMMAF_R:
5041 case BUILT_IN_GAMMAL_R:
5042 case BUILT_IN_MODF:
5043 case BUILT_IN_MODFF:
5044 case BUILT_IN_MODFL:
5046 process_ipa_clobber (fi, gimple_call_arg (t, 1));
5047 return;
5049 /* The following functions clobber their third argument. */
5050 case BUILT_IN_REMQUO:
5051 case BUILT_IN_REMQUOF:
5052 case BUILT_IN_REMQUOL:
5054 process_ipa_clobber (fi, gimple_call_arg (t, 2));
5055 return;
5057 /* The following functions neither read nor clobber memory. */
5058 case BUILT_IN_ASSUME_ALIGNED:
5059 case BUILT_IN_FREE:
5060 return;
5061 /* Trampolines are of no interest to us. */
5062 case BUILT_IN_INIT_TRAMPOLINE:
5063 case BUILT_IN_ADJUST_TRAMPOLINE:
5064 return;
5065 case BUILT_IN_VA_START:
5066 case BUILT_IN_VA_END:
5067 return;
5068 /* printf-style functions may have hooks to set pointers to
5069 point to somewhere into the generated string. Leave them
5070 for a later exercise... */
5071 default:
5072 /* Fallthru to general call handling. */;
5075 /* Parameters passed by value are used. */
5076 lhs = get_function_part_constraint (fi, fi_uses);
5077 for (i = 0; i < gimple_call_num_args (t); i++)
5079 struct constraint_expr *rhsp;
5080 tree arg = gimple_call_arg (t, i);
5082 if (TREE_CODE (arg) == SSA_NAME
5083 || is_gimple_min_invariant (arg))
5084 continue;
5086 get_constraint_for_address_of (arg, &rhsc);
5087 FOR_EACH_VEC_ELT (rhsc, j, rhsp)
5088 process_constraint (new_constraint (lhs, *rhsp));
5089 rhsc.truncate (0);
5092 /* Build constraints for propagating clobbers/uses along the
5093 callgraph edges. */
5094 cfi = get_fi_for_callee (call_stmt);
5095 if (cfi->id == anything_id)
5097 if (gimple_vdef (t))
5098 make_constraint_from (first_vi_for_offset (fi, fi_clobbers),
5099 anything_id);
5100 make_constraint_from (first_vi_for_offset (fi, fi_uses),
5101 anything_id);
5102 return;
5105 /* For callees without function info (that's external functions),
5106 ESCAPED is clobbered and used. */
5107 if (gimple_call_fndecl (t)
5108 && !cfi->is_fn_info)
5110 varinfo_t vi;
5112 if (gimple_vdef (t))
5113 make_copy_constraint (first_vi_for_offset (fi, fi_clobbers),
5114 escaped_id);
5115 make_copy_constraint (first_vi_for_offset (fi, fi_uses), escaped_id);
5117 /* Also honor the call statement use/clobber info. */
5118 if ((vi = lookup_call_clobber_vi (call_stmt)) != NULL)
5119 make_copy_constraint (first_vi_for_offset (fi, fi_clobbers),
5120 vi->id);
5121 if ((vi = lookup_call_use_vi (call_stmt)) != NULL)
5122 make_copy_constraint (first_vi_for_offset (fi, fi_uses),
5123 vi->id);
5124 return;
5127 /* Otherwise the caller clobbers and uses what the callee does.
5128 ??? This should use a new complex constraint that filters
5129 local variables of the callee. */
5130 if (gimple_vdef (t))
5132 lhs = get_function_part_constraint (fi, fi_clobbers);
5133 rhs = get_function_part_constraint (cfi, fi_clobbers);
5134 process_constraint (new_constraint (lhs, rhs));
5136 lhs = get_function_part_constraint (fi, fi_uses);
5137 rhs = get_function_part_constraint (cfi, fi_uses);
5138 process_constraint (new_constraint (lhs, rhs));
5140 else if (gimple_code (t) == GIMPLE_ASM)
5142 /* ??? Ick. We can do better. */
5143 if (gimple_vdef (t))
5144 make_constraint_from (first_vi_for_offset (fi, fi_clobbers),
5145 anything_id);
5146 make_constraint_from (first_vi_for_offset (fi, fi_uses),
5147 anything_id);
5152 /* Find the first varinfo in the same variable as START that overlaps with
5153 OFFSET. Return NULL if we can't find one. */
5155 static varinfo_t
5156 first_vi_for_offset (varinfo_t start, unsigned HOST_WIDE_INT offset)
5158 /* If the offset is outside of the variable, bail out. */
5159 if (offset >= start->fullsize)
5160 return NULL;
5162 /* If we cannot reach offset from start, lookup the first field
5163 and start from there. */
5164 if (start->offset > offset)
5165 start = get_varinfo (start->head);
5167 while (start)
5169 /* We may not find a variable in the field list with the actual
5170 offset when when we have glommed a structure to a variable.
5171 In that case, however, offset should still be within the size
5172 of the variable. */
5173 if (offset >= start->offset
5174 && (offset - start->offset) < start->size)
5175 return start;
5177 start = vi_next (start);
5180 return NULL;
5183 /* Find the first varinfo in the same variable as START that overlaps with
5184 OFFSET. If there is no such varinfo the varinfo directly preceding
5185 OFFSET is returned. */
5187 static varinfo_t
5188 first_or_preceding_vi_for_offset (varinfo_t start,
5189 unsigned HOST_WIDE_INT offset)
5191 /* If we cannot reach offset from start, lookup the first field
5192 and start from there. */
5193 if (start->offset > offset)
5194 start = get_varinfo (start->head);
5196 /* We may not find a variable in the field list with the actual
5197 offset when when we have glommed a structure to a variable.
5198 In that case, however, offset should still be within the size
5199 of the variable.
5200 If we got beyond the offset we look for return the field
5201 directly preceding offset which may be the last field. */
5202 while (start->next
5203 && offset >= start->offset
5204 && !((offset - start->offset) < start->size))
5205 start = vi_next (start);
5207 return start;
5211 /* This structure is used during pushing fields onto the fieldstack
5212 to track the offset of the field, since bitpos_of_field gives it
5213 relative to its immediate containing type, and we want it relative
5214 to the ultimate containing object. */
5216 struct fieldoff
5218 /* Offset from the base of the base containing object to this field. */
5219 HOST_WIDE_INT offset;
5221 /* Size, in bits, of the field. */
5222 unsigned HOST_WIDE_INT size;
5224 unsigned has_unknown_size : 1;
5226 unsigned must_have_pointers : 1;
5228 unsigned may_have_pointers : 1;
5230 unsigned only_restrict_pointers : 1;
5232 typedef struct fieldoff fieldoff_s;
5235 /* qsort comparison function for two fieldoff's PA and PB */
5237 static int
5238 fieldoff_compare (const void *pa, const void *pb)
5240 const fieldoff_s *foa = (const fieldoff_s *)pa;
5241 const fieldoff_s *fob = (const fieldoff_s *)pb;
5242 unsigned HOST_WIDE_INT foasize, fobsize;
5244 if (foa->offset < fob->offset)
5245 return -1;
5246 else if (foa->offset > fob->offset)
5247 return 1;
5249 foasize = foa->size;
5250 fobsize = fob->size;
5251 if (foasize < fobsize)
5252 return -1;
5253 else if (foasize > fobsize)
5254 return 1;
5255 return 0;
5258 /* Sort a fieldstack according to the field offset and sizes. */
5259 static void
5260 sort_fieldstack (vec<fieldoff_s> fieldstack)
5262 fieldstack.qsort (fieldoff_compare);
5265 /* Return true if T is a type that can have subvars. */
5267 static inline bool
5268 type_can_have_subvars (const_tree t)
5270 /* Aggregates without overlapping fields can have subvars. */
5271 return TREE_CODE (t) == RECORD_TYPE;
5274 /* Return true if V is a tree that we can have subvars for.
5275 Normally, this is any aggregate type. Also complex
5276 types which are not gimple registers can have subvars. */
5278 static inline bool
5279 var_can_have_subvars (const_tree v)
5281 /* Volatile variables should never have subvars. */
5282 if (TREE_THIS_VOLATILE (v))
5283 return false;
5285 /* Non decls or memory tags can never have subvars. */
5286 if (!DECL_P (v))
5287 return false;
5289 return type_can_have_subvars (TREE_TYPE (v));
5292 /* Return true if T is a type that does contain pointers. */
5294 static bool
5295 type_must_have_pointers (tree type)
5297 if (POINTER_TYPE_P (type))
5298 return true;
5300 if (TREE_CODE (type) == ARRAY_TYPE)
5301 return type_must_have_pointers (TREE_TYPE (type));
5303 /* A function or method can have pointers as arguments, so track
5304 those separately. */
5305 if (TREE_CODE (type) == FUNCTION_TYPE
5306 || TREE_CODE (type) == METHOD_TYPE)
5307 return true;
5309 return false;
5312 static bool
5313 field_must_have_pointers (tree t)
5315 return type_must_have_pointers (TREE_TYPE (t));
5318 /* Given a TYPE, and a vector of field offsets FIELDSTACK, push all
5319 the fields of TYPE onto fieldstack, recording their offsets along
5320 the way.
5322 OFFSET is used to keep track of the offset in this entire
5323 structure, rather than just the immediately containing structure.
5324 Returns false if the caller is supposed to handle the field we
5325 recursed for. */
5327 static bool
5328 push_fields_onto_fieldstack (tree type, vec<fieldoff_s> *fieldstack,
5329 HOST_WIDE_INT offset)
5331 tree field;
5332 bool empty_p = true;
5334 if (TREE_CODE (type) != RECORD_TYPE)
5335 return false;
5337 /* If the vector of fields is growing too big, bail out early.
5338 Callers check for vec::length <= MAX_FIELDS_FOR_FIELD_SENSITIVE, make
5339 sure this fails. */
5340 if (fieldstack->length () > MAX_FIELDS_FOR_FIELD_SENSITIVE)
5341 return false;
5343 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
5344 if (TREE_CODE (field) == FIELD_DECL)
5346 bool push = false;
5347 HOST_WIDE_INT foff = bitpos_of_field (field);
5349 if (!var_can_have_subvars (field)
5350 || TREE_CODE (TREE_TYPE (field)) == QUAL_UNION_TYPE
5351 || TREE_CODE (TREE_TYPE (field)) == UNION_TYPE)
5352 push = true;
5353 else if (!push_fields_onto_fieldstack
5354 (TREE_TYPE (field), fieldstack, offset + foff)
5355 && (DECL_SIZE (field)
5356 && !integer_zerop (DECL_SIZE (field))))
5357 /* Empty structures may have actual size, like in C++. So
5358 see if we didn't push any subfields and the size is
5359 nonzero, push the field onto the stack. */
5360 push = true;
5362 if (push)
5364 fieldoff_s *pair = NULL;
5365 bool has_unknown_size = false;
5366 bool must_have_pointers_p;
5368 if (!fieldstack->is_empty ())
5369 pair = &fieldstack->last ();
5371 /* If there isn't anything at offset zero, create sth. */
5372 if (!pair
5373 && offset + foff != 0)
5375 fieldoff_s e = {0, offset + foff, false, false, false, false};
5376 pair = fieldstack->safe_push (e);
5379 if (!DECL_SIZE (field)
5380 || !tree_fits_uhwi_p (DECL_SIZE (field)))
5381 has_unknown_size = true;
5383 /* If adjacent fields do not contain pointers merge them. */
5384 must_have_pointers_p = field_must_have_pointers (field);
5385 if (pair
5386 && !has_unknown_size
5387 && !must_have_pointers_p
5388 && !pair->must_have_pointers
5389 && !pair->has_unknown_size
5390 && pair->offset + (HOST_WIDE_INT)pair->size == offset + foff)
5392 pair->size += tree_to_uhwi (DECL_SIZE (field));
5394 else
5396 fieldoff_s e;
5397 e.offset = offset + foff;
5398 e.has_unknown_size = has_unknown_size;
5399 if (!has_unknown_size)
5400 e.size = tree_to_uhwi (DECL_SIZE (field));
5401 else
5402 e.size = -1;
5403 e.must_have_pointers = must_have_pointers_p;
5404 e.may_have_pointers = true;
5405 e.only_restrict_pointers
5406 = (!has_unknown_size
5407 && POINTER_TYPE_P (TREE_TYPE (field))
5408 && TYPE_RESTRICT (TREE_TYPE (field)));
5409 fieldstack->safe_push (e);
5413 empty_p = false;
5416 return !empty_p;
5419 /* Count the number of arguments DECL has, and set IS_VARARGS to true
5420 if it is a varargs function. */
5422 static unsigned int
5423 count_num_arguments (tree decl, bool *is_varargs)
5425 unsigned int num = 0;
5426 tree t;
5428 /* Capture named arguments for K&R functions. They do not
5429 have a prototype and thus no TYPE_ARG_TYPES. */
5430 for (t = DECL_ARGUMENTS (decl); t; t = DECL_CHAIN (t))
5431 ++num;
5433 /* Check if the function has variadic arguments. */
5434 for (t = TYPE_ARG_TYPES (TREE_TYPE (decl)); t; t = TREE_CHAIN (t))
5435 if (TREE_VALUE (t) == void_type_node)
5436 break;
5437 if (!t)
5438 *is_varargs = true;
5440 return num;
5443 /* Creation function node for DECL, using NAME, and return the index
5444 of the variable we've created for the function. */
5446 static varinfo_t
5447 create_function_info_for (tree decl, const char *name)
5449 struct function *fn = DECL_STRUCT_FUNCTION (decl);
5450 varinfo_t vi, prev_vi;
5451 tree arg;
5452 unsigned int i;
5453 bool is_varargs = false;
5454 unsigned int num_args = count_num_arguments (decl, &is_varargs);
5456 /* Create the variable info. */
5458 vi = new_var_info (decl, name);
5459 vi->offset = 0;
5460 vi->size = 1;
5461 vi->fullsize = fi_parm_base + num_args;
5462 vi->is_fn_info = 1;
5463 vi->may_have_pointers = false;
5464 if (is_varargs)
5465 vi->fullsize = ~0;
5466 insert_vi_for_tree (vi->decl, vi);
5468 prev_vi = vi;
5470 /* Create a variable for things the function clobbers and one for
5471 things the function uses. */
5473 varinfo_t clobbervi, usevi;
5474 const char *newname;
5475 char *tempname;
5477 tempname = xasprintf ("%s.clobber", name);
5478 newname = ggc_strdup (tempname);
5479 free (tempname);
5481 clobbervi = new_var_info (NULL, newname);
5482 clobbervi->offset = fi_clobbers;
5483 clobbervi->size = 1;
5484 clobbervi->fullsize = vi->fullsize;
5485 clobbervi->is_full_var = true;
5486 clobbervi->is_global_var = false;
5487 gcc_assert (prev_vi->offset < clobbervi->offset);
5488 prev_vi->next = clobbervi->id;
5489 prev_vi = clobbervi;
5491 tempname = xasprintf ("%s.use", name);
5492 newname = ggc_strdup (tempname);
5493 free (tempname);
5495 usevi = new_var_info (NULL, newname);
5496 usevi->offset = fi_uses;
5497 usevi->size = 1;
5498 usevi->fullsize = vi->fullsize;
5499 usevi->is_full_var = true;
5500 usevi->is_global_var = false;
5501 gcc_assert (prev_vi->offset < usevi->offset);
5502 prev_vi->next = usevi->id;
5503 prev_vi = usevi;
5506 /* And one for the static chain. */
5507 if (fn->static_chain_decl != NULL_TREE)
5509 varinfo_t chainvi;
5510 const char *newname;
5511 char *tempname;
5513 tempname = xasprintf ("%s.chain", name);
5514 newname = ggc_strdup (tempname);
5515 free (tempname);
5517 chainvi = new_var_info (fn->static_chain_decl, newname);
5518 chainvi->offset = fi_static_chain;
5519 chainvi->size = 1;
5520 chainvi->fullsize = vi->fullsize;
5521 chainvi->is_full_var = true;
5522 chainvi->is_global_var = false;
5523 gcc_assert (prev_vi->offset < chainvi->offset);
5524 prev_vi->next = chainvi->id;
5525 prev_vi = chainvi;
5526 insert_vi_for_tree (fn->static_chain_decl, chainvi);
5529 /* Create a variable for the return var. */
5530 if (DECL_RESULT (decl) != NULL
5531 || !VOID_TYPE_P (TREE_TYPE (TREE_TYPE (decl))))
5533 varinfo_t resultvi;
5534 const char *newname;
5535 char *tempname;
5536 tree resultdecl = decl;
5538 if (DECL_RESULT (decl))
5539 resultdecl = DECL_RESULT (decl);
5541 tempname = xasprintf ("%s.result", name);
5542 newname = ggc_strdup (tempname);
5543 free (tempname);
5545 resultvi = new_var_info (resultdecl, newname);
5546 resultvi->offset = fi_result;
5547 resultvi->size = 1;
5548 resultvi->fullsize = vi->fullsize;
5549 resultvi->is_full_var = true;
5550 if (DECL_RESULT (decl))
5551 resultvi->may_have_pointers = true;
5552 gcc_assert (prev_vi->offset < resultvi->offset);
5553 prev_vi->next = resultvi->id;
5554 prev_vi = resultvi;
5555 if (DECL_RESULT (decl))
5556 insert_vi_for_tree (DECL_RESULT (decl), resultvi);
5559 /* Set up variables for each argument. */
5560 arg = DECL_ARGUMENTS (decl);
5561 for (i = 0; i < num_args; i++)
5563 varinfo_t argvi;
5564 const char *newname;
5565 char *tempname;
5566 tree argdecl = decl;
5568 if (arg)
5569 argdecl = arg;
5571 tempname = xasprintf ("%s.arg%d", name, i);
5572 newname = ggc_strdup (tempname);
5573 free (tempname);
5575 argvi = new_var_info (argdecl, newname);
5576 argvi->offset = fi_parm_base + i;
5577 argvi->size = 1;
5578 argvi->is_full_var = true;
5579 argvi->fullsize = vi->fullsize;
5580 if (arg)
5581 argvi->may_have_pointers = true;
5582 gcc_assert (prev_vi->offset < argvi->offset);
5583 prev_vi->next = argvi->id;
5584 prev_vi = argvi;
5585 if (arg)
5587 insert_vi_for_tree (arg, argvi);
5588 arg = DECL_CHAIN (arg);
5592 /* Add one representative for all further args. */
5593 if (is_varargs)
5595 varinfo_t argvi;
5596 const char *newname;
5597 char *tempname;
5598 tree decl;
5600 tempname = xasprintf ("%s.varargs", name);
5601 newname = ggc_strdup (tempname);
5602 free (tempname);
5604 /* We need sth that can be pointed to for va_start. */
5605 decl = build_fake_var_decl (ptr_type_node);
5607 argvi = new_var_info (decl, newname);
5608 argvi->offset = fi_parm_base + num_args;
5609 argvi->size = ~0;
5610 argvi->is_full_var = true;
5611 argvi->is_heap_var = true;
5612 argvi->fullsize = vi->fullsize;
5613 gcc_assert (prev_vi->offset < argvi->offset);
5614 prev_vi->next = argvi->id;
5615 prev_vi = argvi;
5618 return vi;
5622 /* Return true if FIELDSTACK contains fields that overlap.
5623 FIELDSTACK is assumed to be sorted by offset. */
5625 static bool
5626 check_for_overlaps (vec<fieldoff_s> fieldstack)
5628 fieldoff_s *fo = NULL;
5629 unsigned int i;
5630 HOST_WIDE_INT lastoffset = -1;
5632 FOR_EACH_VEC_ELT (fieldstack, i, fo)
5634 if (fo->offset == lastoffset)
5635 return true;
5636 lastoffset = fo->offset;
5638 return false;
5641 /* Create a varinfo structure for NAME and DECL, and add it to VARMAP.
5642 This will also create any varinfo structures necessary for fields
5643 of DECL. */
5645 static varinfo_t
5646 create_variable_info_for_1 (tree decl, const char *name)
5648 varinfo_t vi, newvi;
5649 tree decl_type = TREE_TYPE (decl);
5650 tree declsize = DECL_P (decl) ? DECL_SIZE (decl) : TYPE_SIZE (decl_type);
5651 auto_vec<fieldoff_s> fieldstack;
5652 fieldoff_s *fo;
5653 unsigned int i;
5654 varpool_node *vnode;
5656 if (!declsize
5657 || !tree_fits_uhwi_p (declsize))
5659 vi = new_var_info (decl, name);
5660 vi->offset = 0;
5661 vi->size = ~0;
5662 vi->fullsize = ~0;
5663 vi->is_unknown_size_var = true;
5664 vi->is_full_var = true;
5665 vi->may_have_pointers = true;
5666 return vi;
5669 /* Collect field information. */
5670 if (use_field_sensitive
5671 && var_can_have_subvars (decl)
5672 /* ??? Force us to not use subfields for global initializers
5673 in IPA mode. Else we'd have to parse arbitrary initializers. */
5674 && !(in_ipa_mode
5675 && is_global_var (decl)
5676 && (vnode = varpool_node::get (decl))
5677 && vnode->get_constructor ()))
5679 fieldoff_s *fo = NULL;
5680 bool notokay = false;
5681 unsigned int i;
5683 push_fields_onto_fieldstack (decl_type, &fieldstack, 0);
5685 for (i = 0; !notokay && fieldstack.iterate (i, &fo); i++)
5686 if (fo->has_unknown_size
5687 || fo->offset < 0)
5689 notokay = true;
5690 break;
5693 /* We can't sort them if we have a field with a variable sized type,
5694 which will make notokay = true. In that case, we are going to return
5695 without creating varinfos for the fields anyway, so sorting them is a
5696 waste to boot. */
5697 if (!notokay)
5699 sort_fieldstack (fieldstack);
5700 /* Due to some C++ FE issues, like PR 22488, we might end up
5701 what appear to be overlapping fields even though they,
5702 in reality, do not overlap. Until the C++ FE is fixed,
5703 we will simply disable field-sensitivity for these cases. */
5704 notokay = check_for_overlaps (fieldstack);
5707 if (notokay)
5708 fieldstack.release ();
5711 /* If we didn't end up collecting sub-variables create a full
5712 variable for the decl. */
5713 if (fieldstack.length () <= 1
5714 || fieldstack.length () > MAX_FIELDS_FOR_FIELD_SENSITIVE)
5716 vi = new_var_info (decl, name);
5717 vi->offset = 0;
5718 vi->may_have_pointers = true;
5719 vi->fullsize = tree_to_uhwi (declsize);
5720 vi->size = vi->fullsize;
5721 vi->is_full_var = true;
5722 fieldstack.release ();
5723 return vi;
5726 vi = new_var_info (decl, name);
5727 vi->fullsize = tree_to_uhwi (declsize);
5728 for (i = 0, newvi = vi;
5729 fieldstack.iterate (i, &fo);
5730 ++i, newvi = vi_next (newvi))
5732 const char *newname = "NULL";
5733 char *tempname;
5735 if (dump_file)
5737 tempname
5738 = xasprintf ("%s." HOST_WIDE_INT_PRINT_DEC
5739 "+" HOST_WIDE_INT_PRINT_DEC, name,
5740 fo->offset, fo->size);
5741 newname = ggc_strdup (tempname);
5742 free (tempname);
5744 newvi->name = newname;
5745 newvi->offset = fo->offset;
5746 newvi->size = fo->size;
5747 newvi->fullsize = vi->fullsize;
5748 newvi->may_have_pointers = fo->may_have_pointers;
5749 newvi->only_restrict_pointers = fo->only_restrict_pointers;
5750 if (i + 1 < fieldstack.length ())
5752 varinfo_t tem = new_var_info (decl, name);
5753 newvi->next = tem->id;
5754 tem->head = vi->id;
5758 return vi;
5761 static unsigned int
5762 create_variable_info_for (tree decl, const char *name)
5764 varinfo_t vi = create_variable_info_for_1 (decl, name);
5765 unsigned int id = vi->id;
5767 insert_vi_for_tree (decl, vi);
5769 if (TREE_CODE (decl) != VAR_DECL)
5770 return id;
5772 /* Create initial constraints for globals. */
5773 for (; vi; vi = vi_next (vi))
5775 if (!vi->may_have_pointers
5776 || !vi->is_global_var)
5777 continue;
5779 /* Mark global restrict qualified pointers. */
5780 if ((POINTER_TYPE_P (TREE_TYPE (decl))
5781 && TYPE_RESTRICT (TREE_TYPE (decl)))
5782 || vi->only_restrict_pointers)
5784 varinfo_t rvi
5785 = make_constraint_from_global_restrict (vi, "GLOBAL_RESTRICT");
5786 /* ??? For now exclude reads from globals as restrict sources
5787 if those are not (indirectly) from incoming parameters. */
5788 rvi->is_restrict_var = false;
5789 continue;
5792 /* In non-IPA mode the initializer from nonlocal is all we need. */
5793 if (!in_ipa_mode
5794 || DECL_HARD_REGISTER (decl))
5795 make_copy_constraint (vi, nonlocal_id);
5797 /* In IPA mode parse the initializer and generate proper constraints
5798 for it. */
5799 else
5801 varpool_node *vnode = varpool_node::get (decl);
5803 /* For escaped variables initialize them from nonlocal. */
5804 if (!vnode->all_refs_explicit_p ())
5805 make_copy_constraint (vi, nonlocal_id);
5807 /* If this is a global variable with an initializer and we are in
5808 IPA mode generate constraints for it. */
5809 if (vnode->get_constructor ()
5810 && vnode->definition)
5812 auto_vec<ce_s> rhsc;
5813 struct constraint_expr lhs, *rhsp;
5814 unsigned i;
5815 get_constraint_for_rhs (vnode->get_constructor (), &rhsc);
5816 lhs.var = vi->id;
5817 lhs.offset = 0;
5818 lhs.type = SCALAR;
5819 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
5820 process_constraint (new_constraint (lhs, *rhsp));
5821 /* If this is a variable that escapes from the unit
5822 the initializer escapes as well. */
5823 if (!vnode->all_refs_explicit_p ())
5825 lhs.var = escaped_id;
5826 lhs.offset = 0;
5827 lhs.type = SCALAR;
5828 FOR_EACH_VEC_ELT (rhsc, i, rhsp)
5829 process_constraint (new_constraint (lhs, *rhsp));
5835 return id;
5838 /* Print out the points-to solution for VAR to FILE. */
5840 static void
5841 dump_solution_for_var (FILE *file, unsigned int var)
5843 varinfo_t vi = get_varinfo (var);
5844 unsigned int i;
5845 bitmap_iterator bi;
5847 /* Dump the solution for unified vars anyway, this avoids difficulties
5848 in scanning dumps in the testsuite. */
5849 fprintf (file, "%s = { ", vi->name);
5850 vi = get_varinfo (find (var));
5851 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
5852 fprintf (file, "%s ", get_varinfo (i)->name);
5853 fprintf (file, "}");
5855 /* But note when the variable was unified. */
5856 if (vi->id != var)
5857 fprintf (file, " same as %s", vi->name);
5859 fprintf (file, "\n");
5862 /* Print the points-to solution for VAR to stderr. */
5864 DEBUG_FUNCTION void
5865 debug_solution_for_var (unsigned int var)
5867 dump_solution_for_var (stderr, var);
5870 /* Create varinfo structures for all of the variables in the
5871 function for intraprocedural mode. */
5873 static void
5874 intra_create_variable_infos (struct function *fn)
5876 tree t;
5878 /* For each incoming pointer argument arg, create the constraint ARG
5879 = NONLOCAL or a dummy variable if it is a restrict qualified
5880 passed-by-reference argument. */
5881 for (t = DECL_ARGUMENTS (fn->decl); t; t = DECL_CHAIN (t))
5883 varinfo_t p = get_vi_for_tree (t);
5885 /* For restrict qualified pointers to objects passed by
5886 reference build a real representative for the pointed-to object.
5887 Treat restrict qualified references the same. */
5888 if (TYPE_RESTRICT (TREE_TYPE (t))
5889 && ((DECL_BY_REFERENCE (t) && POINTER_TYPE_P (TREE_TYPE (t)))
5890 || TREE_CODE (TREE_TYPE (t)) == REFERENCE_TYPE)
5891 && !type_contains_placeholder_p (TREE_TYPE (TREE_TYPE (t))))
5893 struct constraint_expr lhsc, rhsc;
5894 varinfo_t vi;
5895 tree heapvar = build_fake_var_decl (TREE_TYPE (TREE_TYPE (t)));
5896 DECL_EXTERNAL (heapvar) = 1;
5897 vi = create_variable_info_for_1 (heapvar, "PARM_NOALIAS");
5898 vi->is_restrict_var = 1;
5899 insert_vi_for_tree (heapvar, vi);
5900 lhsc.var = p->id;
5901 lhsc.type = SCALAR;
5902 lhsc.offset = 0;
5903 rhsc.var = vi->id;
5904 rhsc.type = ADDRESSOF;
5905 rhsc.offset = 0;
5906 process_constraint (new_constraint (lhsc, rhsc));
5907 for (; vi; vi = vi_next (vi))
5908 if (vi->may_have_pointers)
5910 if (vi->only_restrict_pointers)
5911 make_constraint_from_global_restrict (vi, "GLOBAL_RESTRICT");
5912 else
5913 make_copy_constraint (vi, nonlocal_id);
5915 continue;
5918 if (POINTER_TYPE_P (TREE_TYPE (t))
5919 && TYPE_RESTRICT (TREE_TYPE (t)))
5920 make_constraint_from_global_restrict (p, "PARM_RESTRICT");
5921 else
5923 for (; p; p = vi_next (p))
5925 if (p->only_restrict_pointers)
5926 make_constraint_from_global_restrict (p, "PARM_RESTRICT");
5927 else if (p->may_have_pointers)
5928 make_constraint_from (p, nonlocal_id);
5933 /* Add a constraint for a result decl that is passed by reference. */
5934 if (DECL_RESULT (fn->decl)
5935 && DECL_BY_REFERENCE (DECL_RESULT (fn->decl)))
5937 varinfo_t p, result_vi = get_vi_for_tree (DECL_RESULT (fn->decl));
5939 for (p = result_vi; p; p = vi_next (p))
5940 make_constraint_from (p, nonlocal_id);
5943 /* Add a constraint for the incoming static chain parameter. */
5944 if (fn->static_chain_decl != NULL_TREE)
5946 varinfo_t p, chain_vi = get_vi_for_tree (fn->static_chain_decl);
5948 for (p = chain_vi; p; p = vi_next (p))
5949 make_constraint_from (p, nonlocal_id);
5953 /* Structure used to put solution bitmaps in a hashtable so they can
5954 be shared among variables with the same points-to set. */
5956 typedef struct shared_bitmap_info
5958 bitmap pt_vars;
5959 hashval_t hashcode;
5960 } *shared_bitmap_info_t;
5961 typedef const struct shared_bitmap_info *const_shared_bitmap_info_t;
5963 /* Shared_bitmap hashtable helpers. */
5965 struct shared_bitmap_hasher : typed_free_remove <shared_bitmap_info>
5967 typedef shared_bitmap_info value_type;
5968 typedef shared_bitmap_info compare_type;
5969 static inline hashval_t hash (const value_type *);
5970 static inline bool equal (const value_type *, const compare_type *);
5973 /* Hash function for a shared_bitmap_info_t */
5975 inline hashval_t
5976 shared_bitmap_hasher::hash (const value_type *bi)
5978 return bi->hashcode;
5981 /* Equality function for two shared_bitmap_info_t's. */
5983 inline bool
5984 shared_bitmap_hasher::equal (const value_type *sbi1, const compare_type *sbi2)
5986 return bitmap_equal_p (sbi1->pt_vars, sbi2->pt_vars);
5989 /* Shared_bitmap hashtable. */
5991 static hash_table<shared_bitmap_hasher> *shared_bitmap_table;
5993 /* Lookup a bitmap in the shared bitmap hashtable, and return an already
5994 existing instance if there is one, NULL otherwise. */
5996 static bitmap
5997 shared_bitmap_lookup (bitmap pt_vars)
5999 shared_bitmap_info **slot;
6000 struct shared_bitmap_info sbi;
6002 sbi.pt_vars = pt_vars;
6003 sbi.hashcode = bitmap_hash (pt_vars);
6005 slot = shared_bitmap_table->find_slot (&sbi, NO_INSERT);
6006 if (!slot)
6007 return NULL;
6008 else
6009 return (*slot)->pt_vars;
6013 /* Add a bitmap to the shared bitmap hashtable. */
6015 static void
6016 shared_bitmap_add (bitmap pt_vars)
6018 shared_bitmap_info **slot;
6019 shared_bitmap_info_t sbi = XNEW (struct shared_bitmap_info);
6021 sbi->pt_vars = pt_vars;
6022 sbi->hashcode = bitmap_hash (pt_vars);
6024 slot = shared_bitmap_table->find_slot (sbi, INSERT);
6025 gcc_assert (!*slot);
6026 *slot = sbi;
6030 /* Set bits in INTO corresponding to the variable uids in solution set FROM. */
6032 static void
6033 set_uids_in_ptset (bitmap into, bitmap from, struct pt_solution *pt)
6035 unsigned int i;
6036 bitmap_iterator bi;
6037 varinfo_t escaped_vi = get_varinfo (find (escaped_id));
6038 bool everything_escaped
6039 = escaped_vi->solution && bitmap_bit_p (escaped_vi->solution, anything_id);
6041 EXECUTE_IF_SET_IN_BITMAP (from, 0, i, bi)
6043 varinfo_t vi = get_varinfo (i);
6045 /* The only artificial variables that are allowed in a may-alias
6046 set are heap variables. */
6047 if (vi->is_artificial_var && !vi->is_heap_var)
6048 continue;
6050 if (everything_escaped
6051 || (escaped_vi->solution
6052 && bitmap_bit_p (escaped_vi->solution, i)))
6054 pt->vars_contains_escaped = true;
6055 pt->vars_contains_escaped_heap = vi->is_heap_var;
6058 if (TREE_CODE (vi->decl) == VAR_DECL
6059 || TREE_CODE (vi->decl) == PARM_DECL
6060 || TREE_CODE (vi->decl) == RESULT_DECL)
6062 /* If we are in IPA mode we will not recompute points-to
6063 sets after inlining so make sure they stay valid. */
6064 if (in_ipa_mode
6065 && !DECL_PT_UID_SET_P (vi->decl))
6066 SET_DECL_PT_UID (vi->decl, DECL_UID (vi->decl));
6068 /* Add the decl to the points-to set. Note that the points-to
6069 set contains global variables. */
6070 bitmap_set_bit (into, DECL_PT_UID (vi->decl));
6071 if (vi->is_global_var)
6072 pt->vars_contains_nonlocal = true;
6078 /* Compute the points-to solution *PT for the variable VI. */
6080 static struct pt_solution
6081 find_what_var_points_to (varinfo_t orig_vi)
6083 unsigned int i;
6084 bitmap_iterator bi;
6085 bitmap finished_solution;
6086 bitmap result;
6087 varinfo_t vi;
6088 struct pt_solution *pt;
6090 /* This variable may have been collapsed, let's get the real
6091 variable. */
6092 vi = get_varinfo (find (orig_vi->id));
6094 /* See if we have already computed the solution and return it. */
6095 pt_solution **slot = &final_solutions->get_or_insert (vi);
6096 if (*slot != NULL)
6097 return **slot;
6099 *slot = pt = XOBNEW (&final_solutions_obstack, struct pt_solution);
6100 memset (pt, 0, sizeof (struct pt_solution));
6102 /* Translate artificial variables into SSA_NAME_PTR_INFO
6103 attributes. */
6104 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, i, bi)
6106 varinfo_t vi = get_varinfo (i);
6108 if (vi->is_artificial_var)
6110 if (vi->id == nothing_id)
6111 pt->null = 1;
6112 else if (vi->id == escaped_id)
6114 if (in_ipa_mode)
6115 pt->ipa_escaped = 1;
6116 else
6117 pt->escaped = 1;
6118 /* Expand some special vars of ESCAPED in-place here. */
6119 varinfo_t evi = get_varinfo (find (escaped_id));
6120 if (bitmap_bit_p (evi->solution, nonlocal_id))
6121 pt->nonlocal = 1;
6123 else if (vi->id == nonlocal_id)
6124 pt->nonlocal = 1;
6125 else if (vi->is_heap_var)
6126 /* We represent heapvars in the points-to set properly. */
6128 else if (vi->id == string_id)
6129 /* Nobody cares - STRING_CSTs are read-only entities. */
6131 else if (vi->id == anything_id
6132 || vi->id == integer_id)
6133 pt->anything = 1;
6137 /* Instead of doing extra work, simply do not create
6138 elaborate points-to information for pt_anything pointers. */
6139 if (pt->anything)
6140 return *pt;
6142 /* Share the final set of variables when possible. */
6143 finished_solution = BITMAP_GGC_ALLOC ();
6144 stats.points_to_sets_created++;
6146 set_uids_in_ptset (finished_solution, vi->solution, pt);
6147 result = shared_bitmap_lookup (finished_solution);
6148 if (!result)
6150 shared_bitmap_add (finished_solution);
6151 pt->vars = finished_solution;
6153 else
6155 pt->vars = result;
6156 bitmap_clear (finished_solution);
6159 return *pt;
6162 /* Given a pointer variable P, fill in its points-to set. */
6164 static void
6165 find_what_p_points_to (tree p)
6167 struct ptr_info_def *pi;
6168 tree lookup_p = p;
6169 varinfo_t vi;
6171 /* For parameters, get at the points-to set for the actual parm
6172 decl. */
6173 if (TREE_CODE (p) == SSA_NAME
6174 && SSA_NAME_IS_DEFAULT_DEF (p)
6175 && (TREE_CODE (SSA_NAME_VAR (p)) == PARM_DECL
6176 || TREE_CODE (SSA_NAME_VAR (p)) == RESULT_DECL))
6177 lookup_p = SSA_NAME_VAR (p);
6179 vi = lookup_vi_for_tree (lookup_p);
6180 if (!vi)
6181 return;
6183 pi = get_ptr_info (p);
6184 pi->pt = find_what_var_points_to (vi);
6188 /* Query statistics for points-to solutions. */
6190 static struct {
6191 unsigned HOST_WIDE_INT pt_solution_includes_may_alias;
6192 unsigned HOST_WIDE_INT pt_solution_includes_no_alias;
6193 unsigned HOST_WIDE_INT pt_solutions_intersect_may_alias;
6194 unsigned HOST_WIDE_INT pt_solutions_intersect_no_alias;
6195 } pta_stats;
6197 void
6198 dump_pta_stats (FILE *s)
6200 fprintf (s, "\nPTA query stats:\n");
6201 fprintf (s, " pt_solution_includes: "
6202 HOST_WIDE_INT_PRINT_DEC" disambiguations, "
6203 HOST_WIDE_INT_PRINT_DEC" queries\n",
6204 pta_stats.pt_solution_includes_no_alias,
6205 pta_stats.pt_solution_includes_no_alias
6206 + pta_stats.pt_solution_includes_may_alias);
6207 fprintf (s, " pt_solutions_intersect: "
6208 HOST_WIDE_INT_PRINT_DEC" disambiguations, "
6209 HOST_WIDE_INT_PRINT_DEC" queries\n",
6210 pta_stats.pt_solutions_intersect_no_alias,
6211 pta_stats.pt_solutions_intersect_no_alias
6212 + pta_stats.pt_solutions_intersect_may_alias);
6216 /* Reset the points-to solution *PT to a conservative default
6217 (point to anything). */
6219 void
6220 pt_solution_reset (struct pt_solution *pt)
6222 memset (pt, 0, sizeof (struct pt_solution));
6223 pt->anything = true;
6226 /* Set the points-to solution *PT to point only to the variables
6227 in VARS. VARS_CONTAINS_GLOBAL specifies whether that contains
6228 global variables and VARS_CONTAINS_RESTRICT specifies whether
6229 it contains restrict tag variables. */
6231 void
6232 pt_solution_set (struct pt_solution *pt, bitmap vars,
6233 bool vars_contains_nonlocal)
6235 memset (pt, 0, sizeof (struct pt_solution));
6236 pt->vars = vars;
6237 pt->vars_contains_nonlocal = vars_contains_nonlocal;
6238 pt->vars_contains_escaped
6239 = (cfun->gimple_df->escaped.anything
6240 || bitmap_intersect_p (cfun->gimple_df->escaped.vars, vars));
6243 /* Set the points-to solution *PT to point only to the variable VAR. */
6245 void
6246 pt_solution_set_var (struct pt_solution *pt, tree var)
6248 memset (pt, 0, sizeof (struct pt_solution));
6249 pt->vars = BITMAP_GGC_ALLOC ();
6250 bitmap_set_bit (pt->vars, DECL_PT_UID (var));
6251 pt->vars_contains_nonlocal = is_global_var (var);
6252 pt->vars_contains_escaped
6253 = (cfun->gimple_df->escaped.anything
6254 || bitmap_bit_p (cfun->gimple_df->escaped.vars, DECL_PT_UID (var)));
6257 /* Computes the union of the points-to solutions *DEST and *SRC and
6258 stores the result in *DEST. This changes the points-to bitmap
6259 of *DEST and thus may not be used if that might be shared.
6260 The points-to bitmap of *SRC and *DEST will not be shared after
6261 this function if they were not before. */
6263 static void
6264 pt_solution_ior_into (struct pt_solution *dest, struct pt_solution *src)
6266 dest->anything |= src->anything;
6267 if (dest->anything)
6269 pt_solution_reset (dest);
6270 return;
6273 dest->nonlocal |= src->nonlocal;
6274 dest->escaped |= src->escaped;
6275 dest->ipa_escaped |= src->ipa_escaped;
6276 dest->null |= src->null;
6277 dest->vars_contains_nonlocal |= src->vars_contains_nonlocal;
6278 dest->vars_contains_escaped |= src->vars_contains_escaped;
6279 dest->vars_contains_escaped_heap |= src->vars_contains_escaped_heap;
6280 if (!src->vars)
6281 return;
6283 if (!dest->vars)
6284 dest->vars = BITMAP_GGC_ALLOC ();
6285 bitmap_ior_into (dest->vars, src->vars);
6288 /* Return true if the points-to solution *PT is empty. */
6290 bool
6291 pt_solution_empty_p (struct pt_solution *pt)
6293 if (pt->anything
6294 || pt->nonlocal)
6295 return false;
6297 if (pt->vars
6298 && !bitmap_empty_p (pt->vars))
6299 return false;
6301 /* If the solution includes ESCAPED, check if that is empty. */
6302 if (pt->escaped
6303 && !pt_solution_empty_p (&cfun->gimple_df->escaped))
6304 return false;
6306 /* If the solution includes ESCAPED, check if that is empty. */
6307 if (pt->ipa_escaped
6308 && !pt_solution_empty_p (&ipa_escaped_pt))
6309 return false;
6311 return true;
6314 /* Return true if the points-to solution *PT only point to a single var, and
6315 return the var uid in *UID. */
6317 bool
6318 pt_solution_singleton_p (struct pt_solution *pt, unsigned *uid)
6320 if (pt->anything || pt->nonlocal || pt->escaped || pt->ipa_escaped
6321 || pt->null || pt->vars == NULL
6322 || !bitmap_single_bit_set_p (pt->vars))
6323 return false;
6325 *uid = bitmap_first_set_bit (pt->vars);
6326 return true;
6329 /* Return true if the points-to solution *PT includes global memory. */
6331 bool
6332 pt_solution_includes_global (struct pt_solution *pt)
6334 if (pt->anything
6335 || pt->nonlocal
6336 || pt->vars_contains_nonlocal
6337 /* The following is a hack to make the malloc escape hack work.
6338 In reality we'd need different sets for escaped-through-return
6339 and escaped-to-callees and passes would need to be updated. */
6340 || pt->vars_contains_escaped_heap)
6341 return true;
6343 /* 'escaped' is also a placeholder so we have to look into it. */
6344 if (pt->escaped)
6345 return pt_solution_includes_global (&cfun->gimple_df->escaped);
6347 if (pt->ipa_escaped)
6348 return pt_solution_includes_global (&ipa_escaped_pt);
6350 /* ??? This predicate is not correct for the IPA-PTA solution
6351 as we do not properly distinguish between unit escape points
6352 and global variables. */
6353 if (cfun->gimple_df->ipa_pta)
6354 return true;
6356 return false;
6359 /* Return true if the points-to solution *PT includes the variable
6360 declaration DECL. */
6362 static bool
6363 pt_solution_includes_1 (struct pt_solution *pt, const_tree decl)
6365 if (pt->anything)
6366 return true;
6368 if (pt->nonlocal
6369 && is_global_var (decl))
6370 return true;
6372 if (pt->vars
6373 && bitmap_bit_p (pt->vars, DECL_PT_UID (decl)))
6374 return true;
6376 /* If the solution includes ESCAPED, check it. */
6377 if (pt->escaped
6378 && pt_solution_includes_1 (&cfun->gimple_df->escaped, decl))
6379 return true;
6381 /* If the solution includes ESCAPED, check it. */
6382 if (pt->ipa_escaped
6383 && pt_solution_includes_1 (&ipa_escaped_pt, decl))
6384 return true;
6386 return false;
6389 bool
6390 pt_solution_includes (struct pt_solution *pt, const_tree decl)
6392 bool res = pt_solution_includes_1 (pt, decl);
6393 if (res)
6394 ++pta_stats.pt_solution_includes_may_alias;
6395 else
6396 ++pta_stats.pt_solution_includes_no_alias;
6397 return res;
6400 /* Return true if both points-to solutions PT1 and PT2 have a non-empty
6401 intersection. */
6403 static bool
6404 pt_solutions_intersect_1 (struct pt_solution *pt1, struct pt_solution *pt2)
6406 if (pt1->anything || pt2->anything)
6407 return true;
6409 /* If either points to unknown global memory and the other points to
6410 any global memory they alias. */
6411 if ((pt1->nonlocal
6412 && (pt2->nonlocal
6413 || pt2->vars_contains_nonlocal))
6414 || (pt2->nonlocal
6415 && pt1->vars_contains_nonlocal))
6416 return true;
6418 /* If either points to all escaped memory and the other points to
6419 any escaped memory they alias. */
6420 if ((pt1->escaped
6421 && (pt2->escaped
6422 || pt2->vars_contains_escaped))
6423 || (pt2->escaped
6424 && pt1->vars_contains_escaped))
6425 return true;
6427 /* Check the escaped solution if required.
6428 ??? Do we need to check the local against the IPA escaped sets? */
6429 if ((pt1->ipa_escaped || pt2->ipa_escaped)
6430 && !pt_solution_empty_p (&ipa_escaped_pt))
6432 /* If both point to escaped memory and that solution
6433 is not empty they alias. */
6434 if (pt1->ipa_escaped && pt2->ipa_escaped)
6435 return true;
6437 /* If either points to escaped memory see if the escaped solution
6438 intersects with the other. */
6439 if ((pt1->ipa_escaped
6440 && pt_solutions_intersect_1 (&ipa_escaped_pt, pt2))
6441 || (pt2->ipa_escaped
6442 && pt_solutions_intersect_1 (&ipa_escaped_pt, pt1)))
6443 return true;
6446 /* Now both pointers alias if their points-to solution intersects. */
6447 return (pt1->vars
6448 && pt2->vars
6449 && bitmap_intersect_p (pt1->vars, pt2->vars));
6452 bool
6453 pt_solutions_intersect (struct pt_solution *pt1, struct pt_solution *pt2)
6455 bool res = pt_solutions_intersect_1 (pt1, pt2);
6456 if (res)
6457 ++pta_stats.pt_solutions_intersect_may_alias;
6458 else
6459 ++pta_stats.pt_solutions_intersect_no_alias;
6460 return res;
6464 /* Dump points-to information to OUTFILE. */
6466 static void
6467 dump_sa_points_to_info (FILE *outfile)
6469 unsigned int i;
6471 fprintf (outfile, "\nPoints-to sets\n\n");
6473 if (dump_flags & TDF_STATS)
6475 fprintf (outfile, "Stats:\n");
6476 fprintf (outfile, "Total vars: %d\n", stats.total_vars);
6477 fprintf (outfile, "Non-pointer vars: %d\n",
6478 stats.nonpointer_vars);
6479 fprintf (outfile, "Statically unified vars: %d\n",
6480 stats.unified_vars_static);
6481 fprintf (outfile, "Dynamically unified vars: %d\n",
6482 stats.unified_vars_dynamic);
6483 fprintf (outfile, "Iterations: %d\n", stats.iterations);
6484 fprintf (outfile, "Number of edges: %d\n", stats.num_edges);
6485 fprintf (outfile, "Number of implicit edges: %d\n",
6486 stats.num_implicit_edges);
6489 for (i = 1; i < varmap.length (); i++)
6491 varinfo_t vi = get_varinfo (i);
6492 if (!vi->may_have_pointers)
6493 continue;
6494 dump_solution_for_var (outfile, i);
6499 /* Debug points-to information to stderr. */
6501 DEBUG_FUNCTION void
6502 debug_sa_points_to_info (void)
6504 dump_sa_points_to_info (stderr);
6508 /* Initialize the always-existing constraint variables for NULL
6509 ANYTHING, READONLY, and INTEGER */
6511 static void
6512 init_base_vars (void)
6514 struct constraint_expr lhs, rhs;
6515 varinfo_t var_anything;
6516 varinfo_t var_nothing;
6517 varinfo_t var_string;
6518 varinfo_t var_escaped;
6519 varinfo_t var_nonlocal;
6520 varinfo_t var_storedanything;
6521 varinfo_t var_integer;
6523 /* Variable ID zero is reserved and should be NULL. */
6524 varmap.safe_push (NULL);
6526 /* Create the NULL variable, used to represent that a variable points
6527 to NULL. */
6528 var_nothing = new_var_info (NULL_TREE, "NULL");
6529 gcc_assert (var_nothing->id == nothing_id);
6530 var_nothing->is_artificial_var = 1;
6531 var_nothing->offset = 0;
6532 var_nothing->size = ~0;
6533 var_nothing->fullsize = ~0;
6534 var_nothing->is_special_var = 1;
6535 var_nothing->may_have_pointers = 0;
6536 var_nothing->is_global_var = 0;
6538 /* Create the ANYTHING variable, used to represent that a variable
6539 points to some unknown piece of memory. */
6540 var_anything = new_var_info (NULL_TREE, "ANYTHING");
6541 gcc_assert (var_anything->id == anything_id);
6542 var_anything->is_artificial_var = 1;
6543 var_anything->size = ~0;
6544 var_anything->offset = 0;
6545 var_anything->fullsize = ~0;
6546 var_anything->is_special_var = 1;
6548 /* Anything points to anything. This makes deref constraints just
6549 work in the presence of linked list and other p = *p type loops,
6550 by saying that *ANYTHING = ANYTHING. */
6551 lhs.type = SCALAR;
6552 lhs.var = anything_id;
6553 lhs.offset = 0;
6554 rhs.type = ADDRESSOF;
6555 rhs.var = anything_id;
6556 rhs.offset = 0;
6558 /* This specifically does not use process_constraint because
6559 process_constraint ignores all anything = anything constraints, since all
6560 but this one are redundant. */
6561 constraints.safe_push (new_constraint (lhs, rhs));
6563 /* Create the STRING variable, used to represent that a variable
6564 points to a string literal. String literals don't contain
6565 pointers so STRING doesn't point to anything. */
6566 var_string = new_var_info (NULL_TREE, "STRING");
6567 gcc_assert (var_string->id == string_id);
6568 var_string->is_artificial_var = 1;
6569 var_string->offset = 0;
6570 var_string->size = ~0;
6571 var_string->fullsize = ~0;
6572 var_string->is_special_var = 1;
6573 var_string->may_have_pointers = 0;
6575 /* Create the ESCAPED variable, used to represent the set of escaped
6576 memory. */
6577 var_escaped = new_var_info (NULL_TREE, "ESCAPED");
6578 gcc_assert (var_escaped->id == escaped_id);
6579 var_escaped->is_artificial_var = 1;
6580 var_escaped->offset = 0;
6581 var_escaped->size = ~0;
6582 var_escaped->fullsize = ~0;
6583 var_escaped->is_special_var = 0;
6585 /* Create the NONLOCAL variable, used to represent the set of nonlocal
6586 memory. */
6587 var_nonlocal = new_var_info (NULL_TREE, "NONLOCAL");
6588 gcc_assert (var_nonlocal->id == nonlocal_id);
6589 var_nonlocal->is_artificial_var = 1;
6590 var_nonlocal->offset = 0;
6591 var_nonlocal->size = ~0;
6592 var_nonlocal->fullsize = ~0;
6593 var_nonlocal->is_special_var = 1;
6595 /* ESCAPED = *ESCAPED, because escaped is may-deref'd at calls, etc. */
6596 lhs.type = SCALAR;
6597 lhs.var = escaped_id;
6598 lhs.offset = 0;
6599 rhs.type = DEREF;
6600 rhs.var = escaped_id;
6601 rhs.offset = 0;
6602 process_constraint (new_constraint (lhs, rhs));
6604 /* ESCAPED = ESCAPED + UNKNOWN_OFFSET, because if a sub-field escapes the
6605 whole variable escapes. */
6606 lhs.type = SCALAR;
6607 lhs.var = escaped_id;
6608 lhs.offset = 0;
6609 rhs.type = SCALAR;
6610 rhs.var = escaped_id;
6611 rhs.offset = UNKNOWN_OFFSET;
6612 process_constraint (new_constraint (lhs, rhs));
6614 /* *ESCAPED = NONLOCAL. This is true because we have to assume
6615 everything pointed to by escaped points to what global memory can
6616 point to. */
6617 lhs.type = DEREF;
6618 lhs.var = escaped_id;
6619 lhs.offset = 0;
6620 rhs.type = SCALAR;
6621 rhs.var = nonlocal_id;
6622 rhs.offset = 0;
6623 process_constraint (new_constraint (lhs, rhs));
6625 /* NONLOCAL = &NONLOCAL, NONLOCAL = &ESCAPED. This is true because
6626 global memory may point to global memory and escaped memory. */
6627 lhs.type = SCALAR;
6628 lhs.var = nonlocal_id;
6629 lhs.offset = 0;
6630 rhs.type = ADDRESSOF;
6631 rhs.var = nonlocal_id;
6632 rhs.offset = 0;
6633 process_constraint (new_constraint (lhs, rhs));
6634 rhs.type = ADDRESSOF;
6635 rhs.var = escaped_id;
6636 rhs.offset = 0;
6637 process_constraint (new_constraint (lhs, rhs));
6639 /* Create the STOREDANYTHING variable, used to represent the set of
6640 variables stored to *ANYTHING. */
6641 var_storedanything = new_var_info (NULL_TREE, "STOREDANYTHING");
6642 gcc_assert (var_storedanything->id == storedanything_id);
6643 var_storedanything->is_artificial_var = 1;
6644 var_storedanything->offset = 0;
6645 var_storedanything->size = ~0;
6646 var_storedanything->fullsize = ~0;
6647 var_storedanything->is_special_var = 0;
6649 /* Create the INTEGER variable, used to represent that a variable points
6650 to what an INTEGER "points to". */
6651 var_integer = new_var_info (NULL_TREE, "INTEGER");
6652 gcc_assert (var_integer->id == integer_id);
6653 var_integer->is_artificial_var = 1;
6654 var_integer->size = ~0;
6655 var_integer->fullsize = ~0;
6656 var_integer->offset = 0;
6657 var_integer->is_special_var = 1;
6659 /* INTEGER = ANYTHING, because we don't know where a dereference of
6660 a random integer will point to. */
6661 lhs.type = SCALAR;
6662 lhs.var = integer_id;
6663 lhs.offset = 0;
6664 rhs.type = ADDRESSOF;
6665 rhs.var = anything_id;
6666 rhs.offset = 0;
6667 process_constraint (new_constraint (lhs, rhs));
6670 /* Initialize things necessary to perform PTA */
6672 static void
6673 init_alias_vars (void)
6675 use_field_sensitive = (MAX_FIELDS_FOR_FIELD_SENSITIVE > 1);
6677 bitmap_obstack_initialize (&pta_obstack);
6678 bitmap_obstack_initialize (&oldpta_obstack);
6679 bitmap_obstack_initialize (&predbitmap_obstack);
6681 constraint_pool = create_alloc_pool ("Constraint pool",
6682 sizeof (struct constraint), 30);
6683 variable_info_pool = create_alloc_pool ("Variable info pool",
6684 sizeof (struct variable_info), 30);
6685 constraints.create (8);
6686 varmap.create (8);
6687 vi_for_tree = new hash_map<tree, varinfo_t>;
6688 call_stmt_vars = new hash_map<gimple, varinfo_t>;
6690 memset (&stats, 0, sizeof (stats));
6691 shared_bitmap_table = new hash_table<shared_bitmap_hasher> (511);
6692 init_base_vars ();
6694 gcc_obstack_init (&fake_var_decl_obstack);
6696 final_solutions = new hash_map<varinfo_t, pt_solution *>;
6697 gcc_obstack_init (&final_solutions_obstack);
6700 /* Remove the REF and ADDRESS edges from GRAPH, as well as all the
6701 predecessor edges. */
6703 static void
6704 remove_preds_and_fake_succs (constraint_graph_t graph)
6706 unsigned int i;
6708 /* Clear the implicit ref and address nodes from the successor
6709 lists. */
6710 for (i = 1; i < FIRST_REF_NODE; i++)
6712 if (graph->succs[i])
6713 bitmap_clear_range (graph->succs[i], FIRST_REF_NODE,
6714 FIRST_REF_NODE * 2);
6717 /* Free the successor list for the non-ref nodes. */
6718 for (i = FIRST_REF_NODE + 1; i < graph->size; i++)
6720 if (graph->succs[i])
6721 BITMAP_FREE (graph->succs[i]);
6724 /* Now reallocate the size of the successor list as, and blow away
6725 the predecessor bitmaps. */
6726 graph->size = varmap.length ();
6727 graph->succs = XRESIZEVEC (bitmap, graph->succs, graph->size);
6729 free (graph->implicit_preds);
6730 graph->implicit_preds = NULL;
6731 free (graph->preds);
6732 graph->preds = NULL;
6733 bitmap_obstack_release (&predbitmap_obstack);
6736 /* Solve the constraint set. */
6738 static void
6739 solve_constraints (void)
6741 struct scc_info *si;
6743 if (dump_file)
6744 fprintf (dump_file,
6745 "\nCollapsing static cycles and doing variable "
6746 "substitution\n");
6748 init_graph (varmap.length () * 2);
6750 if (dump_file)
6751 fprintf (dump_file, "Building predecessor graph\n");
6752 build_pred_graph ();
6754 if (dump_file)
6755 fprintf (dump_file, "Detecting pointer and location "
6756 "equivalences\n");
6757 si = perform_var_substitution (graph);
6759 if (dump_file)
6760 fprintf (dump_file, "Rewriting constraints and unifying "
6761 "variables\n");
6762 rewrite_constraints (graph, si);
6764 build_succ_graph ();
6766 free_var_substitution_info (si);
6768 /* Attach complex constraints to graph nodes. */
6769 move_complex_constraints (graph);
6771 if (dump_file)
6772 fprintf (dump_file, "Uniting pointer but not location equivalent "
6773 "variables\n");
6774 unite_pointer_equivalences (graph);
6776 if (dump_file)
6777 fprintf (dump_file, "Finding indirect cycles\n");
6778 find_indirect_cycles (graph);
6780 /* Implicit nodes and predecessors are no longer necessary at this
6781 point. */
6782 remove_preds_and_fake_succs (graph);
6784 if (dump_file && (dump_flags & TDF_GRAPH))
6786 fprintf (dump_file, "\n\n// The constraint graph before solve-graph "
6787 "in dot format:\n");
6788 dump_constraint_graph (dump_file);
6789 fprintf (dump_file, "\n\n");
6792 if (dump_file)
6793 fprintf (dump_file, "Solving graph\n");
6795 solve_graph (graph);
6797 if (dump_file && (dump_flags & TDF_GRAPH))
6799 fprintf (dump_file, "\n\n// The constraint graph after solve-graph "
6800 "in dot format:\n");
6801 dump_constraint_graph (dump_file);
6802 fprintf (dump_file, "\n\n");
6805 if (dump_file)
6806 dump_sa_points_to_info (dump_file);
6809 /* Create points-to sets for the current function. See the comments
6810 at the start of the file for an algorithmic overview. */
6812 static void
6813 compute_points_to_sets (void)
6815 basic_block bb;
6816 unsigned i;
6817 varinfo_t vi;
6819 timevar_push (TV_TREE_PTA);
6821 init_alias_vars ();
6823 intra_create_variable_infos (cfun);
6825 /* Now walk all statements and build the constraint set. */
6826 FOR_EACH_BB_FN (bb, cfun)
6828 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
6829 gsi_next (&gsi))
6831 gphi *phi = gsi.phi ();
6833 if (! virtual_operand_p (gimple_phi_result (phi)))
6834 find_func_aliases (cfun, phi);
6837 for (gimple_stmt_iterator gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
6838 gsi_next (&gsi))
6840 gimple stmt = gsi_stmt (gsi);
6842 find_func_aliases (cfun, stmt);
6846 if (dump_file)
6848 fprintf (dump_file, "Points-to analysis\n\nConstraints:\n\n");
6849 dump_constraints (dump_file, 0);
6852 /* From the constraints compute the points-to sets. */
6853 solve_constraints ();
6855 /* Compute the points-to set for ESCAPED used for call-clobber analysis. */
6856 cfun->gimple_df->escaped = find_what_var_points_to (get_varinfo (escaped_id));
6858 /* Make sure the ESCAPED solution (which is used as placeholder in
6859 other solutions) does not reference itself. This simplifies
6860 points-to solution queries. */
6861 cfun->gimple_df->escaped.escaped = 0;
6863 /* Compute the points-to sets for pointer SSA_NAMEs. */
6864 for (i = 0; i < num_ssa_names; ++i)
6866 tree ptr = ssa_name (i);
6867 if (ptr
6868 && POINTER_TYPE_P (TREE_TYPE (ptr)))
6869 find_what_p_points_to (ptr);
6872 /* Compute the call-used/clobbered sets. */
6873 FOR_EACH_BB_FN (bb, cfun)
6875 gimple_stmt_iterator gsi;
6877 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
6879 gcall *stmt;
6880 struct pt_solution *pt;
6882 stmt = dyn_cast <gcall *> (gsi_stmt (gsi));
6883 if (!stmt)
6884 continue;
6886 pt = gimple_call_use_set (stmt);
6887 if (gimple_call_flags (stmt) & ECF_CONST)
6888 memset (pt, 0, sizeof (struct pt_solution));
6889 else if ((vi = lookup_call_use_vi (stmt)) != NULL)
6891 *pt = find_what_var_points_to (vi);
6892 /* Escaped (and thus nonlocal) variables are always
6893 implicitly used by calls. */
6894 /* ??? ESCAPED can be empty even though NONLOCAL
6895 always escaped. */
6896 pt->nonlocal = 1;
6897 pt->escaped = 1;
6899 else
6901 /* If there is nothing special about this call then
6902 we have made everything that is used also escape. */
6903 *pt = cfun->gimple_df->escaped;
6904 pt->nonlocal = 1;
6907 pt = gimple_call_clobber_set (stmt);
6908 if (gimple_call_flags (stmt) & (ECF_CONST|ECF_PURE|ECF_NOVOPS))
6909 memset (pt, 0, sizeof (struct pt_solution));
6910 else if ((vi = lookup_call_clobber_vi (stmt)) != NULL)
6912 *pt = find_what_var_points_to (vi);
6913 /* Escaped (and thus nonlocal) variables are always
6914 implicitly clobbered by calls. */
6915 /* ??? ESCAPED can be empty even though NONLOCAL
6916 always escaped. */
6917 pt->nonlocal = 1;
6918 pt->escaped = 1;
6920 else
6922 /* If there is nothing special about this call then
6923 we have made everything that is used also escape. */
6924 *pt = cfun->gimple_df->escaped;
6925 pt->nonlocal = 1;
6930 timevar_pop (TV_TREE_PTA);
6934 /* Delete created points-to sets. */
6936 static void
6937 delete_points_to_sets (void)
6939 unsigned int i;
6941 delete shared_bitmap_table;
6942 shared_bitmap_table = NULL;
6943 if (dump_file && (dump_flags & TDF_STATS))
6944 fprintf (dump_file, "Points to sets created:%d\n",
6945 stats.points_to_sets_created);
6947 delete vi_for_tree;
6948 delete call_stmt_vars;
6949 bitmap_obstack_release (&pta_obstack);
6950 constraints.release ();
6952 for (i = 0; i < graph->size; i++)
6953 graph->complex[i].release ();
6954 free (graph->complex);
6956 free (graph->rep);
6957 free (graph->succs);
6958 free (graph->pe);
6959 free (graph->pe_rep);
6960 free (graph->indirect_cycles);
6961 free (graph);
6963 varmap.release ();
6964 free_alloc_pool (variable_info_pool);
6965 free_alloc_pool (constraint_pool);
6967 obstack_free (&fake_var_decl_obstack, NULL);
6969 delete final_solutions;
6970 obstack_free (&final_solutions_obstack, NULL);
6973 /* Mark "other" loads and stores as belonging to CLIQUE and with
6974 base zero. */
6976 static bool
6977 visit_loadstore (gimple, tree base, tree ref, void *clique_)
6979 unsigned short clique = (uintptr_t)clique_;
6980 if (TREE_CODE (base) == MEM_REF
6981 || TREE_CODE (base) == TARGET_MEM_REF)
6983 tree ptr = TREE_OPERAND (base, 0);
6984 if (TREE_CODE (ptr) == SSA_NAME)
6986 /* ??? We need to make sure 'ptr' doesn't include any of
6987 the restrict tags in its points-to set. */
6988 return false;
6991 /* For now let decls through. */
6993 /* Do not overwrite existing cliques (that includes clique, base
6994 pairs we just set). */
6995 if (MR_DEPENDENCE_CLIQUE (base) == 0)
6997 MR_DEPENDENCE_CLIQUE (base) = clique;
6998 MR_DEPENDENCE_BASE (base) = 0;
7002 /* For plain decl accesses see whether they are accesses to globals
7003 and rewrite them to MEM_REFs with { clique, 0 }. */
7004 if (TREE_CODE (base) == VAR_DECL
7005 && is_global_var (base)
7006 /* ??? We can't rewrite a plain decl with the walk_stmt_load_store
7007 ops callback. */
7008 && base != ref)
7010 tree *basep = &ref;
7011 while (handled_component_p (*basep))
7012 basep = &TREE_OPERAND (*basep, 0);
7013 gcc_assert (TREE_CODE (*basep) == VAR_DECL);
7014 tree ptr = build_fold_addr_expr (*basep);
7015 tree zero = build_int_cst (TREE_TYPE (ptr), 0);
7016 *basep = build2 (MEM_REF, TREE_TYPE (*basep), ptr, zero);
7017 MR_DEPENDENCE_CLIQUE (*basep) = clique;
7018 MR_DEPENDENCE_BASE (*basep) = 0;
7021 return false;
7024 /* If REF is a MEM_REF then assign a clique, base pair to it, updating
7025 CLIQUE, *RESTRICT_VAR and LAST_RUID. Return whether dependence info
7026 was assigned to REF. */
7028 static bool
7029 maybe_set_dependence_info (tree ref, tree ptr,
7030 unsigned short &clique, varinfo_t restrict_var,
7031 unsigned short &last_ruid)
7033 while (handled_component_p (ref))
7034 ref = TREE_OPERAND (ref, 0);
7035 if ((TREE_CODE (ref) == MEM_REF
7036 || TREE_CODE (ref) == TARGET_MEM_REF)
7037 && TREE_OPERAND (ref, 0) == ptr)
7039 /* Do not overwrite existing cliques. This avoids overwriting dependence
7040 info inlined from a function with restrict parameters inlined
7041 into a function with restrict parameters. This usually means we
7042 prefer to be precise in innermost loops. */
7043 if (MR_DEPENDENCE_CLIQUE (ref) == 0)
7045 if (clique == 0)
7046 clique = ++cfun->last_clique;
7047 if (restrict_var->ruid == 0)
7048 restrict_var->ruid = ++last_ruid;
7049 MR_DEPENDENCE_CLIQUE (ref) = clique;
7050 MR_DEPENDENCE_BASE (ref) = restrict_var->ruid;
7051 return true;
7054 return false;
7057 /* Compute the set of independend memory references based on restrict
7058 tags and their conservative propagation to the points-to sets. */
7060 static void
7061 compute_dependence_clique (void)
7063 unsigned short clique = 0;
7064 unsigned short last_ruid = 0;
7065 for (unsigned i = 0; i < num_ssa_names; ++i)
7067 tree ptr = ssa_name (i);
7068 if (!ptr || !POINTER_TYPE_P (TREE_TYPE (ptr)))
7069 continue;
7071 /* Avoid all this when ptr is not dereferenced? */
7072 tree p = ptr;
7073 if (SSA_NAME_IS_DEFAULT_DEF (ptr)
7074 && (TREE_CODE (SSA_NAME_VAR (ptr)) == PARM_DECL
7075 || TREE_CODE (SSA_NAME_VAR (ptr)) == RESULT_DECL))
7076 p = SSA_NAME_VAR (ptr);
7077 varinfo_t vi = lookup_vi_for_tree (p);
7078 if (!vi)
7079 continue;
7080 vi = get_varinfo (find (vi->id));
7081 bitmap_iterator bi;
7082 unsigned j;
7083 varinfo_t restrict_var = NULL;
7084 EXECUTE_IF_SET_IN_BITMAP (vi->solution, 0, j, bi)
7086 varinfo_t oi = get_varinfo (j);
7087 if (oi->is_restrict_var)
7089 if (restrict_var)
7091 if (dump_file && (dump_flags & TDF_DETAILS))
7093 fprintf (dump_file, "found restrict pointed-to "
7094 "for ");
7095 print_generic_expr (dump_file, ptr, 0);
7096 fprintf (dump_file, " but not exclusively\n");
7098 restrict_var = NULL;
7099 break;
7101 restrict_var = oi;
7103 /* NULL is the only other valid points-to entry. */
7104 else if (oi->id != nothing_id)
7106 restrict_var = NULL;
7107 break;
7110 /* Ok, found that ptr must(!) point to a single(!) restrict
7111 variable. */
7112 /* ??? PTA isn't really a proper propagation engine to compute
7113 this property.
7114 ??? We could handle merging of two restricts by unifying them. */
7115 if (restrict_var)
7117 /* Now look at possible dereferences of ptr. */
7118 imm_use_iterator ui;
7119 gimple use_stmt;
7120 FOR_EACH_IMM_USE_STMT (use_stmt, ui, ptr)
7122 /* ??? Calls and asms. */
7123 if (!gimple_assign_single_p (use_stmt))
7124 continue;
7125 maybe_set_dependence_info (gimple_assign_lhs (use_stmt), ptr,
7126 clique, restrict_var, last_ruid);
7127 maybe_set_dependence_info (gimple_assign_rhs1 (use_stmt), ptr,
7128 clique, restrict_var, last_ruid);
7133 if (clique == 0)
7134 return;
7136 /* Assign the BASE id zero to all accesses not based on a restrict
7137 pointer. That way they get disabiguated against restrict
7138 accesses but not against each other. */
7139 /* ??? For restricts derived from globals (thus not incoming
7140 parameters) we can't restrict scoping properly thus the following
7141 is too aggressive there. For now we have excluded those globals from
7142 getting into the MR_DEPENDENCE machinery. */
7143 basic_block bb;
7144 FOR_EACH_BB_FN (bb, cfun)
7145 for (gimple_stmt_iterator gsi = gsi_start_bb (bb);
7146 !gsi_end_p (gsi); gsi_next (&gsi))
7148 gimple stmt = gsi_stmt (gsi);
7149 walk_stmt_load_store_ops (stmt, (void *)(uintptr_t)clique,
7150 visit_loadstore, visit_loadstore);
7154 /* Compute points-to information for every SSA_NAME pointer in the
7155 current function and compute the transitive closure of escaped
7156 variables to re-initialize the call-clobber states of local variables. */
7158 unsigned int
7159 compute_may_aliases (void)
7161 if (cfun->gimple_df->ipa_pta)
7163 if (dump_file)
7165 fprintf (dump_file, "\nNot re-computing points-to information "
7166 "because IPA points-to information is available.\n\n");
7168 /* But still dump what we have remaining it. */
7169 dump_alias_info (dump_file);
7172 return 0;
7175 /* For each pointer P_i, determine the sets of variables that P_i may
7176 point-to. Compute the reachability set of escaped and call-used
7177 variables. */
7178 compute_points_to_sets ();
7180 /* Debugging dumps. */
7181 if (dump_file)
7182 dump_alias_info (dump_file);
7184 /* Compute restrict-based memory disambiguations. */
7185 compute_dependence_clique ();
7187 /* Deallocate memory used by aliasing data structures and the internal
7188 points-to solution. */
7189 delete_points_to_sets ();
7191 gcc_assert (!need_ssa_update_p (cfun));
7193 return 0;
7196 /* A dummy pass to cause points-to information to be computed via
7197 TODO_rebuild_alias. */
7199 namespace {
7201 const pass_data pass_data_build_alias =
7203 GIMPLE_PASS, /* type */
7204 "alias", /* name */
7205 OPTGROUP_NONE, /* optinfo_flags */
7206 TV_NONE, /* tv_id */
7207 ( PROP_cfg | PROP_ssa ), /* properties_required */
7208 0, /* properties_provided */
7209 0, /* properties_destroyed */
7210 0, /* todo_flags_start */
7211 TODO_rebuild_alias, /* todo_flags_finish */
7214 class pass_build_alias : public gimple_opt_pass
7216 public:
7217 pass_build_alias (gcc::context *ctxt)
7218 : gimple_opt_pass (pass_data_build_alias, ctxt)
7221 /* opt_pass methods: */
7222 virtual bool gate (function *) { return flag_tree_pta; }
7224 }; // class pass_build_alias
7226 } // anon namespace
7228 gimple_opt_pass *
7229 make_pass_build_alias (gcc::context *ctxt)
7231 return new pass_build_alias (ctxt);
7234 /* A dummy pass to cause points-to information to be computed via
7235 TODO_rebuild_alias. */
7237 namespace {
7239 const pass_data pass_data_build_ealias =
7241 GIMPLE_PASS, /* type */
7242 "ealias", /* name */
7243 OPTGROUP_NONE, /* optinfo_flags */
7244 TV_NONE, /* tv_id */
7245 ( PROP_cfg | PROP_ssa ), /* properties_required */
7246 0, /* properties_provided */
7247 0, /* properties_destroyed */
7248 0, /* todo_flags_start */
7249 TODO_rebuild_alias, /* todo_flags_finish */
7252 class pass_build_ealias : public gimple_opt_pass
7254 public:
7255 pass_build_ealias (gcc::context *ctxt)
7256 : gimple_opt_pass (pass_data_build_ealias, ctxt)
7259 /* opt_pass methods: */
7260 virtual bool gate (function *) { return flag_tree_pta; }
7262 }; // class pass_build_ealias
7264 } // anon namespace
7266 gimple_opt_pass *
7267 make_pass_build_ealias (gcc::context *ctxt)
7269 return new pass_build_ealias (ctxt);
7273 /* IPA PTA solutions for ESCAPED. */
7274 struct pt_solution ipa_escaped_pt
7275 = { true, false, false, false, false, false, false, false, NULL };
7277 /* Associate node with varinfo DATA. Worker for
7278 cgraph_for_node_and_aliases. */
7279 static bool
7280 associate_varinfo_to_alias (struct cgraph_node *node, void *data)
7282 if ((node->alias || node->thunk.thunk_p)
7283 && node->analyzed)
7284 insert_vi_for_tree (node->decl, (varinfo_t)data);
7285 return false;
7288 /* Execute the driver for IPA PTA. */
7289 static unsigned int
7290 ipa_pta_execute (void)
7292 struct cgraph_node *node;
7293 varpool_node *var;
7294 int from;
7296 in_ipa_mode = 1;
7298 init_alias_vars ();
7300 if (dump_file && (dump_flags & TDF_DETAILS))
7302 symtab_node::dump_table (dump_file);
7303 fprintf (dump_file, "\n");
7306 /* Build the constraints. */
7307 FOR_EACH_DEFINED_FUNCTION (node)
7309 varinfo_t vi;
7310 /* Nodes without a body are not interesting. Especially do not
7311 visit clones at this point for now - we get duplicate decls
7312 there for inline clones at least. */
7313 if (!node->has_gimple_body_p () || node->global.inlined_to)
7314 continue;
7315 node->get_body ();
7317 gcc_assert (!node->clone_of);
7319 vi = create_function_info_for (node->decl,
7320 alias_get_name (node->decl));
7321 node->call_for_symbol_thunks_and_aliases
7322 (associate_varinfo_to_alias, vi, true);
7325 /* Create constraints for global variables and their initializers. */
7326 FOR_EACH_VARIABLE (var)
7328 if (var->alias && var->analyzed)
7329 continue;
7331 get_vi_for_tree (var->decl);
7334 if (dump_file)
7336 fprintf (dump_file,
7337 "Generating constraints for global initializers\n\n");
7338 dump_constraints (dump_file, 0);
7339 fprintf (dump_file, "\n");
7341 from = constraints.length ();
7343 FOR_EACH_DEFINED_FUNCTION (node)
7345 struct function *func;
7346 basic_block bb;
7348 /* Nodes without a body are not interesting. */
7349 if (!node->has_gimple_body_p () || node->clone_of)
7350 continue;
7352 if (dump_file)
7354 fprintf (dump_file,
7355 "Generating constraints for %s", node->name ());
7356 if (DECL_ASSEMBLER_NAME_SET_P (node->decl))
7357 fprintf (dump_file, " (%s)",
7358 IDENTIFIER_POINTER
7359 (DECL_ASSEMBLER_NAME (node->decl)));
7360 fprintf (dump_file, "\n");
7363 func = DECL_STRUCT_FUNCTION (node->decl);
7364 gcc_assert (cfun == NULL);
7366 /* For externally visible or attribute used annotated functions use
7367 local constraints for their arguments.
7368 For local functions we see all callers and thus do not need initial
7369 constraints for parameters. */
7370 if (node->used_from_other_partition
7371 || node->externally_visible
7372 || node->force_output)
7374 intra_create_variable_infos (func);
7376 /* We also need to make function return values escape. Nothing
7377 escapes by returning from main though. */
7378 if (!MAIN_NAME_P (DECL_NAME (node->decl)))
7380 varinfo_t fi, rvi;
7381 fi = lookup_vi_for_tree (node->decl);
7382 rvi = first_vi_for_offset (fi, fi_result);
7383 if (rvi && rvi->offset == fi_result)
7385 struct constraint_expr includes;
7386 struct constraint_expr var;
7387 includes.var = escaped_id;
7388 includes.offset = 0;
7389 includes.type = SCALAR;
7390 var.var = rvi->id;
7391 var.offset = 0;
7392 var.type = SCALAR;
7393 process_constraint (new_constraint (includes, var));
7398 /* Build constriants for the function body. */
7399 FOR_EACH_BB_FN (bb, func)
7401 for (gphi_iterator gsi = gsi_start_phis (bb); !gsi_end_p (gsi);
7402 gsi_next (&gsi))
7404 gphi *phi = gsi.phi ();
7406 if (! virtual_operand_p (gimple_phi_result (phi)))
7407 find_func_aliases (func, phi);
7410 for (gimple_stmt_iterator gsi = gsi_start_bb (bb); !gsi_end_p (gsi);
7411 gsi_next (&gsi))
7413 gimple stmt = gsi_stmt (gsi);
7415 find_func_aliases (func, stmt);
7416 find_func_clobbers (func, stmt);
7420 if (dump_file)
7422 fprintf (dump_file, "\n");
7423 dump_constraints (dump_file, from);
7424 fprintf (dump_file, "\n");
7426 from = constraints.length ();
7429 /* From the constraints compute the points-to sets. */
7430 solve_constraints ();
7432 /* Compute the global points-to sets for ESCAPED.
7433 ??? Note that the computed escape set is not correct
7434 for the whole unit as we fail to consider graph edges to
7435 externally visible functions. */
7436 ipa_escaped_pt = find_what_var_points_to (get_varinfo (escaped_id));
7438 /* Make sure the ESCAPED solution (which is used as placeholder in
7439 other solutions) does not reference itself. This simplifies
7440 points-to solution queries. */
7441 ipa_escaped_pt.ipa_escaped = 0;
7443 /* Assign the points-to sets to the SSA names in the unit. */
7444 FOR_EACH_DEFINED_FUNCTION (node)
7446 tree ptr;
7447 struct function *fn;
7448 unsigned i;
7449 basic_block bb;
7451 /* Nodes without a body are not interesting. */
7452 if (!node->has_gimple_body_p () || node->clone_of)
7453 continue;
7455 fn = DECL_STRUCT_FUNCTION (node->decl);
7457 /* Compute the points-to sets for pointer SSA_NAMEs. */
7458 FOR_EACH_VEC_ELT (*fn->gimple_df->ssa_names, i, ptr)
7460 if (ptr
7461 && POINTER_TYPE_P (TREE_TYPE (ptr)))
7462 find_what_p_points_to (ptr);
7465 /* Compute the call-use and call-clobber sets for indirect calls
7466 and calls to external functions. */
7467 FOR_EACH_BB_FN (bb, fn)
7469 gimple_stmt_iterator gsi;
7471 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
7473 gcall *stmt;
7474 struct pt_solution *pt;
7475 varinfo_t vi, fi;
7476 tree decl;
7478 stmt = dyn_cast <gcall *> (gsi_stmt (gsi));
7479 if (!stmt)
7480 continue;
7482 /* Handle direct calls to functions with body. */
7483 decl = gimple_call_fndecl (stmt);
7484 if (decl
7485 && (fi = lookup_vi_for_tree (decl))
7486 && fi->is_fn_info)
7488 *gimple_call_clobber_set (stmt)
7489 = find_what_var_points_to
7490 (first_vi_for_offset (fi, fi_clobbers));
7491 *gimple_call_use_set (stmt)
7492 = find_what_var_points_to
7493 (first_vi_for_offset (fi, fi_uses));
7495 /* Handle direct calls to external functions. */
7496 else if (decl)
7498 pt = gimple_call_use_set (stmt);
7499 if (gimple_call_flags (stmt) & ECF_CONST)
7500 memset (pt, 0, sizeof (struct pt_solution));
7501 else if ((vi = lookup_call_use_vi (stmt)) != NULL)
7503 *pt = find_what_var_points_to (vi);
7504 /* Escaped (and thus nonlocal) variables are always
7505 implicitly used by calls. */
7506 /* ??? ESCAPED can be empty even though NONLOCAL
7507 always escaped. */
7508 pt->nonlocal = 1;
7509 pt->ipa_escaped = 1;
7511 else
7513 /* If there is nothing special about this call then
7514 we have made everything that is used also escape. */
7515 *pt = ipa_escaped_pt;
7516 pt->nonlocal = 1;
7519 pt = gimple_call_clobber_set (stmt);
7520 if (gimple_call_flags (stmt) & (ECF_CONST|ECF_PURE|ECF_NOVOPS))
7521 memset (pt, 0, sizeof (struct pt_solution));
7522 else if ((vi = lookup_call_clobber_vi (stmt)) != NULL)
7524 *pt = find_what_var_points_to (vi);
7525 /* Escaped (and thus nonlocal) variables are always
7526 implicitly clobbered by calls. */
7527 /* ??? ESCAPED can be empty even though NONLOCAL
7528 always escaped. */
7529 pt->nonlocal = 1;
7530 pt->ipa_escaped = 1;
7532 else
7534 /* If there is nothing special about this call then
7535 we have made everything that is used also escape. */
7536 *pt = ipa_escaped_pt;
7537 pt->nonlocal = 1;
7540 /* Handle indirect calls. */
7541 else if (!decl
7542 && (fi = get_fi_for_callee (stmt)))
7544 /* We need to accumulate all clobbers/uses of all possible
7545 callees. */
7546 fi = get_varinfo (find (fi->id));
7547 /* If we cannot constrain the set of functions we'll end up
7548 calling we end up using/clobbering everything. */
7549 if (bitmap_bit_p (fi->solution, anything_id)
7550 || bitmap_bit_p (fi->solution, nonlocal_id)
7551 || bitmap_bit_p (fi->solution, escaped_id))
7553 pt_solution_reset (gimple_call_clobber_set (stmt));
7554 pt_solution_reset (gimple_call_use_set (stmt));
7556 else
7558 bitmap_iterator bi;
7559 unsigned i;
7560 struct pt_solution *uses, *clobbers;
7562 uses = gimple_call_use_set (stmt);
7563 clobbers = gimple_call_clobber_set (stmt);
7564 memset (uses, 0, sizeof (struct pt_solution));
7565 memset (clobbers, 0, sizeof (struct pt_solution));
7566 EXECUTE_IF_SET_IN_BITMAP (fi->solution, 0, i, bi)
7568 struct pt_solution sol;
7570 vi = get_varinfo (i);
7571 if (!vi->is_fn_info)
7573 /* ??? We could be more precise here? */
7574 uses->nonlocal = 1;
7575 uses->ipa_escaped = 1;
7576 clobbers->nonlocal = 1;
7577 clobbers->ipa_escaped = 1;
7578 continue;
7581 if (!uses->anything)
7583 sol = find_what_var_points_to
7584 (first_vi_for_offset (vi, fi_uses));
7585 pt_solution_ior_into (uses, &sol);
7587 if (!clobbers->anything)
7589 sol = find_what_var_points_to
7590 (first_vi_for_offset (vi, fi_clobbers));
7591 pt_solution_ior_into (clobbers, &sol);
7599 fn->gimple_df->ipa_pta = true;
7602 delete_points_to_sets ();
7604 in_ipa_mode = 0;
7606 return 0;
7609 namespace {
7611 const pass_data pass_data_ipa_pta =
7613 SIMPLE_IPA_PASS, /* type */
7614 "pta", /* name */
7615 OPTGROUP_NONE, /* optinfo_flags */
7616 TV_IPA_PTA, /* tv_id */
7617 0, /* properties_required */
7618 0, /* properties_provided */
7619 0, /* properties_destroyed */
7620 0, /* todo_flags_start */
7621 0, /* todo_flags_finish */
7624 class pass_ipa_pta : public simple_ipa_opt_pass
7626 public:
7627 pass_ipa_pta (gcc::context *ctxt)
7628 : simple_ipa_opt_pass (pass_data_ipa_pta, ctxt)
7631 /* opt_pass methods: */
7632 virtual bool gate (function *)
7634 return (optimize
7635 && flag_ipa_pta
7636 /* Don't bother doing anything if the program has errors. */
7637 && !seen_error ());
7640 virtual unsigned int execute (function *) { return ipa_pta_execute (); }
7642 }; // class pass_ipa_pta
7644 } // anon namespace
7646 simple_ipa_opt_pass *
7647 make_pass_ipa_pta (gcc::context *ctxt)
7649 return new pass_ipa_pta (ctxt);