OSDN Git Service

PR tree-optimization/16688
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-alias.c
1 /* Alias analysis for trees.
2    Copyright (C) 2004 Free Software Foundation, Inc.
3    Contributed by Diego Novillo <dnovillo@redhat.com>
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
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.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING.  If not, write to
19 the Free Software Foundation, 59 Temple Place - Suite 330,
20 Boston, MA 02111-1307, USA.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "tree.h"
27 #include "rtl.h"
28 #include "tm_p.h"
29 #include "hard-reg-set.h"
30 #include "basic-block.h"
31 #include "timevar.h"
32 #include "expr.h"
33 #include "ggc.h"
34 #include "langhooks.h"
35 #include "flags.h"
36 #include "function.h"
37 #include "diagnostic.h"
38 #include "tree-dump.h"
39 #include "tree-gimple.h"
40 #include "tree-flow.h"
41 #include "tree-inline.h"
42 #include "tree-alias-common.h"
43 #include "tree-pass.h"
44 #include "convert.h"
45 #include "params.h"
46
47
48 /* Structure to map a variable to its alias set and keep track of the
49    virtual operands that will be needed to represent it.  */
50 struct alias_map_d
51 {
52   /* Variable and its alias set.  */
53   tree var;
54   HOST_WIDE_INT set;
55
56   /* Total number of virtual operands that will be needed to represent
57      all the aliases of VAR.  */
58   long total_alias_vops;
59
60   /* Nonzero if the aliases for this memory tag have been grouped
61      already.  Used in group_aliases.  */
62   unsigned int grouped_p : 1;
63
64   /* Set of variables aliased with VAR.  This is the exact same
65      information contained in VAR_ANN (VAR)->MAY_ALIASES, but in
66      bitmap form to speed up alias grouping.  */
67   sbitmap may_aliases;
68 };
69
70
71 /* Alias information used by compute_may_aliases and its helpers.  */
72 struct alias_info
73 {
74   /* SSA names visited while collecting points-to information.  If bit I
75      is set, it means that SSA variable with version I has already been
76      visited.  */
77   bitmap ssa_names_visited;
78
79   /* Array of SSA_NAME pointers processed by the points-to collector.  */
80   varray_type processed_ptrs;
81
82   /* Variables whose address is still needed.  */
83   bitmap addresses_needed;
84
85   /* ADDRESSABLE_VARS contains all the global variables and locals that
86      have had their address taken.  */
87   struct alias_map_d **addressable_vars;
88   size_t num_addressable_vars;
89
90   /* POINTERS contains all the _DECL pointers with unique memory tags
91      that have been referenced in the program.  */
92   struct alias_map_d **pointers;
93   size_t num_pointers;
94
95   /* Number of function calls found in the program.  */
96   size_t num_calls_found;
97
98   /* Array of counters to keep track of how many times each pointer has
99      been dereferenced in the program.  This is used by the alias grouping
100      heuristic in compute_flow_insensitive_aliasing.  */
101   varray_type num_references;
102
103   /* Total number of virtual operands that will be needed to represent
104      all the aliases of all the pointers found in the program.  */
105   long total_alias_vops;
106
107   /* Variables that have been written to.  */
108   bitmap written_vars;
109
110   /* Pointers that have been used in an indirect store operation.  */
111   bitmap dereferenced_ptrs_store;
112
113   /* Pointers that have been used in an indirect load operation.  */
114   bitmap dereferenced_ptrs_load;
115 };
116
117
118 /* Counters used to display statistics on alias analysis.  */
119 struct alias_stats_d
120 {
121   unsigned int alias_queries;
122   unsigned int alias_mayalias;
123   unsigned int alias_noalias;
124   unsigned int simple_queries;
125   unsigned int simple_resolved;
126   unsigned int tbaa_queries;
127   unsigned int tbaa_resolved;
128   unsigned int pta_queries;
129   unsigned int pta_resolved;
130 };
131
132
133 /* Local variables.  */
134 static struct alias_stats_d alias_stats;
135
136 /* Local functions.  */
137 static void compute_flow_insensitive_aliasing (struct alias_info *);
138 static void dump_alias_stats (FILE *);
139 static bool may_alias_p (tree, HOST_WIDE_INT, tree, HOST_WIDE_INT);
140 static tree create_memory_tag (tree type, bool is_type_tag);
141 static tree get_tmt_for (tree, struct alias_info *);
142 static tree get_nmt_for (tree);
143 static void add_may_alias (tree, tree);
144 static void replace_may_alias (tree, size_t, tree);
145 static struct alias_info *init_alias_info (void);
146 static void delete_alias_info (struct alias_info *);
147 static void compute_points_to_and_addr_escape (struct alias_info *);
148 static void compute_flow_sensitive_aliasing (struct alias_info *);
149 static void setup_pointers_and_addressables (struct alias_info *);
150 static bool collect_points_to_info_r (tree, tree, void *);
151 static bool is_escape_site (tree, size_t *);
152 static void add_pointed_to_var (struct alias_info *, tree, tree);
153 static void add_pointed_to_expr (tree, tree);
154 static void create_global_var (void);
155 static void collect_points_to_info_for (struct alias_info *, tree);
156 static bool ptr_is_dereferenced_by (tree, tree, bool *);
157 static void maybe_create_global_var (struct alias_info *ai);
158 static void group_aliases (struct alias_info *);
159 static struct ptr_info_def *get_ptr_info (tree t);
160
161 /* Global declarations.  */
162
163 /* Call clobbered variables in the function.  If bit I is set, then
164    REFERENCED_VARS (I) is call-clobbered.  */
165 bitmap call_clobbered_vars;
166
167 /* Addressable variables in the function.  If bit I is set, then
168    REFERENCED_VARS (I) has had its address taken.  Note that
169    CALL_CLOBBERED_VARS and ADDRESSABLE_VARS are not related.  An
170    addressable variable is not necessarily call-clobbered (e.g., a
171    local addressable whose address does not escape) and not all
172    call-clobbered variables are addressable (e.g., a local static
173    variable).  */
174 bitmap addressable_vars;
175
176 /* 'true' after aliases have been computed (see compute_may_aliases).  This
177    is used by get_stmt_operands and its helpers to determine what to do
178    when scanning an operand for a variable that may be aliased.  If
179    may-alias information is still not available, the statement is marked as
180    having volatile operands.  */
181 bool aliases_computed_p;
182
183 /* When the program has too many call-clobbered variables and call-sites,
184    this variable is used to represent the clobbering effects of function
185    calls.  In these cases, all the call clobbered variables in the program
186    are forced to alias this variable.  This reduces compile times by not
187    having to keep track of too many V_MAY_DEF expressions at call sites.  */
188 tree global_var;
189
190
191 /* Compute may-alias information for every variable referenced in function
192    FNDECL.
193
194    Alias analysis proceeds in 3 main phases:
195
196    1- Points-to and escape analysis.
197
198    This phase walks the use-def chains in the SSA web looking for three
199    things:
200
201         * Assignments of the form P_i = &VAR
202         * Assignments of the form P_i = malloc()
203         * Pointers and ADDR_EXPR that escape the current function.
204
205    The concept of 'escaping' is the same one used in the Java world.  When
206    a pointer or an ADDR_EXPR escapes, it means that it has been exposed
207    outside of the current function.  So, assignment to global variables,
208    function arguments and returning a pointer are all escape sites.
209
210    This is where we are currently limited.  Since not everything is renamed
211    into SSA, we lose track of escape properties when a pointer is stashed
212    inside a field in a structure, for instance.  In those cases, we are
213    assuming that the pointer does escape.
214
215    We use escape analysis to determine whether a variable is
216    call-clobbered.  Simply put, if an ADDR_EXPR escapes, then the variable
217    is call-clobbered.  If a pointer P_i escapes, then all the variables
218    pointed-to by P_i (and its memory tag) also escape.
219
220    2- Compute flow-sensitive aliases
221
222    We have two classes of memory tags.  Memory tags associated with the
223    pointed-to data type of the pointers in the program.  These tags are
224    called "type memory tag" (TMT).  The other class are those associated
225    with SSA_NAMEs, called "name memory tag" (NMT). The basic idea is that
226    when adding operands for an INDIRECT_REF *P_i, we will first check
227    whether P_i has a name tag, if it does we use it, because that will have
228    more precise aliasing information.  Otherwise, we use the standard type
229    tag.
230
231    In this phase, we go through all the pointers we found in points-to
232    analysis and create alias sets for the name memory tags associated with
233    each pointer P_i.  If P_i escapes, we mark call-clobbered the variables
234    it points to and its tag.
235
236
237    3- Compute flow-insensitive aliases
238
239    This pass will compare the alias set of every type memory tag and every
240    addressable variable found in the program.  Given a type memory tag TMT
241    and an addressable variable V.  If the alias sets of TMT and V conflict
242    (as computed by may_alias_p), then V is marked as an alias tag and added
243    to the alias set of TMT.
244
245    For instance, consider the following function:
246
247             foo (int i)
248             {
249               int *p, *q, a, b;
250             
251               if (i > 10)
252                 p = &a;
253               else
254                 q = &b;
255             
256               *p = 3;
257               *q = 5;
258               a = b + 2;
259               return *p;
260             }
261
262    After aliasing analysis has finished, the type memory tag for pointer
263    'p' will have two aliases, namely variables 'a' and 'b'.  Every time
264    pointer 'p' is dereferenced, we want to mark the operation as a
265    potential reference to 'a' and 'b'.
266
267             foo (int i)
268             {
269               int *p, a, b;
270
271               if (i_2 > 10)
272                 p_4 = &a;
273               else
274                 p_6 = &b;
275               # p_1 = PHI <p_4(1), p_6(2)>;
276
277               # a_7 = V_MAY_DEF <a_3>;
278               # b_8 = V_MAY_DEF <b_5>;
279               *p_1 = 3;
280
281               # a_9 = V_MAY_DEF <a_7>
282               # VUSE <b_8>
283               a_9 = b_8 + 2;
284
285               # VUSE <a_9>;
286               # VUSE <b_8>;
287               return *p_1;
288             }
289
290    In certain cases, the list of may aliases for a pointer may grow too
291    large.  This may cause an explosion in the number of virtual operands
292    inserted in the code.  Resulting in increased memory consumption and
293    compilation time.
294
295    When the number of virtual operands needed to represent aliased
296    loads and stores grows too large (configurable with @option{--param
297    max-aliased-vops}), alias sets are grouped to avoid severe
298    compile-time slow downs and memory consumption.  See group_aliases.  */
299
300 static void
301 compute_may_aliases (void)
302 {
303   struct alias_info *ai;
304   
305   memset (&alias_stats, 0, sizeof (alias_stats));
306
307   /* Initialize aliasing information.  */
308   ai = init_alias_info ();
309
310   /* For each pointer P_i, determine the sets of variables that P_i may
311      point-to.  For every addressable variable V, determine whether the
312      address of V escapes the current function, making V call-clobbered
313      (i.e., whether &V is stored in a global variable or if its passed as a
314      function call argument).  */
315   compute_points_to_and_addr_escape (ai);
316
317   /* Collect all pointers and addressable variables, compute alias sets,
318      create memory tags for pointers and promote variables whose address is
319      not needed anymore.  */
320   setup_pointers_and_addressables (ai);
321
322   /* Compute flow-sensitive, points-to based aliasing for all the name
323      memory tags.  Note that this pass needs to be done before flow
324      insensitive analysis because it uses the points-to information
325      gathered before to mark call-clobbered type tags.  */
326   compute_flow_sensitive_aliasing (ai);
327
328   /* Compute type-based flow-insensitive aliasing for all the type
329      memory tags.  */
330   compute_flow_insensitive_aliasing (ai);
331
332   /* If the program has too many call-clobbered variables and/or function
333      calls, create .GLOBAL_VAR and use it to model call-clobbering
334      semantics at call sites.  This reduces the number of virtual operands
335      considerably, improving compile times at the expense of lost
336      aliasing precision.  */
337   maybe_create_global_var (ai);
338
339   /* Debugging dumps.  */
340   if (dump_file)
341     {
342       dump_referenced_vars (dump_file);
343       if (dump_flags & TDF_STATS)
344         dump_alias_stats (dump_file);
345       dump_points_to_info (dump_file);
346       dump_alias_info (dump_file);
347     }
348
349   /* Deallocate memory used by aliasing data structures.  */
350   delete_alias_info (ai);
351
352   /* Indicate that may-alias information is now available.  */
353   aliases_computed_p = true;
354 }
355
356 struct tree_opt_pass pass_may_alias = 
357 {
358   "alias",                              /* name */
359   NULL,                                 /* gate */
360   compute_may_aliases,                  /* execute */
361   NULL,                                 /* sub */
362   NULL,                                 /* next */
363   0,                                    /* static_pass_number */
364   TV_TREE_MAY_ALIAS,                    /* tv_id */
365   PROP_cfg | PROP_ssa | PROP_pta,       /* properties_required */
366   0,                                    /* properties_provided */
367   0,                                    /* properties_destroyed */
368   0,                                    /* todo_flags_start */
369   TODO_dump_func | TODO_rename_vars
370     | TODO_ggc_collect | TODO_verify_ssa  /* todo_flags_finish */
371 };
372
373
374 /* Initialize the data structures used for alias analysis.  */
375
376 static struct alias_info *
377 init_alias_info (void)
378 {
379   struct alias_info *ai;
380
381   ai = xcalloc (1, sizeof (struct alias_info));
382   ai->ssa_names_visited = BITMAP_XMALLOC ();
383   VARRAY_TREE_INIT (ai->processed_ptrs, 50, "processed_ptrs");
384   ai->addresses_needed = BITMAP_XMALLOC ();
385   VARRAY_UINT_INIT (ai->num_references, num_referenced_vars, "num_references");
386   ai->written_vars = BITMAP_XMALLOC ();
387   ai->dereferenced_ptrs_store = BITMAP_XMALLOC ();
388   ai->dereferenced_ptrs_load = BITMAP_XMALLOC ();
389
390   /* If aliases have been computed before, clear existing information.  */
391   if (aliases_computed_p)
392     {
393       size_t i;
394
395       /* Clear the call-clobbered set.  We are going to re-discover
396           call-clobbered variables.  */
397       EXECUTE_IF_SET_IN_BITMAP (call_clobbered_vars, 0, i,
398         {
399           tree var = referenced_var (i);
400           DECL_NEEDS_TO_LIVE_IN_MEMORY_INTERNAL (var) = 0;
401
402           /* Variables that are intrinsically call-clobbered (globals,
403              local statics, etc) will not be marked by the aliasing
404              code, so we can't remove them from CALL_CLOBBERED_VARS.  */
405           if (!is_call_clobbered (var))
406             bitmap_clear_bit (call_clobbered_vars, var_ann (var)->uid);
407         });
408
409       /* Similarly, clear the set of addressable variables.  In this
410          case, we can just clear the set because addressability is
411          only computed here.  */
412       bitmap_clear (addressable_vars);
413
414       /* Clear flow-insensitive alias information from each symbol.  */
415       for (i = 0; i < num_referenced_vars; i++)
416         {
417           var_ann_t ann = var_ann (referenced_var (i));
418
419           ann->is_alias_tag = 0;
420           if (ann->type_mem_tag)
421             {
422               var_ann_t tag_ann = var_ann (ann->type_mem_tag);
423               tag_ann->may_aliases = NULL;
424               bitmap_set_bit (vars_to_rename, tag_ann->uid);
425             }
426         }
427
428       /* Clear flow-sensitive points-to information from each SSA name.  */
429       for (i = 1; i < num_ssa_names; i++)
430         {
431           tree name = ssa_name (i);
432
433           if (!POINTER_TYPE_P (TREE_TYPE (name)))
434             continue;
435
436           if (SSA_NAME_PTR_INFO (name))
437             {
438               struct ptr_info_def *pi = SSA_NAME_PTR_INFO (name);
439
440               /* Clear all the flags but keep the name tag to
441                  avoid creating new temporaries unnecessarily.  If
442                  this pointer is found to point to a subset or
443                  superset of its former points-to set, then a new
444                  tag will need to be created in create_name_tags.  */
445               pi->pt_anything = 0;
446               pi->pt_malloc = 0;
447               pi->value_escapes_p = 0;
448               pi->is_dereferenced = 0;
449               if (pi->pt_vars)
450                 bitmap_clear (pi->pt_vars);
451               if (pi->name_mem_tag)
452                 var_ann (pi->name_mem_tag)->may_aliases = NULL;
453             }
454         }
455     }
456
457   return ai;
458 }
459
460
461 /* Deallocate memory used by alias analysis.  */
462
463 static void
464 delete_alias_info (struct alias_info *ai)
465 {
466   size_t i;
467
468   BITMAP_XFREE (ai->ssa_names_visited);
469   ai->processed_ptrs = NULL;
470   BITMAP_XFREE (ai->addresses_needed);
471
472   for (i = 0; i < ai->num_addressable_vars; i++)
473     {
474       sbitmap_free (ai->addressable_vars[i]->may_aliases);
475       free (ai->addressable_vars[i]);
476     }
477   free (ai->addressable_vars);
478
479   for (i = 0; i < ai->num_pointers; i++)
480     {
481       sbitmap_free (ai->pointers[i]->may_aliases);
482       free (ai->pointers[i]);
483     }
484   free (ai->pointers);
485
486   ai->num_references = NULL;
487   BITMAP_XFREE (ai->written_vars);
488   BITMAP_XFREE (ai->dereferenced_ptrs_store);
489   BITMAP_XFREE (ai->dereferenced_ptrs_load);
490
491   free (ai);
492 }
493
494
495 /* Walk use-def chains for pointer PTR to determine what variables is PTR
496    pointing to.  */
497
498 static void
499 collect_points_to_info_for (struct alias_info *ai, tree ptr)
500 {
501 #if defined ENABLE_CHECKING
502   if (!POINTER_TYPE_P (TREE_TYPE (ptr)))
503     abort ();
504 #endif
505
506   if (!bitmap_bit_p (ai->ssa_names_visited, SSA_NAME_VERSION (ptr)))
507     {
508       bitmap_set_bit (ai->ssa_names_visited, SSA_NAME_VERSION (ptr));
509       walk_use_def_chains (ptr, collect_points_to_info_r, ai, true);
510       VARRAY_PUSH_TREE (ai->processed_ptrs, ptr);
511     }
512 }
513
514
515 /* Helper for ptr_is_dereferenced_by.  Called by walk_tree to look for
516    INDIRECT_REF nodes for the pointer passed in DATA.  */
517
518 static tree
519 find_ptr_dereference (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED, void *data)
520 {
521   tree ptr = (tree) data;
522
523   if (TREE_CODE (*tp) == INDIRECT_REF
524       && TREE_OPERAND (*tp, 0) == ptr)
525     return *tp;
526
527   return NULL_TREE;
528 }
529
530
531 /* Return true if STMT contains INDIRECT_REF <PTR>.  *IS_STORE is set
532    to 'true' if the dereference is on the LHS of an assignment.  */
533
534 static bool
535 ptr_is_dereferenced_by (tree ptr, tree stmt, bool *is_store)
536 {
537   *is_store = false;
538
539   if (TREE_CODE (stmt) == MODIFY_EXPR
540       || (TREE_CODE (stmt) == RETURN_EXPR
541           && TREE_CODE (TREE_OPERAND (stmt, 0)) == MODIFY_EXPR))
542     {
543       tree e, lhs, rhs;
544
545       e = (TREE_CODE (stmt) == RETURN_EXPR) ? TREE_OPERAND (stmt, 0) : stmt;
546       lhs = TREE_OPERAND (e, 0);
547       rhs = TREE_OPERAND (e, 1);
548
549       if (EXPR_P (lhs)
550           && walk_tree (&lhs, find_ptr_dereference, ptr, NULL))
551         {
552           *is_store = true;
553           return true;
554         }
555       else if (EXPR_P (rhs)
556                && walk_tree (&rhs, find_ptr_dereference, ptr, NULL))
557         {
558           return true;
559         }
560     }
561   else if (TREE_CODE (stmt) == ASM_EXPR)
562     {
563       if (walk_tree (&ASM_OUTPUTS (stmt), find_ptr_dereference, ptr, NULL)
564           || walk_tree (&ASM_CLOBBERS (stmt), find_ptr_dereference, ptr, NULL))
565         {
566           *is_store = true;
567           return true;
568         }
569       else if (walk_tree (&ASM_INPUTS (stmt), find_ptr_dereference, ptr, NULL))
570         {
571           return true;
572         }
573     }
574
575   return false;
576 }
577
578
579 /* Traverse use-def links for all the pointers in the program to collect
580    address escape and points-to information.
581    
582    This is loosely based on the same idea described in R. Hasti and S.
583    Horwitz, ``Using static single assignment form to improve
584    flow-insensitive pointer analysis,'' in SIGPLAN Conference on
585    Programming Language Design and Implementation, pp. 97-105, 1998.  */
586
587 static void
588 compute_points_to_and_addr_escape (struct alias_info *ai)
589 {
590   basic_block bb;
591   size_t i;
592
593   timevar_push (TV_TREE_PTA);
594
595   FOR_EACH_BB (bb)
596     {
597       bb_ann_t block_ann = bb_ann (bb);
598       block_stmt_iterator si;
599
600       for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
601         {
602           use_optype uses;
603           def_optype defs;
604           v_may_def_optype v_may_defs;
605           v_must_def_optype v_must_defs;
606           stmt_ann_t ann;
607           bitmap addr_taken;
608           tree stmt = bsi_stmt (si);
609           bool stmt_escapes_p = is_escape_site (stmt, &ai->num_calls_found);
610
611           /* Mark all the variables whose address are taken by the
612              statement.  Note that this will miss all the addresses taken
613              in PHI nodes (those are discovered while following the use-def
614              chains).  */
615           get_stmt_operands (stmt);
616           addr_taken = addresses_taken (stmt);
617           if (addr_taken)
618             EXECUTE_IF_SET_IN_BITMAP (addr_taken, 0, i,
619                 {
620                   tree var = referenced_var (i);
621                   bitmap_set_bit (ai->addresses_needed, var_ann (var)->uid);
622                   if (stmt_escapes_p)
623                     mark_call_clobbered (var);
624                 });
625
626           if (stmt_escapes_p)
627             block_ann->has_escape_site = 1;
628
629           /* Special case for silly ADDR_EXPR tricks
630              (gcc.c-torture/unsorted/pass.c).  If this statement is an
631              assignment to a non-pointer variable and the RHS takes the
632              address of a variable, assume that the variable on the RHS is
633              call-clobbered.  We could add the LHS to the list of
634              "pointers" and follow it to see if it really escapes, but it's
635              not worth the pain.  */
636           if (addr_taken
637               && TREE_CODE (stmt) == MODIFY_EXPR
638               && !POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (stmt, 0))))
639             EXECUTE_IF_SET_IN_BITMAP (addr_taken, 0, i,
640                 {
641                   tree var = referenced_var (i);
642                   mark_call_clobbered (var);
643                 });
644
645           ann = stmt_ann (stmt);
646           uses = USE_OPS (ann);
647           for (i = 0; i < NUM_USES (uses); i++)
648             {
649               tree op = USE_OP (uses, i);
650               var_ann_t v_ann = var_ann (SSA_NAME_VAR (op));
651               struct ptr_info_def *pi;
652               bool is_store;
653
654               /* If the operand's variable may be aliased, keep track
655                  of how many times we've referenced it.  This is used
656                  for alias grouping in compute_flow_sensitive_aliasing.
657                  Note that we don't need to grow AI->NUM_REFERENCES
658                  because we are processing regular variables, not
659                  memory tags (the array's initial size is set to
660                  NUM_REFERENCED_VARS).  */
661               if (may_be_aliased (SSA_NAME_VAR (op)))
662                 (VARRAY_UINT (ai->num_references, v_ann->uid))++;
663
664               if (!POINTER_TYPE_P (TREE_TYPE (op)))
665                 continue;
666
667               collect_points_to_info_for (ai, op);
668
669               pi =  SSA_NAME_PTR_INFO (op);
670               if (ptr_is_dereferenced_by (op, stmt, &is_store))
671                 {
672                   /* If we found OP to point to a set of variables or
673                      malloc, then mark it as being dereferenced.  In a
674                      subsequent pass, dereferenced pointers that point
675                      to a set of variables will be assigned a name tag
676                      to alias all the variables OP points to.  */
677                   if (pi->pt_malloc || pi->pt_vars)
678                     pi->is_dereferenced = 1;
679
680                   /* Keep track of how many time we've dereferenced each
681                      pointer.  Again, we don't need to grow
682                      AI->NUM_REFERENCES because we're processing
683                      existing program variables.  */
684                   (VARRAY_UINT (ai->num_references, v_ann->uid))++;
685
686                   /* If this is a store operation, mark OP as being
687                      dereferenced to store, otherwise mark it as being
688                      dereferenced to load.  */
689                   if (is_store)
690                     bitmap_set_bit (ai->dereferenced_ptrs_store, v_ann->uid);
691                   else
692                     bitmap_set_bit (ai->dereferenced_ptrs_load, v_ann->uid);
693                 }
694               else if (stmt_escapes_p)
695                 {
696                   /* Note that even if STMT is an escape point, pointer OP
697                      will not escape if it is being dereferenced.  That's
698                      why we only check for escape points if OP is not
699                      dereferenced by STMT.  */
700                   pi->value_escapes_p = 1;
701
702                   /* If the statement makes a function call, assume
703                      that pointer OP will be dereferenced in a store
704                      operation inside the called function.  */
705                   if (get_call_expr_in (stmt))
706                     bitmap_set_bit (ai->dereferenced_ptrs_store, v_ann->uid);
707                 }
708             }
709
710           /* Update reference counter for definitions to any
711              potentially aliased variable.  This is used in the alias
712              grouping heuristics.  */
713           defs = DEF_OPS (ann);
714           for (i = 0; i < NUM_DEFS (defs); i++)
715             {
716               tree op = DEF_OP (defs, i);
717               tree var = SSA_NAME_VAR (op);
718               var_ann_t ann = var_ann (var);
719               bitmap_set_bit (ai->written_vars, ann->uid);
720               if (may_be_aliased (var))
721                 (VARRAY_UINT (ai->num_references, ann->uid))++;
722             }
723
724           /* Mark variables in V_MAY_DEF operands as being written to.  */
725           v_may_defs = V_MAY_DEF_OPS (ann);
726           for (i = 0; i < NUM_V_MAY_DEFS (v_may_defs); i++)
727             {
728               tree op = V_MAY_DEF_OP (v_may_defs, i);
729               tree var = SSA_NAME_VAR (op);
730               var_ann_t ann = var_ann (var);
731               bitmap_set_bit (ai->written_vars, ann->uid);
732             }
733             
734           /* Mark variables in V_MUST_DEF operands as being written to.  */
735           v_must_defs = V_MUST_DEF_OPS (ann);
736           for (i = 0; i < NUM_V_MUST_DEFS (v_must_defs); i++)
737             {
738               tree op = V_MUST_DEF_OP (v_must_defs, i);
739               tree var = SSA_NAME_VAR (op);
740               var_ann_t ann = var_ann (var);
741               bitmap_set_bit (ai->written_vars, ann->uid);
742             }
743
744           /* After promoting variables and computing aliasing we will
745              need to re-scan most statements.  FIXME: Try to minimize the
746              number of statements re-scanned.  It's not really necessary to
747              re-scan *all* statements.  */
748           modify_stmt (stmt);
749         }
750     }
751
752   timevar_pop (TV_TREE_PTA);
753 }
754
755
756 /* Create name tags for all the pointers that have been dereferenced.
757    We only create a name tag for a pointer P if P is found to point to
758    a set of variables (so that we can alias them to *P) or if it is
759    the result of a call to malloc (which means that P cannot point to
760    anything else nor alias any other variable).
761
762    If two pointers P and Q point to the same set of variables, they
763    are assigned the same name tag.  */
764
765 static void
766 create_name_tags (struct alias_info *ai)
767 {
768   size_t i;
769
770   for (i = 0; i < VARRAY_ACTIVE_SIZE (ai->processed_ptrs); i++)
771     {
772       tree ptr = VARRAY_TREE (ai->processed_ptrs, i);
773       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
774
775       if (!pi->is_dereferenced)
776         continue;
777
778       if (pi->pt_vars)
779         {
780           size_t j;
781           tree old_name_tag = pi->name_mem_tag;
782
783           /* If PTR points to a set of variables, check if we don't
784              have another pointer Q with the same points-to set before
785              creating a tag.  If so, use Q's tag instead of creating a
786              new one.
787
788              This is important for not creating unnecessary symbols
789              and also for copy propagation.  If we ever need to
790              propagate PTR into Q or vice-versa, we would run into
791              problems if they both had different name tags because
792              they would have different SSA version numbers (which
793              would force us to take the name tags in and out of SSA).  */
794           for (j = 0; j < i; j++)
795             {
796               tree q = VARRAY_TREE (ai->processed_ptrs, j);
797               struct ptr_info_def *qi = SSA_NAME_PTR_INFO (q);
798
799               if (qi
800                   && qi->pt_vars
801                   && qi->name_mem_tag
802                   && bitmap_equal_p (pi->pt_vars, qi->pt_vars))
803                 {
804                   pi->name_mem_tag = qi->name_mem_tag;
805                   break;
806                 }
807             }
808
809           /* If we didn't find a pointer with the same points-to set
810              as PTR, create a new name tag if needed.  */
811           if (pi->name_mem_tag == NULL_TREE)
812             pi->name_mem_tag = get_nmt_for (ptr);
813
814           /* If the new name tag computed for PTR is different than
815              the old name tag that it used to have, then the old tag
816              needs to be removed from the IL, so we mark it for
817              renaming.  */
818           if (old_name_tag && old_name_tag != pi->name_mem_tag)
819             bitmap_set_bit (vars_to_rename, var_ann (old_name_tag)->uid);
820         }
821       else if (pi->pt_malloc)
822         {
823           /* Otherwise, create a unique name tag for this pointer.  */
824           pi->name_mem_tag = get_nmt_for (ptr);
825         }
826       else
827         {
828           /* Only pointers that may point to malloc or other variables
829              may receive a name tag.  If the pointer does not point to
830              a known spot, we should use type tags.  */
831           abort ();
832         }
833
834       /* Mark the new name tag for renaming.  */
835       bitmap_set_bit (vars_to_rename, var_ann (pi->name_mem_tag)->uid);
836     }
837 }
838
839
840
841 /* For every pointer P_i in AI->PROCESSED_PTRS, create may-alias sets for
842    the name memory tag (NMT) associated with P_i.  If P_i escapes, then its
843    name tag and the variables it points-to are call-clobbered.  Finally, if
844    P_i escapes and we could not determine where it points to, then all the
845    variables in the same alias set as *P_i are marked call-clobbered.  This
846    is necessary because we must assume that P_i may take the address of any
847    variable in the same alias set.  */
848
849 static void
850 compute_flow_sensitive_aliasing (struct alias_info *ai)
851 {
852   size_t i;
853
854   create_name_tags (ai);
855
856   for (i = 0; i < VARRAY_ACTIVE_SIZE (ai->processed_ptrs); i++)
857     {
858       size_t j;
859       tree ptr = VARRAY_TREE (ai->processed_ptrs, i);
860       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
861       var_ann_t v_ann = var_ann (SSA_NAME_VAR (ptr));
862
863       if (pi->value_escapes_p || pi->pt_anything)
864         {
865           /* If PTR escapes or may point to anything, then its associated
866              memory tags are call-clobbered.  */
867           if (pi->name_mem_tag)
868             mark_call_clobbered (pi->name_mem_tag);
869
870           if (v_ann->type_mem_tag)
871             mark_call_clobbered (v_ann->type_mem_tag);
872
873           /* If PTR may point to anything, mark call-clobbered all the
874              addressables with the same alias set as the type pointed-to by
875              PTR.  */
876           if (pi->pt_anything)
877             {
878               HOST_WIDE_INT ptr_set;
879               ptr_set = get_alias_set (TREE_TYPE (TREE_TYPE (ptr)));
880               for (j = 0; j < ai->num_addressable_vars; j++)
881                 {
882                   struct alias_map_d *alias_map = ai->addressable_vars[j];
883                   if (alias_map->set == ptr_set)
884                     mark_call_clobbered (alias_map->var);
885                 }
886             }
887
888           /* If PTR's value may escape and PTR is never dereferenced, we
889              need to mark all the variables PTR points-to as
890              call-clobbered.  Note that we only need do this it PTR is
891              never dereferenced.  If PTR is dereferenced, it will have a
892              name memory tag, which will have been marked call-clobbered.
893              This will in turn mark the pointed-to variables as
894              call-clobbered when we call add_may_alias below.  */
895           if (pi->value_escapes_p
896               && pi->name_mem_tag == NULL_TREE
897               && pi->pt_vars)
898             EXECUTE_IF_SET_IN_BITMAP (pi->pt_vars, 0, j,
899                 mark_call_clobbered (referenced_var (j)));
900         }
901
902       /* Set up aliasing information for PTR's name memory tag (if it has
903          one).  Note that only pointers that have been dereferenced will
904          have a name memory tag.  */
905       if (pi->name_mem_tag && pi->pt_vars)
906         EXECUTE_IF_SET_IN_BITMAP (pi->pt_vars, 0, j,
907             add_may_alias (pi->name_mem_tag, referenced_var (j)));
908
909       /* If the name tag is call clobbered, so is the type tag
910          associated with the base VAR_DECL.  */
911       if (pi->name_mem_tag
912           && v_ann->type_mem_tag
913           && is_call_clobbered (pi->name_mem_tag))
914         mark_call_clobbered (v_ann->type_mem_tag);
915     }
916 }
917
918
919 /* Compute type-based alias sets.  Traverse all the pointers and
920    addressable variables found in setup_pointers_and_addressables.
921    
922    For every pointer P in AI->POINTERS and addressable variable V in
923    AI->ADDRESSABLE_VARS, add V to the may-alias sets of P's type
924    memory tag (TMT) if their alias sets conflict.  V is then marked as
925    an alias tag so that the operand scanner knows that statements
926    containing V have aliased operands.  */
927
928 static void
929 compute_flow_insensitive_aliasing (struct alias_info *ai)
930 {
931   size_t i;
932
933   /* Initialize counter for the total number of virtual operands that
934      aliasing will introduce.  When AI->TOTAL_ALIAS_VOPS goes beyond the
935      threshold set by --params max-alias-vops, we enable alias
936      grouping.  */
937   ai->total_alias_vops = 0;
938
939   /* For every pointer P, determine which addressable variables may alias
940      with P's type memory tag.  */
941   for (i = 0; i < ai->num_pointers; i++)
942     {
943       size_t j;
944       struct alias_map_d *p_map = ai->pointers[i];
945       tree tag = var_ann (p_map->var)->type_mem_tag;
946       var_ann_t tag_ann = var_ann (tag);
947
948       p_map->total_alias_vops = 0;
949       p_map->may_aliases = sbitmap_alloc (num_referenced_vars);
950       sbitmap_zero (p_map->may_aliases);
951
952       for (j = 0; j < ai->num_addressable_vars; j++)
953         {
954           struct alias_map_d *v_map;
955           var_ann_t v_ann;
956           tree var;
957           bool tag_stored_p, var_stored_p;
958           
959           v_map = ai->addressable_vars[j];
960           var = v_map->var;
961           v_ann = var_ann (var);
962
963           /* Skip memory tags and variables that have never been
964              written to.  We also need to check if the variables are
965              call-clobbered because they may be overwritten by
966              function calls.  */
967           tag_stored_p = bitmap_bit_p (ai->written_vars, tag_ann->uid)
968                          || is_call_clobbered (tag);
969           var_stored_p = bitmap_bit_p (ai->written_vars, v_ann->uid)
970                          || is_call_clobbered (var);
971           if (!tag_stored_p && !var_stored_p)
972             continue;
973              
974           if (may_alias_p (p_map->var, p_map->set, var, v_map->set))
975             {
976               size_t num_tag_refs, num_var_refs;
977
978               num_tag_refs = VARRAY_UINT (ai->num_references, tag_ann->uid);
979               num_var_refs = VARRAY_UINT (ai->num_references, v_ann->uid);
980
981               /* Add VAR to TAG's may-aliases set.  */
982               add_may_alias (tag, var);
983
984               /* Update the total number of virtual operands due to
985                  aliasing.  Since we are adding one more alias to TAG's
986                  may-aliases set, the total number of virtual operands due
987                  to aliasing will be increased by the number of references
988                  made to VAR and TAG (every reference to TAG will also
989                  count as a reference to VAR).  */
990               ai->total_alias_vops += (num_var_refs + num_tag_refs);
991               p_map->total_alias_vops += (num_var_refs + num_tag_refs);
992
993               /* Update the bitmap used to represent TAG's alias set
994                  in case we need to group aliases.  */
995               SET_BIT (p_map->may_aliases, var_ann (var)->uid);
996             }
997         }
998     }
999
1000   if (dump_file)
1001     fprintf (dump_file, "%s: Total number of aliased vops: %ld\n",
1002              get_name (current_function_decl),
1003              ai->total_alias_vops);
1004
1005   /* Determine if we need to enable alias grouping.  */
1006   if (ai->total_alias_vops >= MAX_ALIASED_VOPS)
1007     group_aliases (ai);
1008 }
1009
1010
1011 /* Comparison function for qsort used in group_aliases.  */
1012
1013 static int
1014 total_alias_vops_cmp (const void *p, const void *q)
1015 {
1016   const struct alias_map_d **p1 = (const struct alias_map_d **)p;
1017   const struct alias_map_d **p2 = (const struct alias_map_d **)q;
1018   long n1 = (*p1)->total_alias_vops;
1019   long n2 = (*p2)->total_alias_vops;
1020
1021   /* We want to sort in descending order.  */
1022   return (n1 > n2 ? -1 : (n1 == n2) ? 0 : 1);
1023 }
1024
1025 /* Group all the aliases for TAG to make TAG represent all the
1026    variables in its alias set.  Update the total number
1027    of virtual operands due to aliasing (AI->TOTAL_ALIAS_VOPS).  This
1028    function will make TAG be the unique alias tag for all the
1029    variables in its may-aliases.  So, given:
1030
1031         may-aliases(TAG) = { V1, V2, V3 }
1032
1033    This function will group the variables into:
1034
1035         may-aliases(V1) = { TAG }
1036         may-aliases(V2) = { TAG }
1037         may-aliases(V2) = { TAG }  */
1038
1039 static void
1040 group_aliases_into (tree tag, sbitmap tag_aliases, struct alias_info *ai)
1041 {
1042   size_t i;
1043   var_ann_t tag_ann = var_ann (tag);
1044   size_t num_tag_refs = VARRAY_UINT (ai->num_references, tag_ann->uid);
1045
1046   EXECUTE_IF_SET_IN_SBITMAP (tag_aliases, 0, i,
1047     {
1048       tree var = referenced_var (i);
1049       var_ann_t ann = var_ann (var);
1050
1051       /* Make TAG the unique alias of VAR.  */
1052       ann->is_alias_tag = 0;
1053       ann->may_aliases = NULL;
1054
1055       /* Note that VAR and TAG may be the same if the function has no
1056          addressable variables (see the discussion at the end of
1057          setup_pointers_and_addressables).  */
1058       if (var != tag)
1059         add_may_alias (var, tag);
1060
1061       /* Reduce total number of virtual operands contributed
1062          by TAG on behalf of VAR.  Notice that the references to VAR
1063          itself won't be removed.  We will merely replace them with
1064          references to TAG.  */
1065       ai->total_alias_vops -= num_tag_refs;
1066     });
1067
1068   /* We have reduced the number of virtual operands that TAG makes on
1069      behalf of all the variables formerly aliased with it.  However,
1070      we have also "removed" all the virtual operands for TAG itself,
1071      so we add them back.  */
1072   ai->total_alias_vops += num_tag_refs;
1073
1074   /* TAG no longer has any aliases.  */
1075   tag_ann->may_aliases = NULL;
1076 }
1077
1078
1079 /* Group may-aliases sets to reduce the number of virtual operands due
1080    to aliasing.
1081
1082      1- Sort the list of pointers in decreasing number of contributed
1083         virtual operands.
1084
1085      2- Take the first entry in AI->POINTERS and revert the role of
1086         the memory tag and its aliases.  Usually, whenever an aliased
1087         variable Vi is found to alias with a memory tag T, we add Vi
1088         to the may-aliases set for T.  Meaning that after alias
1089         analysis, we will have:
1090
1091                 may-aliases(T) = { V1, V2, V3, ..., Vn }
1092
1093         This means that every statement that references T, will get 'n'
1094         virtual operands for each of the Vi tags.  But, when alias
1095         grouping is enabled, we make T an alias tag and add it to the
1096         alias set of all the Vi variables:
1097
1098                 may-aliases(V1) = { T }
1099                 may-aliases(V2) = { T }
1100                 ...
1101                 may-aliases(Vn) = { T }
1102
1103         This has two effects: (a) statements referencing T will only get
1104         a single virtual operand, and, (b) all the variables Vi will now
1105         appear to alias each other.  So, we lose alias precision to
1106         improve compile time.  But, in theory, a program with such a high
1107         level of aliasing should not be very optimizable in the first
1108         place.
1109
1110      3- Since variables may be in the alias set of more than one
1111         memory tag, the grouping done in step (2) needs to be extended
1112         to all the memory tags that have a non-empty intersection with
1113         the may-aliases set of tag T.  For instance, if we originally
1114         had these may-aliases sets:
1115
1116                 may-aliases(T) = { V1, V2, V3 }
1117                 may-aliases(R) = { V2, V4 }
1118
1119         In step (2) we would have reverted the aliases for T as:
1120
1121                 may-aliases(V1) = { T }
1122                 may-aliases(V2) = { T }
1123                 may-aliases(V3) = { T }
1124
1125         But note that now V2 is no longer aliased with R.  We could
1126         add R to may-aliases(V2), but we are in the process of
1127         grouping aliases to reduce virtual operands so what we do is
1128         add V4 to the grouping to obtain:
1129
1130                 may-aliases(V1) = { T }
1131                 may-aliases(V2) = { T }
1132                 may-aliases(V3) = { T }
1133                 may-aliases(V4) = { T }
1134
1135      4- If the total number of virtual operands due to aliasing is
1136         still above the threshold set by max-alias-vops, go back to (2).  */
1137
1138 static void
1139 group_aliases (struct alias_info *ai)
1140 {
1141   size_t i;
1142   sbitmap res;
1143
1144   /* Sort the POINTERS array in descending order of contributed
1145      virtual operands.  */
1146   qsort (ai->pointers, ai->num_pointers, sizeof (struct alias_map_d *),
1147          total_alias_vops_cmp);
1148
1149   res = sbitmap_alloc (num_referenced_vars);
1150
1151   /* For every pointer in AI->POINTERS, reverse the roles of its tag
1152      and the tag's may-aliases set.  */
1153   for (i = 0; i < ai->num_pointers; i++)
1154     {
1155       size_t j;
1156       tree tag1 = var_ann (ai->pointers[i]->var)->type_mem_tag;
1157       sbitmap tag1_aliases = ai->pointers[i]->may_aliases;
1158
1159       /* Skip tags that have been grouped already.  */
1160       if (ai->pointers[i]->grouped_p)
1161         continue;
1162
1163       /* See if TAG1 had any aliases in common with other type tags.
1164          If we find a TAG2 with common aliases with TAG1, add TAG2's
1165          aliases into TAG1.  */
1166       for (j = i + 1; j < ai->num_pointers; j++)
1167         {
1168           sbitmap tag2_aliases = ai->pointers[j]->may_aliases;
1169
1170           sbitmap_a_and_b (res, tag1_aliases, tag2_aliases);
1171           if (sbitmap_first_set_bit (res) >= 0)
1172             {
1173               tree tag2 = var_ann (ai->pointers[j]->var)->type_mem_tag;
1174
1175               sbitmap_a_or_b (tag1_aliases, tag1_aliases, tag2_aliases);
1176
1177               /* TAG2 does not need its aliases anymore.  */
1178               sbitmap_zero (tag2_aliases);
1179               var_ann (tag2)->may_aliases = NULL;
1180
1181               /* TAG1 is the unique alias of TAG2.  */
1182               add_may_alias (tag2, tag1);
1183
1184               ai->pointers[j]->grouped_p = true;
1185             }
1186         }
1187
1188       /* Now group all the aliases we collected into TAG1.  */
1189       group_aliases_into (tag1, tag1_aliases, ai);
1190
1191       /* If we've reduced total number of virtual operands below the
1192          threshold, stop.  */
1193       if (ai->total_alias_vops < MAX_ALIASED_VOPS)
1194         break;
1195     }
1196
1197   /* Finally, all the variables that have been grouped cannot be in
1198      the may-alias set of name memory tags.  Suppose that we have
1199      grouped the aliases in this code so that may-aliases(a) = TMT.20
1200
1201         p_5 = &a;
1202         ...
1203         # a_9 = V_MAY_DEF <a_8>
1204         p_5->field = 0
1205         ... Several modifications to TMT.20 ... 
1206         # VUSE <a_9>
1207         x_30 = p_5->field
1208
1209      Since p_5 points to 'a', the optimizers will try to propagate 0
1210      into p_5->field, but that is wrong because there have been
1211      modifications to 'TMT.20' in between.  To prevent this we have to
1212      replace 'a' with 'TMT.20' in the name tag of p_5.  */
1213   for (i = 0; i < VARRAY_ACTIVE_SIZE (ai->processed_ptrs); i++)
1214     {
1215       size_t j;
1216       tree ptr = VARRAY_TREE (ai->processed_ptrs, i);
1217       tree name_tag = SSA_NAME_PTR_INFO (ptr)->name_mem_tag;
1218       varray_type aliases;
1219       
1220       if (name_tag == NULL_TREE)
1221         continue;
1222
1223       aliases = var_ann (name_tag)->may_aliases;
1224       for (j = 0; aliases && j < VARRAY_ACTIVE_SIZE (aliases); j++)
1225         {
1226           tree alias = VARRAY_TREE (aliases, j);
1227           var_ann_t ann = var_ann (alias);
1228
1229           if (ann->mem_tag_kind == NOT_A_TAG && ann->may_aliases)
1230             {
1231               tree new_alias;
1232
1233 #if defined ENABLE_CHECKING
1234               if (VARRAY_ACTIVE_SIZE (ann->may_aliases) != 1)
1235                 abort ();
1236 #endif
1237               new_alias = VARRAY_TREE (ann->may_aliases, 0);
1238               replace_may_alias (name_tag, j, new_alias);
1239             }
1240         }
1241     }
1242
1243   sbitmap_free (res);
1244
1245   if (dump_file)
1246     fprintf (dump_file,
1247              "%s: Total number of aliased vops after grouping: %ld%s\n",
1248              get_name (current_function_decl),
1249              ai->total_alias_vops,
1250              (ai->total_alias_vops < 0) ? " (negative values are OK)" : "");
1251 }
1252
1253
1254 /* Create a new alias set entry for VAR in AI->ADDRESSABLE_VARS.  */
1255
1256 static void
1257 create_alias_map_for (tree var, struct alias_info *ai)
1258 {
1259   struct alias_map_d *alias_map;
1260   alias_map = xcalloc (1, sizeof (*alias_map));
1261   alias_map->var = var;
1262
1263   if (TREE_CODE (TREE_TYPE (var)) == ARRAY_TYPE)
1264     alias_map->set = get_alias_set (TREE_TYPE (TREE_TYPE (var)));
1265   else
1266     alias_map->set = get_alias_set (var);
1267   ai->addressable_vars[ai->num_addressable_vars++] = alias_map;
1268 }
1269
1270
1271 /* Create memory tags for all the dereferenced pointers and build the
1272    ADDRESSABLE_VARS and POINTERS arrays used for building the may-alias
1273    sets.  Based on the address escape and points-to information collected
1274    earlier, this pass will also clear the TREE_ADDRESSABLE flag from those
1275    variables whose address is not needed anymore.  */
1276
1277 static void
1278 setup_pointers_and_addressables (struct alias_info *ai)
1279 {
1280   size_t i, n_vars, num_addressable_vars, num_pointers;
1281
1282   /* Size up the arrays ADDRESSABLE_VARS and POINTERS.  */
1283   num_addressable_vars = num_pointers = 0;
1284   for (i = 0; i < num_referenced_vars; i++)
1285     {
1286       tree var = referenced_var (i);
1287
1288       if (may_be_aliased (var))
1289         num_addressable_vars++;
1290
1291       if (POINTER_TYPE_P (TREE_TYPE (var)))
1292         {
1293           /* Since we don't keep track of volatile variables, assume that
1294              these pointers are used in indirect store operations.  */
1295           if (TREE_THIS_VOLATILE (var))
1296             bitmap_set_bit (ai->dereferenced_ptrs_store, var_ann (var)->uid);
1297
1298           num_pointers++;
1299         }
1300     }
1301
1302   /* Create ADDRESSABLE_VARS and POINTERS.  Note that these arrays are
1303      always going to be slightly bigger than we actually need them
1304      because some TREE_ADDRESSABLE variables will be marked
1305      non-addressable below and only pointers with unique type tags are
1306      going to be added to POINTERS.  */
1307   ai->addressable_vars = xcalloc (num_addressable_vars,
1308                                   sizeof (struct alias_map_d *));
1309   ai->pointers = xcalloc (num_pointers, sizeof (struct alias_map_d *));
1310   ai->num_addressable_vars = 0;
1311   ai->num_pointers = 0;
1312
1313   /* Since we will be creating type memory tags within this loop, cache the
1314      value of NUM_REFERENCED_VARS to avoid processing the additional tags
1315      unnecessarily.  */
1316   n_vars = num_referenced_vars;
1317
1318   for (i = 0; i < n_vars; i++)
1319     {
1320       tree var = referenced_var (i);
1321       var_ann_t v_ann = var_ann (var);
1322
1323       /* Name memory tags already have flow-sensitive aliasing
1324          information, so they need not be processed by
1325          compute_may_aliases.  Similarly, type memory tags are already
1326          accounted for when we process their associated pointer.  */
1327       if (v_ann->mem_tag_kind != NOT_A_TAG)
1328         continue;
1329
1330       /* Remove the ADDRESSABLE flag from every addressable variable whose
1331          address is not needed anymore.  This is caused by the propagation
1332          of ADDR_EXPR constants into INDIRECT_REF expressions and the
1333          removal of dead pointer assignments done by the early scalar
1334          cleanup passes.  */
1335       if (TREE_ADDRESSABLE (var))
1336         {
1337           if (!bitmap_bit_p (ai->addresses_needed, v_ann->uid)
1338               && v_ann->mem_tag_kind == NOT_A_TAG
1339               && !needs_to_live_in_memory (var))
1340             {
1341               /* The address of VAR is not needed, remove the
1342                  addressable bit, so that it can be optimized as a
1343                  regular variable.  */
1344               mark_non_addressable (var);
1345
1346               /* Since VAR is now a regular GIMPLE register, we will need
1347                  to rename VAR into SSA afterwards.  */
1348               bitmap_set_bit (vars_to_rename, v_ann->uid);
1349             }
1350           else
1351             {
1352               /* Add the variable to the set of addressables.  Mostly
1353                  used when scanning operands for ASM_EXPRs that
1354                  clobber memory.  In those cases, we need to clobber
1355                  all call-clobbered variables and all addressables.  */
1356               bitmap_set_bit (addressable_vars, v_ann->uid);
1357             }
1358         }
1359
1360       /* Global variables and addressable locals may be aliased.  Create an
1361          entry in ADDRESSABLE_VARS for VAR.  */
1362       if (may_be_aliased (var))
1363         {
1364           create_alias_map_for (var, ai);
1365           bitmap_set_bit (vars_to_rename, var_ann (var)->uid);
1366         }
1367
1368       /* Add pointer variables that have been dereferenced to the POINTERS
1369          array and create a type memory tag for them.  */
1370       if (POINTER_TYPE_P (TREE_TYPE (var))
1371           && (bitmap_bit_p (ai->dereferenced_ptrs_store, v_ann->uid)
1372               || bitmap_bit_p (ai->dereferenced_ptrs_load, v_ann->uid)))
1373         {
1374           tree tag;
1375           var_ann_t t_ann;
1376
1377           /* If pointer VAR still doesn't have a memory tag associated
1378              with it, create it now or re-use an existing one.  */
1379           tag = get_tmt_for (var, ai);
1380           t_ann = var_ann (tag);
1381
1382           /* The type tag will need to be renamed into SSA afterwards.
1383              Note that we cannot do this inside get_tmt_for because
1384              aliasing may run multiple times and we only create type
1385              tags the first time.  */
1386           bitmap_set_bit (vars_to_rename, t_ann->uid);
1387
1388           /* Associate the tag with pointer VAR.  */
1389           v_ann->type_mem_tag = tag;
1390
1391           /* If pointer VAR has been used in a store operation, then its
1392              memory tag must be marked as written-to.  */
1393           if (bitmap_bit_p (ai->dereferenced_ptrs_store, v_ann->uid))
1394             bitmap_set_bit (ai->written_vars, t_ann->uid);
1395
1396           /* If pointer VAR is a global variable or a PARM_DECL, then its
1397              memory tag should be considered a global variable.  */
1398           if (TREE_CODE (var) == PARM_DECL || needs_to_live_in_memory (var))
1399             mark_call_clobbered (tag);
1400
1401           /* All the dereferences of pointer VAR count as references of
1402              TAG.  Since TAG can be associated with several pointers, add
1403              the dereferences of VAR to the TAG.  We may need to grow
1404              AI->NUM_REFERENCES because we have been adding name and
1405              type tags.  */
1406           if (t_ann->uid >= VARRAY_SIZE (ai->num_references))
1407             VARRAY_GROW (ai->num_references, t_ann->uid + 10);
1408
1409           VARRAY_UINT (ai->num_references, t_ann->uid)
1410               += VARRAY_UINT (ai->num_references, v_ann->uid);
1411         }
1412     }
1413
1414   /* If we found no addressable variables, but we have more than one
1415      pointer, we will need to check for conflicts between the
1416      pointers.  Otherwise, we would miss alias relations as in
1417      testsuite/gcc.dg/tree-ssa/20040319-1.c:
1418
1419                 struct bar { int count;  int *arr;};
1420
1421                 void foo (struct bar *b)
1422                 {
1423                   b->count = 0;
1424                   *(b->arr) = 2;
1425                   if (b->count == 0)
1426                     abort ();
1427                 }
1428
1429      b->count and *(b->arr) could be aliased if b->arr == &b->count.
1430      To do this, we add all the memory tags for the pointers in
1431      AI->POINTERS to AI->ADDRESSABLE_VARS, so that
1432      compute_flow_insensitive_aliasing will naturally compare every
1433      pointer to every type tag.  */
1434   if (ai->num_addressable_vars == 0
1435       && ai->num_pointers > 1)
1436     {
1437       free (ai->addressable_vars);
1438       ai->addressable_vars = xcalloc (ai->num_pointers,
1439                                       sizeof (struct alias_map_d *));
1440       ai->num_addressable_vars = 0;
1441       for (i = 0; i < ai->num_pointers; i++)
1442         {
1443           struct alias_map_d *p = ai->pointers[i];
1444           tree tag = var_ann (p->var)->type_mem_tag;
1445           create_alias_map_for (tag, ai);
1446         }
1447     }
1448 }
1449
1450
1451 /* Determine whether to use .GLOBAL_VAR to model call clobbering semantics. At
1452    every call site, we need to emit V_MAY_DEF expressions to represent the
1453    clobbering effects of the call for variables whose address escapes the
1454    current function.
1455
1456    One approach is to group all call-clobbered variables into a single
1457    representative that is used as an alias of every call-clobbered variable
1458    (.GLOBAL_VAR).  This works well, but it ties the optimizer hands because
1459    references to any call clobbered variable is a reference to .GLOBAL_VAR.
1460
1461    The second approach is to emit a clobbering V_MAY_DEF for every 
1462    call-clobbered variable at call sites.  This is the preferred way in terms 
1463    of optimization opportunities but it may create too many V_MAY_DEF operands
1464    if there are many call clobbered variables and function calls in the 
1465    function.
1466
1467    To decide whether or not to use .GLOBAL_VAR we multiply the number of
1468    function calls found by the number of call-clobbered variables.  If that
1469    product is beyond a certain threshold, as determined by the parameterized
1470    values shown below, we use .GLOBAL_VAR.
1471
1472    FIXME.  This heuristic should be improved.  One idea is to use several
1473    .GLOBAL_VARs of different types instead of a single one.  The thresholds
1474    have been derived from a typical bootstrap cycle, including all target
1475    libraries. Compile times were found increase by ~1% compared to using
1476    .GLOBAL_VAR.  */
1477
1478 static void
1479 maybe_create_global_var (struct alias_info *ai)
1480 {
1481   size_t i, n_clobbered;
1482   
1483   /* No need to create it, if we have one already.  */
1484   if (global_var)
1485     return;
1486
1487   /* Count all the call-clobbered variables.  */
1488   n_clobbered = 0;
1489   EXECUTE_IF_SET_IN_BITMAP (call_clobbered_vars, 0, i, n_clobbered++);
1490
1491   /* Create .GLOBAL_VAR if we have too many call-clobbered variables.
1492      We also create .GLOBAL_VAR when there no call-clobbered variables
1493      to prevent code motion transformations from re-arranging function
1494      calls that may have side effects.  For instance,
1495
1496                 foo ()
1497                 {
1498                   int a = f ();
1499                   g ();
1500                   h (a);
1501                 }
1502
1503      There are no call-clobbered variables in foo(), so it would be
1504      entirely possible for a pass to want to move the call to f()
1505      after the call to g().  If f() has side effects, that would be
1506      wrong.  Creating .GLOBAL_VAR in this case will insert VDEFs for
1507      it and prevent such transformations.  */
1508   if (n_clobbered == 0
1509       || ai->num_calls_found * n_clobbered >= (size_t) GLOBAL_VAR_THRESHOLD)
1510     create_global_var ();
1511
1512   /* If the function has calls to clobbering functions and .GLOBAL_VAR has
1513      been created, make it an alias for all call-clobbered variables.  */
1514   if (global_var)
1515     EXECUTE_IF_SET_IN_BITMAP (call_clobbered_vars, 0, i,
1516       {
1517         tree var = referenced_var (i);
1518         if (var != global_var)
1519           {
1520              add_may_alias (var, global_var);
1521              bitmap_set_bit (vars_to_rename, var_ann (var)->uid);
1522           }
1523       });
1524 }
1525
1526
1527 /* Return TRUE if pointer PTR may point to variable VAR.
1528    
1529    MEM_ALIAS_SET is the alias set for the memory location pointed-to by PTR
1530         This is needed because when checking for type conflicts we are
1531         interested in the alias set of the memory location pointed-to by
1532         PTR.  The alias set of PTR itself is irrelevant.
1533    
1534    VAR_ALIAS_SET is the alias set for VAR.  */
1535
1536 static bool
1537 may_alias_p (tree ptr, HOST_WIDE_INT mem_alias_set,
1538              tree var, HOST_WIDE_INT var_alias_set)
1539 {
1540   tree mem;
1541   var_ann_t v_ann, m_ann;
1542
1543   alias_stats.alias_queries++;
1544   alias_stats.simple_queries++;
1545
1546   /* By convention, a variable cannot alias itself.  */
1547   mem = var_ann (ptr)->type_mem_tag;
1548   if (mem == var)
1549     {
1550       alias_stats.alias_noalias++;
1551       alias_stats.simple_resolved++;
1552       return false;
1553     }
1554
1555   v_ann = var_ann (var);
1556   m_ann = var_ann (mem);
1557
1558 #if defined ENABLE_CHECKING
1559   if (m_ann->mem_tag_kind != TYPE_TAG)
1560     abort ();
1561 #endif
1562
1563   alias_stats.tbaa_queries++;
1564
1565   /* If VAR is a pointer with the same alias set as PTR, then dereferencing
1566      PTR can't possibly affect VAR.  Note, that we are specifically testing
1567      for PTR's alias set here, not its pointed-to type.  We also can't
1568      do this check with relaxed aliasing enabled.  */
1569   if (POINTER_TYPE_P (TREE_TYPE (var))
1570       && var_alias_set != 0)
1571     {
1572       HOST_WIDE_INT ptr_alias_set = get_alias_set (ptr);
1573       if (ptr_alias_set == var_alias_set)
1574         {
1575           alias_stats.alias_noalias++;
1576           alias_stats.tbaa_resolved++;
1577           return false;
1578         }
1579     }
1580
1581   /* If the alias sets don't conflict then MEM cannot alias VAR.  */
1582   if (!alias_sets_conflict_p (mem_alias_set, var_alias_set))
1583     {
1584       /* Handle aliases to structure fields.  If either VAR or MEM are
1585          aggregate types, they may not have conflicting types, but one of
1586          the structures could contain a pointer to the other one.
1587
1588          For instance, given
1589
1590                 MEM -> struct P *p;
1591                 VAR -> struct Q *q;
1592
1593          It may happen that '*p' and '*q' can't alias because 'struct P'
1594          and 'struct Q' have non-conflicting alias sets.  However, it could
1595          happen that one of the fields in 'struct P' is a 'struct Q *' or
1596          vice-versa.
1597
1598          Therefore, we also need to check if 'struct P' aliases 'struct Q *'
1599          or 'struct Q' aliases 'struct P *'.  Notice, that since GIMPLE
1600          does not have more than one-level pointers, we don't need to
1601          recurse into the structures.  */
1602       if (AGGREGATE_TYPE_P (TREE_TYPE (mem))
1603           || AGGREGATE_TYPE_P (TREE_TYPE (var)))
1604         {
1605           tree ptr_to_var;
1606           
1607           if (TREE_CODE (TREE_TYPE (var)) == ARRAY_TYPE)
1608             ptr_to_var = TYPE_POINTER_TO (TREE_TYPE (TREE_TYPE (var)));
1609           else
1610             ptr_to_var = TYPE_POINTER_TO (TREE_TYPE (var));
1611
1612           /* If no pointer-to VAR exists, then MEM can't alias VAR.  */
1613           if (ptr_to_var == NULL_TREE)
1614             {
1615               alias_stats.alias_noalias++;
1616               alias_stats.tbaa_resolved++;
1617               return false;
1618             }
1619
1620           /* If MEM doesn't alias a pointer to VAR and VAR doesn't alias
1621              PTR, then PTR can't alias VAR.  */
1622           if (!alias_sets_conflict_p (mem_alias_set, get_alias_set (ptr_to_var))
1623               && !alias_sets_conflict_p (var_alias_set, get_alias_set (ptr)))
1624             {
1625               alias_stats.alias_noalias++;
1626               alias_stats.tbaa_resolved++;
1627               return false;
1628             }
1629         }
1630       else
1631         {
1632           alias_stats.alias_noalias++;
1633           alias_stats.tbaa_resolved++;
1634           return false;
1635         }
1636     }
1637
1638   if (flag_tree_points_to != PTA_NONE)
1639       alias_stats.pta_queries++;
1640
1641   /* If -ftree-points-to is given, check if PTR may point to VAR.  */
1642   if (flag_tree_points_to == PTA_ANDERSEN
1643       && !ptr_may_alias_var (ptr, var))
1644     {
1645       alias_stats.alias_noalias++;
1646       alias_stats.pta_resolved++;
1647       return false;
1648     }
1649
1650   alias_stats.alias_mayalias++;
1651   return true;
1652 }
1653
1654
1655 /* Add ALIAS to the set of variables that may alias VAR.  */
1656
1657 static void
1658 add_may_alias (tree var, tree alias)
1659 {
1660   size_t i;
1661   var_ann_t v_ann = get_var_ann (var);
1662   var_ann_t a_ann = get_var_ann (alias);
1663
1664 #if defined ENABLE_CHECKING
1665   if (var == alias)
1666     abort ();
1667 #endif
1668
1669   if (v_ann->may_aliases == NULL)
1670     VARRAY_TREE_INIT (v_ann->may_aliases, 2, "aliases");
1671
1672   /* Avoid adding duplicates.  */
1673   for (i = 0; i < VARRAY_ACTIVE_SIZE (v_ann->may_aliases); i++)
1674     if (alias == VARRAY_TREE (v_ann->may_aliases, i))
1675       return;
1676
1677   /* If VAR is a call-clobbered variable, so is its new ALIAS.  */
1678   if (is_call_clobbered (var))
1679     mark_call_clobbered (alias);
1680
1681   /* Likewise.  If ALIAS is call-clobbered, so is VAR.  */
1682   else if (is_call_clobbered (alias))
1683     mark_call_clobbered (var);
1684
1685   VARRAY_PUSH_TREE (v_ann->may_aliases, alias);
1686   a_ann->is_alias_tag = 1;
1687 }
1688
1689
1690 /* Replace alias I in the alias sets of VAR with NEW_ALIAS.  */
1691
1692 static void
1693 replace_may_alias (tree var, size_t i, tree new_alias)
1694 {
1695   var_ann_t v_ann = var_ann (var);
1696   VARRAY_TREE (v_ann->may_aliases, i) = new_alias;
1697
1698   /* If VAR is a call-clobbered variable, so is NEW_ALIAS.  */
1699   if (is_call_clobbered (var))
1700     mark_call_clobbered (new_alias);
1701
1702   /* Likewise.  If NEW_ALIAS is call-clobbered, so is VAR.  */
1703   else if (is_call_clobbered (new_alias))
1704     mark_call_clobbered (var);
1705 }
1706
1707
1708 /* Mark pointer PTR as pointing to an arbitrary memory location.  */
1709
1710 static void
1711 set_pt_anything (tree ptr)
1712 {
1713   struct ptr_info_def *pi = get_ptr_info (ptr);
1714
1715   pi->pt_anything = 1;
1716   pi->pt_malloc = 0;
1717   pi->pt_vars = NULL;
1718   pi->is_dereferenced = 0;
1719
1720   /* The pointer used to have a name tag, but we now found it pointing
1721      to an arbitrary location.  The name tag needs to be renamed and
1722      disassociated from PTR.  */
1723   if (pi->name_mem_tag)
1724     {
1725       bitmap_set_bit (vars_to_rename, var_ann (pi->name_mem_tag)->uid);
1726       pi->name_mem_tag = NULL_TREE;
1727     }
1728 }
1729
1730
1731 /* Mark pointer PTR as pointing to a malloc'd memory area.  */
1732
1733 static void
1734 set_pt_malloc (tree ptr)
1735 {
1736   struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
1737
1738   /* If the pointer has already been found to point to arbitrary
1739      memory locations, it is unsafe to mark it as pointing to malloc. */
1740   if (pi->pt_anything)
1741     return;
1742
1743   pi->pt_malloc = 1;
1744 }
1745
1746
1747 /* Given two pointers DEST and ORIG.  Merge the points-to information in
1748    ORIG into DEST.  AI is as in collect_points_to_info.  */
1749
1750 static void
1751 merge_pointed_to_info (struct alias_info *ai, tree dest, tree orig)
1752 {
1753   struct ptr_info_def *dest_pi, *orig_pi;
1754
1755   /* Make sure we have points-to information for ORIG.  */
1756   collect_points_to_info_for (ai, orig);
1757
1758   dest_pi = get_ptr_info (dest);
1759   orig_pi = SSA_NAME_PTR_INFO (orig);
1760
1761   if (orig_pi)
1762     {
1763       /* Notice that we never merge PT_MALLOC.  This attribute is only
1764          true if the pointer is the result of a malloc() call.
1765          Otherwise, we can end up in this situation:
1766
1767          P_i = malloc ();
1768          ...
1769          P_j = P_i + X;
1770
1771          P_j would be marked as PT_MALLOC, which is wrong because
1772          PT_MALLOC implies that the pointer may not point to another
1773          variable.
1774
1775          FIXME 1: Subsequent analysis may determine that P_j
1776          cannot alias anything else, but we are being conservative
1777          here.
1778
1779          FIXME 2: If the merging comes from a copy assignment, we
1780          ought to merge PT_MALLOC, but then both pointers would end up
1781          getting different name tags because create_name_tags is not
1782          smart enough to determine that the two come from the same
1783          malloc call.  Copy propagation before aliasing should cure
1784          this.  */
1785       dest_pi->pt_malloc = 0;
1786
1787       if (orig_pi->pt_malloc || orig_pi->pt_anything)
1788         set_pt_anything (dest);
1789
1790       if (!dest_pi->pt_anything
1791           && orig_pi->pt_vars
1792           && bitmap_first_set_bit (orig_pi->pt_vars) >= 0)
1793         {
1794           if (dest_pi->pt_vars == NULL)
1795             {
1796               dest_pi->pt_vars = BITMAP_GGC_ALLOC ();
1797               bitmap_copy (dest_pi->pt_vars, orig_pi->pt_vars);
1798             }
1799           else
1800             bitmap_a_or_b (dest_pi->pt_vars,
1801                            dest_pi->pt_vars,
1802                            orig_pi->pt_vars);
1803         }
1804     }
1805 }
1806
1807
1808 /* Add VALUE to the list of expressions pointed-to by PTR.  */
1809
1810 static void
1811 add_pointed_to_expr (tree ptr, tree value)
1812 {
1813   if (TREE_CODE (value) == WITH_SIZE_EXPR)
1814     value = TREE_OPERAND (value, 0);
1815
1816 #if defined ENABLE_CHECKING
1817   /* Pointer variables should have been handled by merge_pointed_to_info.  */
1818   if (TREE_CODE (value) == SSA_NAME
1819       && POINTER_TYPE_P (TREE_TYPE (value)))
1820     abort ();
1821 #endif
1822
1823   get_ptr_info (ptr);
1824
1825   /* If VALUE is the result of a malloc-like call, then the area pointed to
1826      PTR is guaranteed to not alias with anything else.  */
1827   if (TREE_CODE (value) == CALL_EXPR
1828       && (call_expr_flags (value) & (ECF_MALLOC | ECF_MAY_BE_ALLOCA)))
1829     set_pt_malloc (ptr);
1830   else
1831     set_pt_anything (ptr);
1832
1833   if (dump_file)
1834     {
1835       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
1836
1837       fprintf (dump_file, "Pointer ");
1838       print_generic_expr (dump_file, ptr, dump_flags);
1839       fprintf (dump_file, " points to ");
1840       if (pi->pt_malloc)
1841         fprintf (dump_file, "malloc space: ");
1842       else
1843         fprintf (dump_file, "an arbitrary address: ");
1844       print_generic_expr (dump_file, value, dump_flags);
1845       fprintf (dump_file, "\n");
1846     }
1847 }
1848
1849
1850 /* If VALUE is of the form &DECL, add DECL to the set of variables
1851    pointed-to by PTR.  Otherwise, add VALUE as a pointed-to expression by
1852    PTR.  AI is as in collect_points_to_info.  */
1853
1854 static void
1855 add_pointed_to_var (struct alias_info *ai, tree ptr, tree value)
1856 {
1857   struct ptr_info_def *pi = get_ptr_info (ptr);
1858
1859   if (TREE_CODE (value) == ADDR_EXPR)
1860     {
1861       tree pt_var;
1862       size_t uid;
1863
1864       pt_var = TREE_OPERAND (value, 0);
1865       if (TREE_CODE_CLASS (TREE_CODE (pt_var)) == 'r')
1866         pt_var = get_base_address (pt_var);
1867
1868       if (pt_var && SSA_VAR_P (pt_var))
1869         {
1870           uid = var_ann (pt_var)->uid;
1871           bitmap_set_bit (ai->addresses_needed, uid);
1872
1873           /* If PTR has already been found to point anywhere, don't
1874              add the variable to PTR's points-to set.  */
1875           if (!pi->pt_anything)
1876             {
1877               if (pi->pt_vars == NULL)
1878                 pi->pt_vars = BITMAP_GGC_ALLOC ();
1879               bitmap_set_bit (pi->pt_vars, uid);
1880             }
1881         }
1882       else
1883         add_pointed_to_expr (ptr, value);
1884     }
1885   else
1886     add_pointed_to_expr (ptr, value);
1887 }
1888
1889
1890 /* Callback for walk_use_def_chains to gather points-to information from the
1891    SSA web.
1892    
1893    VAR is an SSA variable or a GIMPLE expression.
1894    
1895    STMT is the statement that generates the SSA variable or, if STMT is a
1896       PHI_NODE, VAR is one of the PHI arguments.
1897
1898    DATA is a pointer to a structure of type ALIAS_INFO.  */
1899
1900 static bool
1901 collect_points_to_info_r (tree var, tree stmt, void *data)
1902 {
1903   struct alias_info *ai = (struct alias_info *) data;
1904
1905   if (dump_file && (dump_flags & TDF_DETAILS))
1906     {
1907       fprintf (dump_file, "Visiting use-def links for ");
1908       print_generic_expr (dump_file, var, dump_flags);
1909       fprintf (dump_file, "\n");
1910     }
1911
1912   if (TREE_CODE (stmt) == MODIFY_EXPR)
1913     {
1914       tree rhs = TREE_OPERAND (stmt, 1);
1915       STRIP_NOPS (rhs);
1916
1917       /* Found P_i = CONST.  */
1918       if (is_gimple_min_invariant (rhs))
1919         add_pointed_to_var (ai, var, rhs);
1920
1921       /* Found P_i = Q_j.  */
1922       else if (TREE_CODE (rhs) == SSA_NAME
1923                && POINTER_TYPE_P (TREE_TYPE (rhs)))
1924         merge_pointed_to_info (ai, var, rhs);
1925
1926       /* Found P_i = PLUS_EXPR or P_i = MINUS_EXPR  */
1927       else if (TREE_CODE (rhs) == PLUS_EXPR
1928                || TREE_CODE (rhs) == MINUS_EXPR)
1929         {
1930           tree op0 = TREE_OPERAND (rhs, 0);
1931           tree op1 = TREE_OPERAND (rhs, 1);
1932
1933           if (TREE_CODE (op0) == SSA_NAME
1934               && POINTER_TYPE_P (TREE_TYPE (op0)))
1935             merge_pointed_to_info (ai, var, op0);
1936           else if (TREE_CODE (op1) == SSA_NAME
1937                    && POINTER_TYPE_P (TREE_TYPE (op1)))
1938             merge_pointed_to_info (ai, var, op1);
1939           else if (is_gimple_min_invariant (op0))
1940             add_pointed_to_var (ai, var, op0);
1941           else if (is_gimple_min_invariant (op1))
1942             add_pointed_to_var (ai, var, op1);
1943           else
1944             add_pointed_to_expr (var, rhs);
1945         }
1946
1947       /* Something else.  */
1948       else
1949         add_pointed_to_expr (var, rhs);
1950     }
1951   else if (TREE_CODE (stmt) == ASM_EXPR)
1952     {
1953       /* Pointers defined by __asm__ statements can point anywhere.  */
1954       set_pt_anything (var);
1955     }
1956   else if (IS_EMPTY_STMT (stmt))
1957     {
1958       tree decl = SSA_NAME_VAR (var);
1959
1960       if (TREE_CODE (decl) == PARM_DECL)
1961         add_pointed_to_expr (var, decl);
1962       else if (DECL_INITIAL (decl))
1963         add_pointed_to_var (ai, var, DECL_INITIAL (decl));
1964       else
1965         add_pointed_to_expr (var, decl);
1966     }
1967   else if (TREE_CODE (stmt) == PHI_NODE)
1968     {
1969       /* It STMT is a PHI node, then VAR is one of its arguments.  The
1970          variable that we are analyzing is the LHS of the PHI node.  */
1971       tree lhs = PHI_RESULT (stmt);
1972
1973       if (is_gimple_min_invariant (var))
1974         add_pointed_to_var (ai, lhs, var);
1975       else if (TREE_CODE (var) == SSA_NAME)
1976         {
1977           if (bitmap_bit_p (ai->ssa_names_visited, SSA_NAME_VERSION (var)))
1978             merge_pointed_to_info (ai, lhs, var);
1979           else
1980             set_pt_anything (lhs);
1981         }
1982       else
1983         abort ();
1984     }
1985   else
1986     abort ();
1987
1988   return false;
1989 }
1990
1991
1992 /* Return true if STMT is an "escape" site from the current function.  Escape
1993    sites those statements which might expose the address of a variable
1994    outside the current function.  STMT is an escape site iff:
1995
1996         1- STMT is a function call, or
1997         2- STMT is an __asm__ expression, or
1998         3- STMT is an assignment to a non-local variable, or
1999         4- STMT is a return statement.
2000
2001    If NUM_CALLS_P is not NULL, the counter is incremented if STMT contains
2002    a function call.  */
2003
2004 static bool
2005 is_escape_site (tree stmt, size_t *num_calls_p)
2006 {
2007   if (get_call_expr_in (stmt) != NULL_TREE)
2008     {
2009       if (num_calls_p)
2010         (*num_calls_p)++;
2011
2012       return true;
2013     }
2014   else if (TREE_CODE (stmt) == ASM_EXPR)
2015     return true;
2016   else if (TREE_CODE (stmt) == MODIFY_EXPR)
2017     {
2018       tree lhs = TREE_OPERAND (stmt, 0);
2019
2020       /* Get to the base of _REF nodes.  */
2021       if (TREE_CODE (lhs) != SSA_NAME)
2022         lhs = get_base_address (lhs);
2023
2024       /* If we couldn't recognize the LHS of the assignment, assume that it
2025          is a non-local store.  */
2026       if (lhs == NULL_TREE)
2027         return true;
2028
2029       /* If the LHS is an SSA name, it can't possibly represent a non-local
2030          memory store.  */
2031       if (TREE_CODE (lhs) == SSA_NAME)
2032         return false;
2033
2034       /* FIXME: LHS is not an SSA_NAME.  Even if it's an assignment to a
2035          local variables we cannot be sure if it will escape, because we
2036          don't have information about objects not in SSA form.  Need to
2037          implement something along the lines of
2038
2039          J.-D. Choi, M. Gupta, M. J. Serrano, V. C. Sreedhar, and S. P.
2040          Midkiff, ``Escape analysis for java,'' in Proceedings of the
2041          Conference on Object-Oriented Programming Systems, Languages, and
2042          Applications (OOPSLA), pp. 1-19, 1999.  */
2043       return true;
2044     }
2045   else if (TREE_CODE (stmt) == RETURN_EXPR)
2046     return true;
2047
2048   return false;
2049 }
2050
2051
2052 /* Create a new memory tag of type TYPE.  If IS_TYPE_TAG is true, the tag
2053    is considered to represent all the pointers whose pointed-to types are
2054    in the same alias set class.  Otherwise, the tag represents a single
2055    SSA_NAME pointer variable.  */
2056
2057 static tree
2058 create_memory_tag (tree type, bool is_type_tag)
2059 {
2060   var_ann_t ann;
2061   tree tag = create_tmp_var_raw (type, (is_type_tag) ? "TMT" : "NMT");
2062
2063   /* By default, memory tags are local variables.  Alias analysis will
2064      determine whether they should be considered globals.  */
2065   DECL_CONTEXT (tag) = current_function_decl;
2066
2067   /* If the pointed-to type is volatile, so is the tag.  */
2068   TREE_THIS_VOLATILE (tag) = TREE_THIS_VOLATILE (type);
2069
2070   /* Memory tags are by definition addressable.  This also prevents
2071      is_gimple_ref frome confusing memory tags with optimizable
2072      variables.  */
2073   TREE_ADDRESSABLE (tag) = 1;
2074
2075   ann = get_var_ann (tag);
2076   ann->mem_tag_kind = (is_type_tag) ? TYPE_TAG : NAME_TAG;
2077   ann->type_mem_tag = NULL_TREE;
2078
2079   /* Add the tag to the symbol table.  */
2080   add_referenced_tmp_var (tag);
2081
2082   return tag;
2083 }
2084
2085
2086 /* Create a name memory tag to represent a specific SSA_NAME pointer P_i.
2087    This is used if P_i has been found to point to a specific set of
2088    variables or to a non-aliased memory location like the address returned
2089    by malloc functions.  */
2090
2091 static tree
2092 get_nmt_for (tree ptr)
2093 {
2094   struct ptr_info_def *pi = get_ptr_info (ptr);
2095   tree tag = pi->name_mem_tag;
2096
2097   if (tag == NULL_TREE)
2098     {
2099       tag = create_memory_tag (TREE_TYPE (TREE_TYPE (ptr)), false);
2100
2101       /* If PTR is a PARM_DECL, its memory tag should be considered a
2102          global variable.  */
2103       if (TREE_CODE (SSA_NAME_VAR (ptr)) == PARM_DECL)
2104         mark_call_clobbered (tag);
2105
2106       /* Similarly, if PTR points to malloc, then TAG is a global.  */
2107       if (pi->pt_malloc)
2108         mark_call_clobbered (tag);
2109     }
2110
2111   return tag;
2112 }
2113
2114
2115 /* Return the type memory tag associated to pointer PTR.  A memory tag is an
2116    artificial variable that represents the memory location pointed-to by
2117    PTR.  It is used to model the effects of pointer de-references on
2118    addressable variables.
2119    
2120    AI points to the data gathered during alias analysis.  This function
2121    populates the array AI->POINTERS.  */
2122
2123 static tree
2124 get_tmt_for (tree ptr, struct alias_info *ai)
2125 {
2126   size_t i;
2127   tree tag;
2128   tree tag_type = TREE_TYPE (TREE_TYPE (ptr));
2129   HOST_WIDE_INT tag_set = get_alias_set (tag_type);
2130
2131   /* To avoid creating unnecessary memory tags, only create one memory tag
2132      per alias set class.  Note that it may be tempting to group
2133      memory tags based on conflicting alias sets instead of
2134      equivalence.  That would be wrong because alias sets are not
2135      necessarily transitive (as demonstrated by the libstdc++ test
2136      23_containers/vector/cons/4.cc).  Given three alias sets A, B, C
2137      such that conflicts (A, B) == true and conflicts (A, C) == true,
2138      it does not necessarily follow that conflicts (B, C) == true.  */
2139   for (i = 0, tag = NULL_TREE; i < ai->num_pointers; i++)
2140     {
2141       struct alias_map_d *curr = ai->pointers[i];
2142       if (tag_set == curr->set 
2143           && (flag_tree_points_to == PTA_NONE 
2144               || same_points_to_set (curr->var, ptr)))
2145         {
2146           tag = var_ann (curr->var)->type_mem_tag;
2147           break;
2148         }
2149     }
2150
2151   /* If VAR cannot alias with any of the existing memory tags, create a new
2152      tag for PTR and add it to the POINTERS array.  */
2153   if (tag == NULL_TREE)
2154     {
2155       struct alias_map_d *alias_map;
2156
2157       /* If PTR did not have a type tag already, create a new TMT.*
2158          artificial variable representing the memory location
2159          pointed-to by PTR.  */
2160       if (var_ann (ptr)->type_mem_tag == NULL_TREE)
2161         tag = create_memory_tag (tag_type, true);
2162       else
2163         tag = var_ann (ptr)->type_mem_tag;
2164
2165       /* Add PTR to the POINTERS array.  Note that we are not interested in
2166          PTR's alias set.  Instead, we cache the alias set for the memory that
2167          PTR points to.  */
2168       alias_map = xcalloc (1, sizeof (*alias_map));
2169       alias_map->var = ptr;
2170       alias_map->set = tag_set;
2171       ai->pointers[ai->num_pointers++] = alias_map;
2172     }
2173
2174 #if defined ENABLE_CHECKING
2175   /* Make sure that the type tag has the same alias set as the
2176      pointed-to type.  */
2177   if (tag_set != get_alias_set (tag))
2178     abort ();
2179 #endif
2180
2181
2182   return tag;
2183 }
2184
2185
2186 /* Create GLOBAL_VAR, an artificial global variable to act as a
2187    representative of all the variables that may be clobbered by function
2188    calls.  */
2189
2190 static void
2191 create_global_var (void)
2192 {
2193   global_var = build_decl (VAR_DECL, get_identifier (".GLOBAL_VAR"),
2194                            size_type_node);
2195   DECL_ARTIFICIAL (global_var) = 1;
2196   TREE_READONLY (global_var) = 0;
2197   DECL_EXTERNAL (global_var) = 0;
2198   TREE_STATIC (global_var) = 1;
2199   TREE_USED (global_var) = 1;
2200   DECL_CONTEXT (global_var) = NULL_TREE;
2201   TREE_THIS_VOLATILE (global_var) = 0;
2202   TREE_ADDRESSABLE (global_var) = 0;
2203
2204   add_referenced_tmp_var (global_var);
2205   bitmap_set_bit (vars_to_rename, var_ann (global_var)->uid);
2206 }
2207
2208
2209 /* Dump alias statistics on FILE.  */
2210
2211 static void 
2212 dump_alias_stats (FILE *file)
2213 {
2214   const char *funcname
2215     = lang_hooks.decl_printable_name (current_function_decl, 2);
2216   fprintf (file, "\nAlias statistics for %s\n\n", funcname);
2217   fprintf (file, "Total alias queries:\t%u\n", alias_stats.alias_queries);
2218   fprintf (file, "Total alias mayalias results:\t%u\n", 
2219            alias_stats.alias_mayalias);
2220   fprintf (file, "Total alias noalias results:\t%u\n",
2221            alias_stats.alias_noalias);
2222   fprintf (file, "Total simple queries:\t%u\n",
2223            alias_stats.simple_queries);
2224   fprintf (file, "Total simple resolved:\t%u\n",
2225            alias_stats.simple_resolved);
2226   fprintf (file, "Total TBAA queries:\t%u\n",
2227            alias_stats.tbaa_queries);
2228   fprintf (file, "Total TBAA resolved:\t%u\n",
2229            alias_stats.tbaa_resolved);
2230   fprintf (file, "Total PTA queries:\t%u\n",
2231            alias_stats.pta_queries);
2232   fprintf (file, "Total PTA resolved:\t%u\n",
2233            alias_stats.pta_resolved);
2234 }
2235   
2236
2237 /* Dump alias information on FILE.  */
2238
2239 void
2240 dump_alias_info (FILE *file)
2241 {
2242   size_t i;
2243   const char *funcname
2244     = lang_hooks.decl_printable_name (current_function_decl, 2);
2245
2246   fprintf (file, "\nFlow-insensitive alias information for %s\n\n", funcname);
2247
2248   fprintf (file, "Aliased symbols\n\n");
2249   for (i = 0; i < num_referenced_vars; i++)
2250     {
2251       tree var = referenced_var (i);
2252       if (may_be_aliased (var))
2253         dump_variable (file, var);
2254     }
2255
2256   fprintf (file, "\nDereferenced pointers\n\n");
2257   for (i = 0; i < num_referenced_vars; i++)
2258     {
2259       tree var = referenced_var (i);
2260       var_ann_t ann = var_ann (var);
2261       if (ann->type_mem_tag)
2262         dump_variable (file, var);
2263     }
2264
2265   fprintf (file, "\nType memory tags\n\n");
2266   for (i = 0; i < num_referenced_vars; i++)
2267     {
2268       tree var = referenced_var (i);
2269       var_ann_t ann = var_ann (var);
2270       if (ann->mem_tag_kind == TYPE_TAG)
2271         dump_variable (file, var);
2272     }
2273
2274   fprintf (file, "\n\nFlow-sensitive alias information for %s\n\n", funcname);
2275
2276   fprintf (file, "SSA_NAME pointers\n\n");
2277   for (i = 1; i < num_ssa_names; i++)
2278     {
2279       tree ptr = ssa_name (i);
2280       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
2281       if (!SSA_NAME_IN_FREE_LIST (ptr)
2282           && pi
2283           && pi->name_mem_tag)
2284         dump_points_to_info_for (file, ptr);
2285     }
2286
2287   fprintf (file, "\nName memory tags\n\n");
2288   for (i = 0; i < num_referenced_vars; i++)
2289     {
2290       tree var = referenced_var (i);
2291       var_ann_t ann = var_ann (var);
2292       if (ann->mem_tag_kind == NAME_TAG)
2293         dump_variable (file, var);
2294     }
2295
2296   fprintf (file, "\n");
2297 }
2298
2299
2300 /* Dump alias information on stderr.  */
2301
2302 void
2303 debug_alias_info (void)
2304 {
2305   dump_alias_info (stderr);
2306 }
2307
2308
2309 /* Return the alias information associated with pointer T.  It creates a
2310    new instance if none existed.  */
2311
2312 static struct ptr_info_def *
2313 get_ptr_info (tree t)
2314 {
2315   struct ptr_info_def *pi;
2316
2317 #if defined ENABLE_CHECKING
2318   if (!POINTER_TYPE_P (TREE_TYPE (t)))
2319     abort ();
2320 #endif
2321
2322   pi = SSA_NAME_PTR_INFO (t);
2323   if (pi == NULL)
2324     {
2325       pi = ggc_alloc (sizeof (*pi));
2326       memset ((void *)pi, 0, sizeof (*pi));
2327       SSA_NAME_PTR_INFO (t) = pi;
2328     }
2329
2330   return pi;
2331 }
2332
2333
2334 /* Dump points-to information for SSA_NAME PTR into FILE.  */
2335
2336 void
2337 dump_points_to_info_for (FILE *file, tree ptr)
2338 {
2339   struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
2340
2341   print_generic_expr (file, ptr, dump_flags);
2342
2343   if (pi)
2344     {
2345       if (pi->name_mem_tag)
2346         {
2347           fprintf (file, ", name memory tag: ");
2348           print_generic_expr (file, pi->name_mem_tag, dump_flags);
2349         }
2350
2351       if (pi->is_dereferenced)
2352         fprintf (file, ", is dereferenced");
2353
2354       if (pi->value_escapes_p)
2355         fprintf (file, ", its value escapes");
2356
2357       if (pi->pt_anything)
2358         fprintf (file, ", points-to anything");
2359
2360       if (pi->pt_malloc)
2361         fprintf (file, ", points-to malloc");
2362
2363       if (pi->pt_vars)
2364         {
2365           unsigned ix;
2366
2367           fprintf (file, ", points-to vars: { ");
2368           EXECUTE_IF_SET_IN_BITMAP (pi->pt_vars, 0, ix,
2369               {
2370                 print_generic_expr (file, referenced_var (ix), dump_flags);
2371                 fprintf (file, " ");
2372               });
2373           fprintf (file, "}");
2374         }
2375     }
2376
2377   fprintf (file, "\n");
2378 }
2379
2380
2381 /* Dump points-to information for VAR into stderr.  */
2382
2383 void
2384 debug_points_to_info_for (tree var)
2385 {
2386   dump_points_to_info_for (stderr, var);
2387 }
2388
2389
2390 /* Dump points-to information into FILE.  NOTE: This function is slow, as
2391    it needs to traverse the whole CFG looking for pointer SSA_NAMEs.  */
2392
2393 void
2394 dump_points_to_info (FILE *file)
2395 {
2396   basic_block bb;
2397   block_stmt_iterator si;
2398   size_t i;
2399   const char *fname =
2400     lang_hooks.decl_printable_name (current_function_decl, 2);
2401
2402   fprintf (file, "\n\nPointed-to sets for pointers in %s\n\n", fname);
2403
2404   /* First dump points-to information for the default definitions of
2405      pointer variables.  This is necessary because default definitions are
2406      not part of the code.  */
2407   for (i = 0; i < num_referenced_vars; i++)
2408     {
2409       tree var = referenced_var (i);
2410       if (POINTER_TYPE_P (TREE_TYPE (var)))
2411         {
2412           var_ann_t ann = var_ann (var);
2413           if (ann->default_def)
2414             dump_points_to_info_for (file, ann->default_def);
2415         }
2416     }
2417
2418   /* Dump points-to information for every pointer defined in the program.  */
2419   FOR_EACH_BB (bb)
2420     {
2421       tree phi;
2422
2423       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
2424         {
2425           tree ptr = PHI_RESULT (phi);
2426           if (POINTER_TYPE_P (TREE_TYPE (ptr)))
2427             dump_points_to_info_for (file, ptr);
2428         }
2429
2430         for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
2431           {
2432             stmt_ann_t ann = stmt_ann (bsi_stmt (si));
2433             def_optype defs = DEF_OPS (ann);
2434             if (defs)
2435               for (i = 0; i < NUM_DEFS (defs); i++)
2436                 if (POINTER_TYPE_P (TREE_TYPE (DEF_OP (defs, i))))
2437                   dump_points_to_info_for (file, DEF_OP (defs, i));
2438           }
2439     }
2440
2441   fprintf (file, "\n");
2442 }
2443
2444
2445 /* Dump points-to info pointed by PTO into STDERR.  */
2446
2447 void
2448 debug_points_to_info (void)
2449 {
2450   dump_points_to_info (stderr);
2451 }
2452
2453 /* Dump to FILE the list of variables that may be aliasing VAR.  */
2454
2455 void
2456 dump_may_aliases_for (FILE *file, tree var)
2457 {
2458   varray_type aliases;
2459   
2460   if (TREE_CODE (var) == SSA_NAME)
2461     var = SSA_NAME_VAR (var);
2462
2463   aliases = var_ann (var)->may_aliases;
2464   if (aliases)
2465     {
2466       size_t i;
2467       fprintf (file, "{ ");
2468       for (i = 0; i < VARRAY_ACTIVE_SIZE (aliases); i++)
2469         {
2470           print_generic_expr (file, VARRAY_TREE (aliases, i), dump_flags);
2471           fprintf (file, " ");
2472         }
2473       fprintf (file, "}");
2474     }
2475 }
2476
2477
2478 /* Dump to stderr the list of variables that may be aliasing VAR.  */
2479
2480 void
2481 debug_may_aliases_for (tree var)
2482 {
2483   dump_may_aliases_for (stderr, var);
2484 }
2485
2486 /* Return true if VAR may be aliased.  */
2487
2488 bool
2489 may_be_aliased (tree var)
2490 {
2491   /* Obviously.  */
2492   if (TREE_ADDRESSABLE (var))
2493     return true;
2494
2495   /* Automatic variables can't have their addresses escape any other way.  */
2496   if (!TREE_STATIC (var))
2497     return false;
2498
2499   /* Globally visible variables can have their addresses taken by other
2500      translation units.  */
2501   if (DECL_EXTERNAL (var) || TREE_PUBLIC (var))
2502     return true;
2503
2504   /* If we're in unit-at-a-time mode, then we must have seen all occurrences
2505      of address-of operators, and so we can trust TREE_ADDRESSABLE.  Otherwise
2506      we can only be sure the variable isn't addressable if it's local to the
2507      current function.  */
2508   if (flag_unit_at_a_time)
2509     return false;
2510   if (decl_function_context (var) == current_function_decl)
2511     return false;
2512
2513   return true;
2514 }
2515