OSDN Git Service

2005-03-18 Daniel Berlin <dberlin@dberlin.org>
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-alias.c
1 /* Alias analysis for trees.
2    Copyright (C) 2004, 2005 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-pass.h"
43 #include "convert.h"
44 #include "params.h"
45 #include "vec.h"
46
47 /* 'true' after aliases have been computed (see compute_may_aliases).  */
48 bool aliases_computed_p;
49
50 /* Structure to map a variable to its alias set and keep track of the
51    virtual operands that will be needed to represent it.  */
52 struct alias_map_d
53 {
54   /* Variable and its alias set.  */
55   tree var;
56   HOST_WIDE_INT set;
57
58   /* Total number of virtual operands that will be needed to represent
59      all the aliases of VAR.  */
60   long total_alias_vops;
61
62   /* Nonzero if the aliases for this memory tag have been grouped
63      already.  Used in group_aliases.  */
64   unsigned int grouped_p : 1;
65
66   /* Set of variables aliased with VAR.  This is the exact same
67      information contained in VAR_ANN (VAR)->MAY_ALIASES, but in
68      bitmap form to speed up alias grouping.  */
69   sbitmap may_aliases;
70 };
71
72
73 /* Alias information used by compute_may_aliases and its helpers.  */
74 struct alias_info
75 {
76   /* SSA names visited while collecting points-to information.  If bit I
77      is set, it means that SSA variable with version I has already been
78      visited.  */
79   sbitmap ssa_names_visited;
80
81   /* Array of SSA_NAME pointers processed by the points-to collector.  */
82   varray_type processed_ptrs;
83
84   /* Variables whose address is still needed.  */
85   bitmap addresses_needed;
86
87   /* ADDRESSABLE_VARS contains all the global variables and locals that
88      have had their address taken.  */
89   struct alias_map_d **addressable_vars;
90   size_t num_addressable_vars;
91
92   /* POINTERS contains all the _DECL pointers with unique memory tags
93      that have been referenced in the program.  */
94   struct alias_map_d **pointers;
95   size_t num_pointers;
96
97   /* Number of function calls found in the program.  */
98   size_t num_calls_found;
99
100   /* Number of const/pure function calls found in the program.  */
101   size_t num_pure_const_calls_found;
102
103   /* Array of counters to keep track of how many times each pointer has
104      been dereferenced in the program.  This is used by the alias grouping
105      heuristic in compute_flow_insensitive_aliasing.  */
106   varray_type num_references;
107
108   /* Total number of virtual operands that will be needed to represent
109      all the aliases of all the pointers found in the program.  */
110   long total_alias_vops;
111
112   /* Variables that have been written to.  */
113   bitmap written_vars;
114
115   /* Pointers that have been used in an indirect store operation.  */
116   bitmap dereferenced_ptrs_store;
117
118   /* Pointers that have been used in an indirect load operation.  */
119   bitmap dereferenced_ptrs_load;
120 };
121
122
123 /* Counters used to display statistics on alias analysis.  */
124 struct alias_stats_d
125 {
126   unsigned int alias_queries;
127   unsigned int alias_mayalias;
128   unsigned int alias_noalias;
129   unsigned int simple_queries;
130   unsigned int simple_resolved;
131   unsigned int tbaa_queries;
132   unsigned int tbaa_resolved;
133 };
134
135
136 /* Local variables.  */
137 static struct alias_stats_d alias_stats;
138
139 /* Local functions.  */
140 static void compute_flow_insensitive_aliasing (struct alias_info *);
141 static void dump_alias_stats (FILE *);
142 static bool may_alias_p (tree, HOST_WIDE_INT, tree, HOST_WIDE_INT);
143 static tree create_memory_tag (tree type, bool is_type_tag);
144 static tree get_tmt_for (tree, struct alias_info *);
145 static tree get_nmt_for (tree);
146 static void add_may_alias (tree, tree);
147 static void replace_may_alias (tree, size_t, tree);
148 static struct alias_info *init_alias_info (void);
149 static void delete_alias_info (struct alias_info *);
150 static void compute_points_to_and_addr_escape (struct alias_info *);
151 static void compute_flow_sensitive_aliasing (struct alias_info *);
152 static void setup_pointers_and_addressables (struct alias_info *);
153 static bool collect_points_to_info_r (tree, tree, void *);
154 static bool is_escape_site (tree, struct alias_info *);
155 static void add_pointed_to_var (struct alias_info *, tree, tree);
156 static void create_global_var (void);
157 static void collect_points_to_info_for (struct alias_info *, tree);
158 static void maybe_create_global_var (struct alias_info *ai);
159 static void group_aliases (struct alias_info *);
160 static void set_pt_anything (tree ptr);
161 static void set_pt_malloc (tree ptr);
162
163 /* Global declarations.  */
164
165 /* Call clobbered variables in the function.  If bit I is set, then
166    REFERENCED_VARS (I) is call-clobbered.  */
167 bitmap call_clobbered_vars;
168
169 /* Addressable variables in the function.  If bit I is set, then
170    REFERENCED_VARS (I) has had its address taken.  Note that
171    CALL_CLOBBERED_VARS and ADDRESSABLE_VARS are not related.  An
172    addressable variable is not necessarily call-clobbered (e.g., a
173    local addressable whose address does not escape) and not all
174    call-clobbered variables are addressable (e.g., a local static
175    variable).  */
176 bitmap addressable_vars;
177
178 /* When the program has too many call-clobbered variables and call-sites,
179    this variable is used to represent the clobbering effects of function
180    calls.  In these cases, all the call clobbered variables in the program
181    are forced to alias this variable.  This reduces compile times by not
182    having to keep track of too many V_MAY_DEF expressions at call sites.  */
183 tree global_var;
184
185
186 /* Compute may-alias information for every variable referenced in function
187    FNDECL.
188
189    Alias analysis proceeds in 3 main phases:
190
191    1- Points-to and escape analysis.
192
193    This phase walks the use-def chains in the SSA web looking for three
194    things:
195
196         * Assignments of the form P_i = &VAR
197         * Assignments of the form P_i = malloc()
198         * Pointers and ADDR_EXPR that escape the current function.
199
200    The concept of 'escaping' is the same one used in the Java world.  When
201    a pointer or an ADDR_EXPR escapes, it means that it has been exposed
202    outside of the current function.  So, assignment to global variables,
203    function arguments and returning a pointer are all escape sites, as are
204    conversions between pointers and integers.
205
206    This is where we are currently limited.  Since not everything is renamed
207    into SSA, we lose track of escape properties when a pointer is stashed
208    inside a field in a structure, for instance.  In those cases, we are
209    assuming that the pointer does escape.
210
211    We use escape analysis to determine whether a variable is
212    call-clobbered.  Simply put, if an ADDR_EXPR escapes, then the variable
213    is call-clobbered.  If a pointer P_i escapes, then all the variables
214    pointed-to by P_i (and its memory tag) also escape.
215
216    2- Compute flow-sensitive aliases
217
218    We have two classes of memory tags.  Memory tags associated with the
219    pointed-to data type of the pointers in the program.  These tags are
220    called "type memory tag" (TMT).  The other class are those associated
221    with SSA_NAMEs, called "name memory tag" (NMT). The basic idea is that
222    when adding operands for an INDIRECT_REF *P_i, we will first check
223    whether P_i has a name tag, if it does we use it, because that will have
224    more precise aliasing information.  Otherwise, we use the standard type
225    tag.
226
227    In this phase, we go through all the pointers we found in points-to
228    analysis and create alias sets for the name memory tags associated with
229    each pointer P_i.  If P_i escapes, we mark call-clobbered the variables
230    it points to and its tag.
231
232
233    3- Compute flow-insensitive aliases
234
235    This pass will compare the alias set of every type memory tag and every
236    addressable variable found in the program.  Given a type memory tag TMT
237    and an addressable variable V.  If the alias sets of TMT and V conflict
238    (as computed by may_alias_p), then V is marked as an alias tag and added
239    to the alias set of TMT.
240
241    For instance, consider the following function:
242
243             foo (int i)
244             {
245               int *p, a, b;
246             
247               if (i > 10)
248                 p = &a;
249               else
250                 p = &b;
251             
252               *p = 3;
253               a = b + 2;
254               return *p;
255             }
256
257    After aliasing analysis has finished, the type memory tag for pointer
258    'p' will have two aliases, namely variables 'a' and 'b'.  Every time
259    pointer 'p' is dereferenced, we want to mark the operation as a
260    potential reference to 'a' and 'b'.
261
262             foo (int i)
263             {
264               int *p, a, b;
265
266               if (i_2 > 10)
267                 p_4 = &a;
268               else
269                 p_6 = &b;
270               # p_1 = PHI <p_4(1), p_6(2)>;
271
272               # a_7 = V_MAY_DEF <a_3>;
273               # b_8 = V_MAY_DEF <b_5>;
274               *p_1 = 3;
275
276               # a_9 = V_MAY_DEF <a_7>
277               # VUSE <b_8>
278               a_9 = b_8 + 2;
279
280               # VUSE <a_9>;
281               # VUSE <b_8>;
282               return *p_1;
283             }
284
285    In certain cases, the list of may aliases for a pointer may grow too
286    large.  This may cause an explosion in the number of virtual operands
287    inserted in the code.  Resulting in increased memory consumption and
288    compilation time.
289
290    When the number of virtual operands needed to represent aliased
291    loads and stores grows too large (configurable with @option{--param
292    max-aliased-vops}), alias sets are grouped to avoid severe
293    compile-time slow downs and memory consumption.  See group_aliases.  */
294
295 static void
296 compute_may_aliases (void)
297 {
298   struct alias_info *ai;
299   
300   memset (&alias_stats, 0, sizeof (alias_stats));
301
302   /* Initialize aliasing information.  */
303   ai = init_alias_info ();
304
305   /* For each pointer P_i, determine the sets of variables that P_i may
306      point-to.  For every addressable variable V, determine whether the
307      address of V escapes the current function, making V call-clobbered
308      (i.e., whether &V is stored in a global variable or if its passed as a
309      function call argument).  */
310   compute_points_to_and_addr_escape (ai);
311
312   /* Collect all pointers and addressable variables, compute alias sets,
313      create memory tags for pointers and promote variables whose address is
314      not needed anymore.  */
315   setup_pointers_and_addressables (ai);
316
317   /* Compute flow-sensitive, points-to based aliasing for all the name
318      memory tags.  Note that this pass needs to be done before flow
319      insensitive analysis because it uses the points-to information
320      gathered before to mark call-clobbered type tags.  */
321   compute_flow_sensitive_aliasing (ai);
322
323   /* Compute type-based flow-insensitive aliasing for all the type
324      memory tags.  */
325   compute_flow_insensitive_aliasing (ai);
326
327   /* If the program has too many call-clobbered variables and/or function
328      calls, create .GLOBAL_VAR and use it to model call-clobbering
329      semantics at call sites.  This reduces the number of virtual operands
330      considerably, improving compile times at the expense of lost
331      aliasing precision.  */
332   maybe_create_global_var (ai);
333
334   /* Debugging dumps.  */
335   if (dump_file)
336     {
337       dump_referenced_vars (dump_file);
338       if (dump_flags & TDF_STATS)
339         dump_alias_stats (dump_file);
340       dump_points_to_info (dump_file);
341       dump_alias_info (dump_file);
342     }
343
344   /* Deallocate memory used by aliasing data structures.  */
345   delete_alias_info (ai);
346 }
347
348 struct tree_opt_pass pass_may_alias = 
349 {
350   "alias",                              /* name */
351   NULL,                                 /* gate */
352   compute_may_aliases,                  /* execute */
353   NULL,                                 /* sub */
354   NULL,                                 /* next */
355   0,                                    /* static_pass_number */
356   TV_TREE_MAY_ALIAS,                    /* tv_id */
357   PROP_cfg | PROP_ssa,                  /* properties_required */
358   PROP_alias,                           /* properties_provided */
359   0,                                    /* properties_destroyed */
360   0,                                    /* todo_flags_start */
361   TODO_dump_func | TODO_rename_vars
362     | TODO_ggc_collect | TODO_verify_ssa
363     | TODO_verify_stmts,                /* todo_flags_finish */
364   0                                     /* letter */
365 };
366
367
368 /* Data structure used to count the number of dereferences to PTR
369    inside an expression.  */
370 struct count_ptr_d
371 {
372   tree ptr;
373   unsigned count;
374 };
375
376
377 /* Helper for count_uses_and_derefs.  Called by walk_tree to look for
378    (ALIGN/MISALIGNED_)INDIRECT_REF nodes for the pointer passed in DATA.  */
379
380 static tree
381 count_ptr_derefs (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED, void *data)
382 {
383   struct count_ptr_d *count_p = (struct count_ptr_d *) data;
384
385   if (INDIRECT_REF_P (*tp) && TREE_OPERAND (*tp, 0) == count_p->ptr)
386     count_p->count++;
387
388   return NULL_TREE;
389 }
390
391
392 /* Count the number of direct and indirect uses for pointer PTR in
393    statement STMT.  The two counts are stored in *NUM_USES_P and
394    *NUM_DEREFS_P respectively.  *IS_STORE_P is set to 'true' if at
395    least one of those dereferences is a store operation.  */
396
397 static void
398 count_uses_and_derefs (tree ptr, tree stmt, unsigned *num_uses_p,
399                        unsigned *num_derefs_p, bool *is_store)
400 {
401   ssa_op_iter i;
402   tree use;
403
404   *num_uses_p = 0;
405   *num_derefs_p = 0;
406   *is_store = false;
407
408   /* Find out the total number of uses of PTR in STMT.  */
409   FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
410     if (use == ptr)
411       (*num_uses_p)++;
412
413   /* Now count the number of indirect references to PTR.  This is
414      truly awful, but we don't have much choice.  There are no parent
415      pointers inside INDIRECT_REFs, so an expression like
416      '*x_1 = foo (x_1, *x_1)' needs to be traversed piece by piece to
417      find all the indirect and direct uses of x_1 inside.  The only
418      shortcut we can take is the fact that GIMPLE only allows
419      INDIRECT_REFs inside the expressions below.  */
420   if (TREE_CODE (stmt) == MODIFY_EXPR
421       || (TREE_CODE (stmt) == RETURN_EXPR
422           && TREE_CODE (TREE_OPERAND (stmt, 0)) == MODIFY_EXPR)
423       || TREE_CODE (stmt) == ASM_EXPR
424       || TREE_CODE (stmt) == CALL_EXPR)
425     {
426       tree lhs, rhs;
427
428       if (TREE_CODE (stmt) == MODIFY_EXPR)
429         {
430           lhs = TREE_OPERAND (stmt, 0);
431           rhs = TREE_OPERAND (stmt, 1);
432         }
433       else if (TREE_CODE (stmt) == RETURN_EXPR)
434         {
435           tree e = TREE_OPERAND (stmt, 0);
436           lhs = TREE_OPERAND (e, 0);
437           rhs = TREE_OPERAND (e, 1);
438         }
439       else if (TREE_CODE (stmt) == ASM_EXPR)
440         {
441           lhs = ASM_OUTPUTS (stmt);
442           rhs = ASM_INPUTS (stmt);
443         }
444       else
445         {
446           lhs = NULL_TREE;
447           rhs = stmt;
448         }
449
450       if (lhs && (TREE_CODE (lhs) == TREE_LIST || EXPR_P (lhs)))
451         {
452           struct count_ptr_d count;
453           count.ptr = ptr;
454           count.count = 0;
455           walk_tree (&lhs, count_ptr_derefs, &count, NULL);
456           *is_store = true;
457           *num_derefs_p = count.count;
458         }
459
460       if (rhs && (TREE_CODE (rhs) == TREE_LIST || EXPR_P (rhs)))
461         {
462           struct count_ptr_d count;
463           count.ptr = ptr;
464           count.count = 0;
465           walk_tree (&rhs, count_ptr_derefs, &count, NULL);
466           *num_derefs_p += count.count;
467         }
468     }
469
470   gcc_assert (*num_uses_p >= *num_derefs_p);
471 }
472
473
474 /* Initialize the data structures used for alias analysis.  */
475
476 static struct alias_info *
477 init_alias_info (void)
478 {
479   struct alias_info *ai;
480
481   ai = xcalloc (1, sizeof (struct alias_info));
482   ai->ssa_names_visited = sbitmap_alloc (num_ssa_names);
483   sbitmap_zero (ai->ssa_names_visited);
484   VARRAY_TREE_INIT (ai->processed_ptrs, 50, "processed_ptrs");
485   ai->addresses_needed = BITMAP_ALLOC (NULL);
486   VARRAY_UINT_INIT (ai->num_references, num_referenced_vars, "num_references");
487   ai->written_vars = BITMAP_ALLOC (NULL);
488   ai->dereferenced_ptrs_store = BITMAP_ALLOC (NULL);
489   ai->dereferenced_ptrs_load = BITMAP_ALLOC (NULL);
490
491   /* If aliases have been computed before, clear existing information.  */
492   if (aliases_computed_p)
493     {
494       unsigned i;
495       basic_block bb;
496   
497      /* Make sure that every statement has a valid set of operands.
498         If a statement needs to be scanned for operands while we
499         compute aliases, it may get erroneous operands because all
500         the alias relations are not built at that point.
501         FIXME: This code will become obsolete when operands are not
502         lazily updated.  */
503       FOR_EACH_BB (bb)
504         {
505           block_stmt_iterator si;
506           for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
507             get_stmt_operands (bsi_stmt (si));
508         }
509
510       /* Similarly, clear the set of addressable variables.  In this
511          case, we can just clear the set because addressability is
512          only computed here.  */
513       bitmap_clear (addressable_vars);
514
515       /* Clear flow-insensitive alias information from each symbol.  */
516       for (i = 0; i < num_referenced_vars; i++)
517         {
518           tree var = referenced_var (i);
519           var_ann_t ann = var_ann (var);
520
521           ann->is_alias_tag = 0;
522           ann->may_aliases = NULL;
523
524           /* Since we are about to re-discover call-clobbered
525              variables, clear the call-clobbered flag.  Variables that
526              are intrinsically call-clobbered (globals, local statics,
527              etc) will not be marked by the aliasing code, so we can't
528              remove them from CALL_CLOBBERED_VARS.  
529
530              NB: STRUCT_FIELDS are still call clobbered if they are for
531              a global variable, so we *don't* clear their call clobberedness
532              just because they are tags, though we will clear it if they
533              aren't for global variables.  */
534           if (ann->mem_tag_kind == NAME_TAG 
535               || ann->mem_tag_kind == TYPE_TAG 
536               || !is_global_var (var))
537             clear_call_clobbered (var);
538         }
539
540       /* Clear flow-sensitive points-to information from each SSA name.  */
541       for (i = 1; i < num_ssa_names; i++)
542         {
543           tree name = ssa_name (i);
544
545           if (!name || !POINTER_TYPE_P (TREE_TYPE (name)))
546             continue;
547
548           if (SSA_NAME_PTR_INFO (name))
549             {
550               struct ptr_info_def *pi = SSA_NAME_PTR_INFO (name);
551
552               /* Clear all the flags but keep the name tag to
553                  avoid creating new temporaries unnecessarily.  If
554                  this pointer is found to point to a subset or
555                  superset of its former points-to set, then a new
556                  tag will need to be created in create_name_tags.  */
557               pi->pt_anything = 0;
558               pi->pt_malloc = 0;
559               pi->pt_null = 0;
560               pi->value_escapes_p = 0;
561               pi->is_dereferenced = 0;
562               if (pi->pt_vars)
563                 bitmap_clear (pi->pt_vars);
564             }
565         }
566     }
567
568   /* Next time, we will need to reset alias information.  */
569   aliases_computed_p = true;
570
571   return ai;
572 }
573
574
575 /* Deallocate memory used by alias analysis.  */
576
577 static void
578 delete_alias_info (struct alias_info *ai)
579 {
580   size_t i;
581
582   sbitmap_free (ai->ssa_names_visited);
583   ai->processed_ptrs = NULL;
584   BITMAP_FREE (ai->addresses_needed);
585
586   for (i = 0; i < ai->num_addressable_vars; i++)
587     {
588       sbitmap_free (ai->addressable_vars[i]->may_aliases);
589       free (ai->addressable_vars[i]);
590     }
591   free (ai->addressable_vars);
592
593   for (i = 0; i < ai->num_pointers; i++)
594     {
595       sbitmap_free (ai->pointers[i]->may_aliases);
596       free (ai->pointers[i]);
597     }
598   free (ai->pointers);
599
600   ai->num_references = NULL;
601   BITMAP_FREE (ai->written_vars);
602   BITMAP_FREE (ai->dereferenced_ptrs_store);
603   BITMAP_FREE (ai->dereferenced_ptrs_load);
604
605   free (ai);
606 }
607
608
609 /* Walk use-def chains for pointer PTR to determine what variables is PTR
610    pointing to.  */
611
612 static void
613 collect_points_to_info_for (struct alias_info *ai, tree ptr)
614 {
615   gcc_assert (POINTER_TYPE_P (TREE_TYPE (ptr)));
616
617   if (!TEST_BIT (ai->ssa_names_visited, SSA_NAME_VERSION (ptr)))
618     {
619       SET_BIT (ai->ssa_names_visited, SSA_NAME_VERSION (ptr));
620       walk_use_def_chains (ptr, collect_points_to_info_r, ai, true);
621       VARRAY_PUSH_TREE (ai->processed_ptrs, ptr);
622     }
623 }
624
625
626 /* Traverse use-def links for all the pointers in the program to collect
627    address escape and points-to information.
628    
629    This is loosely based on the same idea described in R. Hasti and S.
630    Horwitz, ``Using static single assignment form to improve
631    flow-insensitive pointer analysis,'' in SIGPLAN Conference on
632    Programming Language Design and Implementation, pp. 97-105, 1998.  */
633
634 static void
635 compute_points_to_and_addr_escape (struct alias_info *ai)
636 {
637   basic_block bb;
638   unsigned i;
639   tree op;
640   ssa_op_iter iter;
641
642   timevar_push (TV_TREE_PTA);
643
644   FOR_EACH_BB (bb)
645     {
646       bb_ann_t block_ann = bb_ann (bb);
647       block_stmt_iterator si;
648
649       for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
650         {
651           bitmap addr_taken;
652           tree stmt = bsi_stmt (si);
653           bool stmt_escapes_p = is_escape_site (stmt, ai);
654           bitmap_iterator bi;
655
656           /* Mark all the variables whose address are taken by the
657              statement.  Note that this will miss all the addresses taken
658              in PHI nodes (those are discovered while following the use-def
659              chains).  */
660           get_stmt_operands (stmt);
661           addr_taken = addresses_taken (stmt);
662           if (addr_taken)
663             EXECUTE_IF_SET_IN_BITMAP (addr_taken, 0, i, bi)
664               {
665                 tree var = referenced_var (i);
666                 bitmap_set_bit (ai->addresses_needed, var_ann (var)->uid);
667                 if (stmt_escapes_p)
668                   mark_call_clobbered (var);
669               }
670
671           if (stmt_escapes_p)
672             block_ann->has_escape_site = 1;
673
674           FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
675             {
676               var_ann_t v_ann = var_ann (SSA_NAME_VAR (op));
677               struct ptr_info_def *pi;
678               bool is_store;
679               unsigned num_uses, num_derefs;
680
681               /* If the operand's variable may be aliased, keep track
682                  of how many times we've referenced it.  This is used
683                  for alias grouping in compute_flow_sensitive_aliasing.
684                  Note that we don't need to grow AI->NUM_REFERENCES
685                  because we are processing regular variables, not
686                  memory tags (the array's initial size is set to
687                  NUM_REFERENCED_VARS).  */
688               if (may_be_aliased (SSA_NAME_VAR (op)))
689                 (VARRAY_UINT (ai->num_references, v_ann->uid))++;
690
691               if (!POINTER_TYPE_P (TREE_TYPE (op)))
692                 continue;
693
694               collect_points_to_info_for (ai, op);
695
696               pi = SSA_NAME_PTR_INFO (op);
697               count_uses_and_derefs (op, stmt, &num_uses, &num_derefs,
698                                      &is_store);
699
700               if (num_derefs > 0)
701                 {
702                   /* Mark OP as dereferenced.  In a subsequent pass,
703                      dereferenced pointers that point to a set of
704                      variables will be assigned a name tag to alias
705                      all the variables OP points to.  */
706                   pi->is_dereferenced = 1;
707
708                   /* Keep track of how many time we've dereferenced each
709                      pointer.  Again, we don't need to grow
710                      AI->NUM_REFERENCES because we're processing
711                      existing program variables.  */
712                   (VARRAY_UINT (ai->num_references, v_ann->uid))++;
713
714                   /* If this is a store operation, mark OP as being
715                      dereferenced to store, otherwise mark it as being
716                      dereferenced to load.  */
717                   if (is_store)
718                     bitmap_set_bit (ai->dereferenced_ptrs_store, v_ann->uid);
719                   else
720                     bitmap_set_bit (ai->dereferenced_ptrs_load, v_ann->uid);
721                 }
722
723               if (stmt_escapes_p && num_derefs < num_uses)
724                 {
725                   /* If STMT is an escape point and STMT contains at
726                      least one direct use of OP, then the value of OP
727                      escapes and so the pointed-to variables need to
728                      be marked call-clobbered.  */
729                   pi->value_escapes_p = 1;
730
731                   /* If the statement makes a function call, assume
732                      that pointer OP will be dereferenced in a store
733                      operation inside the called function.  */
734                   if (get_call_expr_in (stmt))
735                     {
736                       bitmap_set_bit (ai->dereferenced_ptrs_store, v_ann->uid);
737                       pi->is_dereferenced = 1;
738                     }
739                 }
740             }
741
742           /* Update reference counter for definitions to any
743              potentially aliased variable.  This is used in the alias
744              grouping heuristics.  */
745           FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_DEF)
746             {
747               tree var = SSA_NAME_VAR (op);
748               var_ann_t ann = var_ann (var);
749               bitmap_set_bit (ai->written_vars, ann->uid);
750               if (may_be_aliased (var))
751                 (VARRAY_UINT (ai->num_references, ann->uid))++;
752
753               if (POINTER_TYPE_P (TREE_TYPE (op)))
754                 collect_points_to_info_for (ai, op);
755             }
756
757           /* Mark variables in V_MAY_DEF operands as being written to.  */
758           FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_VIRTUAL_DEFS)
759             {
760               tree var = SSA_NAME_VAR (op);
761               var_ann_t ann = var_ann (var);
762               bitmap_set_bit (ai->written_vars, ann->uid);
763             }
764             
765           /* After promoting variables and computing aliasing we will
766              need to re-scan most statements.  FIXME: Try to minimize the
767              number of statements re-scanned.  It's not really necessary to
768              re-scan *all* statements.  */
769           modify_stmt (stmt);
770         }
771     }
772
773   timevar_pop (TV_TREE_PTA);
774 }
775
776
777 /* Create name tags for all the pointers that have been dereferenced.
778    We only create a name tag for a pointer P if P is found to point to
779    a set of variables (so that we can alias them to *P) or if it is
780    the result of a call to malloc (which means that P cannot point to
781    anything else nor alias any other variable).
782
783    If two pointers P and Q point to the same set of variables, they
784    are assigned the same name tag.  */
785
786 static void
787 create_name_tags (struct alias_info *ai)
788 {
789   size_t i;
790
791   for (i = 0; i < VARRAY_ACTIVE_SIZE (ai->processed_ptrs); i++)
792     {
793       tree ptr = VARRAY_TREE (ai->processed_ptrs, i);
794       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
795
796       if (pi->pt_anything || !pi->is_dereferenced)
797         {
798           /* No name tags for pointers that have not been
799              dereferenced or point to an arbitrary location.  */
800           pi->name_mem_tag = NULL_TREE;
801           continue;
802         }
803
804       if (pi->pt_vars && !bitmap_empty_p (pi->pt_vars))
805         {
806           size_t j;
807           tree old_name_tag = pi->name_mem_tag;
808
809           /* If PTR points to a set of variables, check if we don't
810              have another pointer Q with the same points-to set before
811              creating a tag.  If so, use Q's tag instead of creating a
812              new one.
813
814              This is important for not creating unnecessary symbols
815              and also for copy propagation.  If we ever need to
816              propagate PTR into Q or vice-versa, we would run into
817              problems if they both had different name tags because
818              they would have different SSA version numbers (which
819              would force us to take the name tags in and out of SSA).  */
820           for (j = 0; j < i; j++)
821             {
822               tree q = VARRAY_TREE (ai->processed_ptrs, j);
823               struct ptr_info_def *qi = SSA_NAME_PTR_INFO (q);
824
825               if (qi
826                   && qi->pt_vars
827                   && qi->name_mem_tag
828                   && bitmap_equal_p (pi->pt_vars, qi->pt_vars))
829                 {
830                   pi->name_mem_tag = qi->name_mem_tag;
831                   break;
832                 }
833             }
834
835           /* If we didn't find a pointer with the same points-to set
836              as PTR, create a new name tag if needed.  */
837           if (pi->name_mem_tag == NULL_TREE)
838             pi->name_mem_tag = get_nmt_for (ptr);
839
840           /* If the new name tag computed for PTR is different than
841              the old name tag that it used to have, then the old tag
842              needs to be removed from the IL, so we mark it for
843              renaming.  */
844           if (old_name_tag && old_name_tag != pi->name_mem_tag)
845             bitmap_set_bit (vars_to_rename, var_ann (old_name_tag)->uid);
846         }
847       else if (pi->pt_malloc)
848         {
849           /* Otherwise, create a unique name tag for this pointer.  */
850           pi->name_mem_tag = get_nmt_for (ptr);
851         }
852       else
853         {
854           /* Only pointers that may point to malloc or other variables
855              may receive a name tag.  If the pointer does not point to
856              a known spot, we should use type tags.  */
857           set_pt_anything (ptr);
858           continue;
859         }
860
861       TREE_THIS_VOLATILE (pi->name_mem_tag)
862           |= TREE_THIS_VOLATILE (TREE_TYPE (TREE_TYPE (ptr)));
863
864       /* Mark the new name tag for renaming.  */
865       bitmap_set_bit (vars_to_rename, var_ann (pi->name_mem_tag)->uid);
866     }
867 }
868
869
870
871 /* For every pointer P_i in AI->PROCESSED_PTRS, create may-alias sets for
872    the name memory tag (NMT) associated with P_i.  If P_i escapes, then its
873    name tag and the variables it points-to are call-clobbered.  Finally, if
874    P_i escapes and we could not determine where it points to, then all the
875    variables in the same alias set as *P_i are marked call-clobbered.  This
876    is necessary because we must assume that P_i may take the address of any
877    variable in the same alias set.  */
878
879 static void
880 compute_flow_sensitive_aliasing (struct alias_info *ai)
881 {
882   size_t i;
883
884   create_name_tags (ai);
885
886   for (i = 0; i < VARRAY_ACTIVE_SIZE (ai->processed_ptrs); i++)
887     {
888       unsigned j;
889       tree ptr = VARRAY_TREE (ai->processed_ptrs, i);
890       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
891       var_ann_t v_ann = var_ann (SSA_NAME_VAR (ptr));
892       bitmap_iterator bi;
893
894       if (pi->value_escapes_p || pi->pt_anything)
895         {
896           /* If PTR escapes or may point to anything, then its associated
897              memory tags and pointed-to variables are call-clobbered.  */
898           if (pi->name_mem_tag)
899             mark_call_clobbered (pi->name_mem_tag);
900
901           if (v_ann->type_mem_tag)
902             mark_call_clobbered (v_ann->type_mem_tag);
903
904           if (pi->pt_vars)
905             EXECUTE_IF_SET_IN_BITMAP (pi->pt_vars, 0, j, bi)
906               {
907                 mark_call_clobbered (referenced_var (j));
908               }
909         }
910
911       /* Set up aliasing information for PTR's name memory tag (if it has
912          one).  Note that only pointers that have been dereferenced will
913          have a name memory tag.  */
914       if (pi->name_mem_tag && pi->pt_vars)
915         EXECUTE_IF_SET_IN_BITMAP (pi->pt_vars, 0, j, bi)
916           {
917             add_may_alias (pi->name_mem_tag, referenced_var (j));
918             add_may_alias (v_ann->type_mem_tag, referenced_var (j));
919           }
920
921       /* If the name tag is call clobbered, so is the type tag
922          associated with the base VAR_DECL.  */
923       if (pi->name_mem_tag
924           && v_ann->type_mem_tag
925           && is_call_clobbered (pi->name_mem_tag))
926         mark_call_clobbered (v_ann->type_mem_tag);
927     }
928 }
929
930
931 /* Compute type-based alias sets.  Traverse all the pointers and
932    addressable variables found in setup_pointers_and_addressables.
933    
934    For every pointer P in AI->POINTERS and addressable variable V in
935    AI->ADDRESSABLE_VARS, add V to the may-alias sets of P's type
936    memory tag (TMT) if their alias sets conflict.  V is then marked as
937    an alias tag so that the operand scanner knows that statements
938    containing V have aliased operands.  */
939
940 static void
941 compute_flow_insensitive_aliasing (struct alias_info *ai)
942 {
943   size_t i;
944
945   /* Initialize counter for the total number of virtual operands that
946      aliasing will introduce.  When AI->TOTAL_ALIAS_VOPS goes beyond the
947      threshold set by --params max-alias-vops, we enable alias
948      grouping.  */
949   ai->total_alias_vops = 0;
950
951   /* For every pointer P, determine which addressable variables may alias
952      with P's type memory tag.  */
953   for (i = 0; i < ai->num_pointers; i++)
954     {
955       size_t j;
956       struct alias_map_d *p_map = ai->pointers[i];
957       tree tag = var_ann (p_map->var)->type_mem_tag;
958       var_ann_t tag_ann = var_ann (tag);
959
960       p_map->total_alias_vops = 0;
961       p_map->may_aliases = sbitmap_alloc (num_referenced_vars);
962       sbitmap_zero (p_map->may_aliases);
963
964       for (j = 0; j < ai->num_addressable_vars; j++)
965         {
966           struct alias_map_d *v_map;
967           var_ann_t v_ann;
968           tree var;
969           bool tag_stored_p, var_stored_p;
970           
971           v_map = ai->addressable_vars[j];
972           var = v_map->var;
973           v_ann = var_ann (var);
974
975           /* Skip memory tags and variables that have never been
976              written to.  We also need to check if the variables are
977              call-clobbered because they may be overwritten by
978              function calls.
979
980              Note this is effectively random accessing elements in
981              the sparse bitset, which can be highly inefficient.
982              So we first check the call_clobbered status of the
983              tag and variable before querying the bitmap.  */
984           tag_stored_p = is_call_clobbered (tag)
985                          || bitmap_bit_p (ai->written_vars, tag_ann->uid);
986           var_stored_p = is_call_clobbered (var)
987                          || bitmap_bit_p (ai->written_vars, v_ann->uid);
988           if (!tag_stored_p && !var_stored_p)
989             continue;
990              
991           if (may_alias_p (p_map->var, p_map->set, var, v_map->set))
992             {
993               subvar_t svars;
994               size_t num_tag_refs, num_var_refs;
995
996               num_tag_refs = VARRAY_UINT (ai->num_references, tag_ann->uid);
997               num_var_refs = VARRAY_UINT (ai->num_references, v_ann->uid);
998
999               /* Add VAR to TAG's may-aliases set.  */
1000
1001               /* If this is an aggregate, we may have subvariables for it
1002                  that need to be pointed to.  */
1003               if (var_can_have_subvars (var)
1004                   && (svars = get_subvars_for_var (var)))
1005                 {
1006                   subvar_t sv;
1007
1008                   for (sv = svars; sv; sv = sv->next)
1009                     add_may_alias (tag, sv->var);
1010                 }
1011               else
1012                 {
1013                   add_may_alias (tag, var);
1014                 }
1015
1016               /* Update the total number of virtual operands due to
1017                  aliasing.  Since we are adding one more alias to TAG's
1018                  may-aliases set, the total number of virtual operands due
1019                  to aliasing will be increased by the number of references
1020                  made to VAR and TAG (every reference to TAG will also
1021                  count as a reference to VAR).  */
1022               ai->total_alias_vops += (num_var_refs + num_tag_refs);
1023               p_map->total_alias_vops += (num_var_refs + num_tag_refs);
1024
1025               /* Update the bitmap used to represent TAG's alias set
1026                  in case we need to group aliases.  */
1027               SET_BIT (p_map->may_aliases, var_ann (var)->uid);
1028             }
1029         }
1030     }
1031
1032   /* Since this analysis is based exclusively on symbols, it fails to
1033      handle cases where two pointers P and Q have different memory
1034      tags with conflicting alias set numbers but no aliased symbols in
1035      common.
1036
1037      For example, suppose that we have two memory tags TMT.1 and TMT.2
1038      such that
1039      
1040                 may-aliases (TMT.1) = { a }
1041                 may-aliases (TMT.2) = { b }
1042
1043      and the alias set number of TMT.1 conflicts with that of TMT.2.
1044      Since they don't have symbols in common, loads and stores from
1045      TMT.1 and TMT.2 will seem independent of each other, which will
1046      lead to the optimizers making invalid transformations (see
1047      testsuite/gcc.c-torture/execute/pr15262-[12].c).
1048
1049      To avoid this problem, we do a final traversal of AI->POINTERS
1050      looking for pairs of pointers that have no aliased symbols in
1051      common and yet have conflicting alias set numbers.  */
1052   for (i = 0; i < ai->num_pointers; i++)
1053     {
1054       size_t j;
1055       struct alias_map_d *p_map1 = ai->pointers[i];
1056       tree tag1 = var_ann (p_map1->var)->type_mem_tag;
1057       sbitmap may_aliases1 = p_map1->may_aliases;
1058
1059       for (j = i + 1; j < ai->num_pointers; j++)
1060         {
1061           struct alias_map_d *p_map2 = ai->pointers[j];
1062           tree tag2 = var_ann (p_map2->var)->type_mem_tag;
1063           sbitmap may_aliases2 = p_map2->may_aliases;
1064
1065           /* If the pointers may not point to each other, do nothing.  */
1066           if (!may_alias_p (p_map1->var, p_map1->set, tag2, p_map2->set))
1067             continue;
1068
1069           /* The two pointers may alias each other.  If they already have
1070              symbols in common, do nothing.  */
1071           if (sbitmap_any_common_bits (may_aliases1, may_aliases2))
1072             continue;
1073
1074           if (sbitmap_first_set_bit (may_aliases2) >= 0)
1075             {
1076               size_t k;
1077
1078               /* Add all the aliases for TAG2 into TAG1's alias set.
1079                  FIXME, update grouping heuristic counters.  */
1080               EXECUTE_IF_SET_IN_SBITMAP (may_aliases2, 0, k,
1081                   add_may_alias (tag1, referenced_var (k)));
1082               sbitmap_a_or_b (may_aliases1, may_aliases1, may_aliases2);
1083             }
1084           else
1085             {
1086               /* Since TAG2 does not have any aliases of its own, add
1087                  TAG2 itself to the alias set of TAG1.  */
1088               add_may_alias (tag1, tag2);
1089               SET_BIT (may_aliases1, var_ann (tag2)->uid);
1090             }
1091         }
1092     }
1093
1094   if (dump_file)
1095     fprintf (dump_file, "%s: Total number of aliased vops: %ld\n",
1096              get_name (current_function_decl),
1097              ai->total_alias_vops);
1098
1099   /* Determine if we need to enable alias grouping.  */
1100   if (ai->total_alias_vops >= MAX_ALIASED_VOPS)
1101     group_aliases (ai);
1102 }
1103
1104
1105 /* Comparison function for qsort used in group_aliases.  */
1106
1107 static int
1108 total_alias_vops_cmp (const void *p, const void *q)
1109 {
1110   const struct alias_map_d **p1 = (const struct alias_map_d **)p;
1111   const struct alias_map_d **p2 = (const struct alias_map_d **)q;
1112   long n1 = (*p1)->total_alias_vops;
1113   long n2 = (*p2)->total_alias_vops;
1114
1115   /* We want to sort in descending order.  */
1116   return (n1 > n2 ? -1 : (n1 == n2) ? 0 : 1);
1117 }
1118
1119 /* Group all the aliases for TAG to make TAG represent all the
1120    variables in its alias set.  Update the total number
1121    of virtual operands due to aliasing (AI->TOTAL_ALIAS_VOPS).  This
1122    function will make TAG be the unique alias tag for all the
1123    variables in its may-aliases.  So, given:
1124
1125         may-aliases(TAG) = { V1, V2, V3 }
1126
1127    This function will group the variables into:
1128
1129         may-aliases(V1) = { TAG }
1130         may-aliases(V2) = { TAG }
1131         may-aliases(V2) = { TAG }  */
1132
1133 static void
1134 group_aliases_into (tree tag, sbitmap tag_aliases, struct alias_info *ai)
1135 {
1136   size_t i;
1137   var_ann_t tag_ann = var_ann (tag);
1138   size_t num_tag_refs = VARRAY_UINT (ai->num_references, tag_ann->uid);
1139
1140   EXECUTE_IF_SET_IN_SBITMAP (tag_aliases, 0, i,
1141     {
1142       tree var = referenced_var (i);
1143       var_ann_t ann = var_ann (var);
1144
1145       /* Make TAG the unique alias of VAR.  */
1146       ann->is_alias_tag = 0;
1147       ann->may_aliases = NULL;
1148
1149       /* Note that VAR and TAG may be the same if the function has no
1150          addressable variables (see the discussion at the end of
1151          setup_pointers_and_addressables).  */
1152       if (var != tag)
1153         add_may_alias (var, tag);
1154
1155       /* Reduce total number of virtual operands contributed
1156          by TAG on behalf of VAR.  Notice that the references to VAR
1157          itself won't be removed.  We will merely replace them with
1158          references to TAG.  */
1159       ai->total_alias_vops -= num_tag_refs;
1160     });
1161
1162   /* We have reduced the number of virtual operands that TAG makes on
1163      behalf of all the variables formerly aliased with it.  However,
1164      we have also "removed" all the virtual operands for TAG itself,
1165      so we add them back.  */
1166   ai->total_alias_vops += num_tag_refs;
1167
1168   /* TAG no longer has any aliases.  */
1169   tag_ann->may_aliases = NULL;
1170 }
1171
1172
1173 /* Group may-aliases sets to reduce the number of virtual operands due
1174    to aliasing.
1175
1176      1- Sort the list of pointers in decreasing number of contributed
1177         virtual operands.
1178
1179      2- Take the first entry in AI->POINTERS and revert the role of
1180         the memory tag and its aliases.  Usually, whenever an aliased
1181         variable Vi is found to alias with a memory tag T, we add Vi
1182         to the may-aliases set for T.  Meaning that after alias
1183         analysis, we will have:
1184
1185                 may-aliases(T) = { V1, V2, V3, ..., Vn }
1186
1187         This means that every statement that references T, will get 'n'
1188         virtual operands for each of the Vi tags.  But, when alias
1189         grouping is enabled, we make T an alias tag and add it to the
1190         alias set of all the Vi variables:
1191
1192                 may-aliases(V1) = { T }
1193                 may-aliases(V2) = { T }
1194                 ...
1195                 may-aliases(Vn) = { T }
1196
1197         This has two effects: (a) statements referencing T will only get
1198         a single virtual operand, and, (b) all the variables Vi will now
1199         appear to alias each other.  So, we lose alias precision to
1200         improve compile time.  But, in theory, a program with such a high
1201         level of aliasing should not be very optimizable in the first
1202         place.
1203
1204      3- Since variables may be in the alias set of more than one
1205         memory tag, the grouping done in step (2) needs to be extended
1206         to all the memory tags that have a non-empty intersection with
1207         the may-aliases set of tag T.  For instance, if we originally
1208         had these may-aliases sets:
1209
1210                 may-aliases(T) = { V1, V2, V3 }
1211                 may-aliases(R) = { V2, V4 }
1212
1213         In step (2) we would have reverted the aliases for T as:
1214
1215                 may-aliases(V1) = { T }
1216                 may-aliases(V2) = { T }
1217                 may-aliases(V3) = { T }
1218
1219         But note that now V2 is no longer aliased with R.  We could
1220         add R to may-aliases(V2), but we are in the process of
1221         grouping aliases to reduce virtual operands so what we do is
1222         add V4 to the grouping to obtain:
1223
1224                 may-aliases(V1) = { T }
1225                 may-aliases(V2) = { T }
1226                 may-aliases(V3) = { T }
1227                 may-aliases(V4) = { T }
1228
1229      4- If the total number of virtual operands due to aliasing is
1230         still above the threshold set by max-alias-vops, go back to (2).  */
1231
1232 static void
1233 group_aliases (struct alias_info *ai)
1234 {
1235   size_t i;
1236
1237   /* Sort the POINTERS array in descending order of contributed
1238      virtual operands.  */
1239   qsort (ai->pointers, ai->num_pointers, sizeof (struct alias_map_d *),
1240          total_alias_vops_cmp);
1241
1242   /* For every pointer in AI->POINTERS, reverse the roles of its tag
1243      and the tag's may-aliases set.  */
1244   for (i = 0; i < ai->num_pointers; i++)
1245     {
1246       size_t j;
1247       tree tag1 = var_ann (ai->pointers[i]->var)->type_mem_tag;
1248       sbitmap tag1_aliases = ai->pointers[i]->may_aliases;
1249
1250       /* Skip tags that have been grouped already.  */
1251       if (ai->pointers[i]->grouped_p)
1252         continue;
1253
1254       /* See if TAG1 had any aliases in common with other type tags.
1255          If we find a TAG2 with common aliases with TAG1, add TAG2's
1256          aliases into TAG1.  */
1257       for (j = i + 1; j < ai->num_pointers; j++)
1258         {
1259           sbitmap tag2_aliases = ai->pointers[j]->may_aliases;
1260
1261           if (sbitmap_any_common_bits (tag1_aliases, tag2_aliases))
1262             {
1263               tree tag2 = var_ann (ai->pointers[j]->var)->type_mem_tag;
1264
1265               sbitmap_a_or_b (tag1_aliases, tag1_aliases, tag2_aliases);
1266
1267               /* TAG2 does not need its aliases anymore.  */
1268               sbitmap_zero (tag2_aliases);
1269               var_ann (tag2)->may_aliases = NULL;
1270
1271               /* TAG1 is the unique alias of TAG2.  */
1272               add_may_alias (tag2, tag1);
1273
1274               ai->pointers[j]->grouped_p = true;
1275             }
1276         }
1277
1278       /* Now group all the aliases we collected into TAG1.  */
1279       group_aliases_into (tag1, tag1_aliases, ai);
1280
1281       /* If we've reduced total number of virtual operands below the
1282          threshold, stop.  */
1283       if (ai->total_alias_vops < MAX_ALIASED_VOPS)
1284         break;
1285     }
1286
1287   /* Finally, all the variables that have been grouped cannot be in
1288      the may-alias set of name memory tags.  Suppose that we have
1289      grouped the aliases in this code so that may-aliases(a) = TMT.20
1290
1291         p_5 = &a;
1292         ...
1293         # a_9 = V_MAY_DEF <a_8>
1294         p_5->field = 0
1295         ... Several modifications to TMT.20 ... 
1296         # VUSE <a_9>
1297         x_30 = p_5->field
1298
1299      Since p_5 points to 'a', the optimizers will try to propagate 0
1300      into p_5->field, but that is wrong because there have been
1301      modifications to 'TMT.20' in between.  To prevent this we have to
1302      replace 'a' with 'TMT.20' in the name tag of p_5.  */
1303   for (i = 0; i < VARRAY_ACTIVE_SIZE (ai->processed_ptrs); i++)
1304     {
1305       size_t j;
1306       tree ptr = VARRAY_TREE (ai->processed_ptrs, i);
1307       tree name_tag = SSA_NAME_PTR_INFO (ptr)->name_mem_tag;
1308       varray_type aliases;
1309       
1310       if (name_tag == NULL_TREE)
1311         continue;
1312
1313       aliases = var_ann (name_tag)->may_aliases;
1314       for (j = 0; aliases && j < VARRAY_ACTIVE_SIZE (aliases); j++)
1315         {
1316           tree alias = VARRAY_TREE (aliases, j);
1317           var_ann_t ann = var_ann (alias);
1318
1319           if ((ann->mem_tag_kind == NOT_A_TAG 
1320                || ann->mem_tag_kind == STRUCT_FIELD)
1321               && ann->may_aliases)
1322             {
1323               tree new_alias;
1324
1325               gcc_assert (VARRAY_ACTIVE_SIZE (ann->may_aliases) == 1);
1326
1327               new_alias = VARRAY_TREE (ann->may_aliases, 0);
1328               replace_may_alias (name_tag, j, new_alias);
1329             }
1330         }
1331     }
1332
1333   if (dump_file)
1334     fprintf (dump_file,
1335              "%s: Total number of aliased vops after grouping: %ld%s\n",
1336              get_name (current_function_decl),
1337              ai->total_alias_vops,
1338              (ai->total_alias_vops < 0) ? " (negative values are OK)" : "");
1339 }
1340
1341
1342 /* Create a new alias set entry for VAR in AI->ADDRESSABLE_VARS.  */
1343
1344 static void
1345 create_alias_map_for (tree var, struct alias_info *ai)
1346 {
1347   struct alias_map_d *alias_map;
1348   alias_map = xcalloc (1, sizeof (*alias_map));
1349   alias_map->var = var;
1350   alias_map->set = get_alias_set (var);
1351   ai->addressable_vars[ai->num_addressable_vars++] = alias_map;
1352 }
1353
1354
1355 /* Create memory tags for all the dereferenced pointers and build the
1356    ADDRESSABLE_VARS and POINTERS arrays used for building the may-alias
1357    sets.  Based on the address escape and points-to information collected
1358    earlier, this pass will also clear the TREE_ADDRESSABLE flag from those
1359    variables whose address is not needed anymore.  */
1360
1361 static void
1362 setup_pointers_and_addressables (struct alias_info *ai)
1363 {
1364   size_t i, n_vars, num_addressable_vars, num_pointers;
1365
1366   /* Size up the arrays ADDRESSABLE_VARS and POINTERS.  */
1367   num_addressable_vars = num_pointers = 0;
1368   for (i = 0; i < num_referenced_vars; i++)
1369     {
1370       tree var = referenced_var (i);
1371
1372       if (may_be_aliased (var))
1373         num_addressable_vars++;
1374
1375       if (POINTER_TYPE_P (TREE_TYPE (var)))
1376         {
1377           /* Since we don't keep track of volatile variables, assume that
1378              these pointers are used in indirect store operations.  */
1379           if (TREE_THIS_VOLATILE (var))
1380             bitmap_set_bit (ai->dereferenced_ptrs_store, var_ann (var)->uid);
1381
1382           num_pointers++;
1383         }
1384     }
1385
1386   /* Create ADDRESSABLE_VARS and POINTERS.  Note that these arrays are
1387      always going to be slightly bigger than we actually need them
1388      because some TREE_ADDRESSABLE variables will be marked
1389      non-addressable below and only pointers with unique type tags are
1390      going to be added to POINTERS.  */
1391   ai->addressable_vars = xcalloc (num_addressable_vars,
1392                                   sizeof (struct alias_map_d *));
1393   ai->pointers = xcalloc (num_pointers, sizeof (struct alias_map_d *));
1394   ai->num_addressable_vars = 0;
1395   ai->num_pointers = 0;
1396
1397   /* Since we will be creating type memory tags within this loop, cache the
1398      value of NUM_REFERENCED_VARS to avoid processing the additional tags
1399      unnecessarily.  */
1400   n_vars = num_referenced_vars;
1401
1402   for (i = 0; i < n_vars; i++)
1403     {
1404       tree var = referenced_var (i);
1405       var_ann_t v_ann = var_ann (var);
1406       subvar_t svars;
1407
1408       /* Name memory tags already have flow-sensitive aliasing
1409          information, so they need not be processed by
1410          compute_flow_insensitive_aliasing.  Similarly, type memory
1411          tags are already accounted for when we process their
1412          associated pointer. 
1413       
1414          Structure fields, on the other hand, have to have some of this
1415          information processed for them, but it's pointless to mark them
1416          non-addressable (since they are fake variables anyway).  */
1417       if (v_ann->mem_tag_kind != NOT_A_TAG
1418           && v_ann->mem_tag_kind != STRUCT_FIELD) 
1419         continue;
1420
1421       /* Remove the ADDRESSABLE flag from every addressable variable whose
1422          address is not needed anymore.  This is caused by the propagation
1423          of ADDR_EXPR constants into INDIRECT_REF expressions and the
1424          removal of dead pointer assignments done by the early scalar
1425          cleanup passes.  */
1426       if (TREE_ADDRESSABLE (var) && v_ann->mem_tag_kind != STRUCT_FIELD)
1427         {
1428           if (!bitmap_bit_p (ai->addresses_needed, v_ann->uid)
1429               && TREE_CODE (var) != RESULT_DECL
1430               && !is_global_var (var))
1431             {
1432               bool okay_to_mark = true;
1433               /* Since VAR is now a regular GIMPLE register, we will need
1434                  to rename VAR into SSA afterwards.  */
1435               bitmap_set_bit (vars_to_rename, v_ann->uid);
1436
1437               if (var_can_have_subvars (var)
1438                   && (svars = get_subvars_for_var (var)))
1439                 {
1440                   subvar_t sv;
1441
1442                   for (sv = svars; sv; sv = sv->next)
1443                     {         
1444                       var_ann_t svann = var_ann (sv->var);
1445                       if (bitmap_bit_p (ai->addresses_needed, svann->uid))
1446                         okay_to_mark = false;
1447                       bitmap_set_bit (vars_to_rename, svann->uid);
1448                     }
1449                 }
1450               /* The address of VAR is not needed, remove the
1451                  addressable bit, so that it can be optimized as a
1452                  regular variable.  */
1453               if (okay_to_mark)
1454                 mark_non_addressable (var);
1455
1456             }
1457           else
1458             {
1459               /* Add the variable to the set of addressables.  Mostly
1460                  used when scanning operands for ASM_EXPRs that
1461                  clobber memory.  In those cases, we need to clobber
1462                  all call-clobbered variables and all addressables.  */
1463               bitmap_set_bit (addressable_vars, v_ann->uid);
1464               if (var_can_have_subvars (var)
1465                   && (svars = get_subvars_for_var (var)))
1466                 {
1467                   subvar_t sv;
1468                   for (sv = svars; sv; sv = sv->next)
1469                     bitmap_set_bit (addressable_vars, var_ann (sv->var)->uid);
1470                 }
1471
1472             }
1473         }
1474
1475       /* Global variables and addressable locals may be aliased.  Create an
1476          entry in ADDRESSABLE_VARS for VAR.  */
1477       if (may_be_aliased (var))
1478         {
1479           create_alias_map_for (var, ai);
1480           bitmap_set_bit (vars_to_rename, var_ann (var)->uid);    
1481         }
1482
1483       /* Add pointer variables that have been dereferenced to the POINTERS
1484          array and create a type memory tag for them.  */
1485       if (POINTER_TYPE_P (TREE_TYPE (var)))
1486         {
1487           if ((bitmap_bit_p (ai->dereferenced_ptrs_store, v_ann->uid)
1488                 || bitmap_bit_p (ai->dereferenced_ptrs_load, v_ann->uid)))
1489             {
1490               tree tag;
1491               var_ann_t t_ann;
1492
1493               /* If pointer VAR still doesn't have a memory tag
1494                  associated with it, create it now or re-use an
1495                  existing one.  */
1496               tag = get_tmt_for (var, ai);
1497               t_ann = var_ann (tag);
1498
1499               /* The type tag will need to be renamed into SSA
1500                  afterwards. Note that we cannot do this inside
1501                  get_tmt_for because aliasing may run multiple times
1502                  and we only create type tags the first time.  */
1503               bitmap_set_bit (vars_to_rename, t_ann->uid);
1504
1505               /* Associate the tag with pointer VAR.  */
1506               v_ann->type_mem_tag = tag;
1507
1508               /* If pointer VAR has been used in a store operation,
1509                  then its memory tag must be marked as written-to.  */
1510               if (bitmap_bit_p (ai->dereferenced_ptrs_store, v_ann->uid))
1511                 bitmap_set_bit (ai->written_vars, t_ann->uid);
1512
1513               /* If pointer VAR is a global variable or a PARM_DECL,
1514                  then its memory tag should be considered a global
1515                  variable.  */
1516               if (TREE_CODE (var) == PARM_DECL || is_global_var (var))
1517                 mark_call_clobbered (tag);
1518
1519               /* All the dereferences of pointer VAR count as
1520                  references of TAG.  Since TAG can be associated with
1521                  several pointers, add the dereferences of VAR to the
1522                  TAG.  We may need to grow AI->NUM_REFERENCES because
1523                  we have been adding name and type tags.  */
1524               if (t_ann->uid >= VARRAY_SIZE (ai->num_references))
1525                 VARRAY_GROW (ai->num_references, t_ann->uid + 10);
1526
1527               VARRAY_UINT (ai->num_references, t_ann->uid)
1528                 += VARRAY_UINT (ai->num_references, v_ann->uid);
1529             }
1530           else
1531             {
1532               /* The pointer has not been dereferenced.  If it had a
1533                  type memory tag, remove it and mark the old tag for
1534                  renaming to remove it out of the IL.  */
1535               var_ann_t ann = var_ann (var);
1536               tree tag = ann->type_mem_tag;
1537               if (tag)
1538                 {
1539                   bitmap_set_bit (vars_to_rename, var_ann (tag)->uid);
1540                   ann->type_mem_tag = NULL_TREE;
1541                 }
1542             }
1543         }
1544     }
1545 }
1546
1547
1548 /* Determine whether to use .GLOBAL_VAR to model call clobbering semantics. At
1549    every call site, we need to emit V_MAY_DEF expressions to represent the
1550    clobbering effects of the call for variables whose address escapes the
1551    current function.
1552
1553    One approach is to group all call-clobbered variables into a single
1554    representative that is used as an alias of every call-clobbered variable
1555    (.GLOBAL_VAR).  This works well, but it ties the optimizer hands because
1556    references to any call clobbered variable is a reference to .GLOBAL_VAR.
1557
1558    The second approach is to emit a clobbering V_MAY_DEF for every 
1559    call-clobbered variable at call sites.  This is the preferred way in terms 
1560    of optimization opportunities but it may create too many V_MAY_DEF operands
1561    if there are many call clobbered variables and function calls in the 
1562    function.
1563
1564    To decide whether or not to use .GLOBAL_VAR we multiply the number of
1565    function calls found by the number of call-clobbered variables.  If that
1566    product is beyond a certain threshold, as determined by the parameterized
1567    values shown below, we use .GLOBAL_VAR.
1568
1569    FIXME.  This heuristic should be improved.  One idea is to use several
1570    .GLOBAL_VARs of different types instead of a single one.  The thresholds
1571    have been derived from a typical bootstrap cycle, including all target
1572    libraries. Compile times were found increase by ~1% compared to using
1573    .GLOBAL_VAR.  */
1574
1575 static void
1576 maybe_create_global_var (struct alias_info *ai)
1577 {
1578   unsigned i, n_clobbered;
1579   bitmap_iterator bi;
1580   
1581   /* No need to create it, if we have one already.  */
1582   if (global_var == NULL_TREE)
1583     {
1584       /* Count all the call-clobbered variables.  */
1585       n_clobbered = 0;
1586       EXECUTE_IF_SET_IN_BITMAP (call_clobbered_vars, 0, i, bi)
1587         {
1588           n_clobbered++;
1589         }
1590
1591       /* If the number of virtual operands that would be needed to
1592          model all the call-clobbered variables is larger than
1593          GLOBAL_VAR_THRESHOLD, create .GLOBAL_VAR.
1594
1595          Also create .GLOBAL_VAR if there are no call-clobbered
1596          variables and the program contains a mixture of pure/const
1597          and regular function calls.  This is to avoid the problem
1598          described in PR 20115:
1599
1600               int X;
1601               int func_pure (void) { return X; }
1602               int func_non_pure (int a) { X += a; }
1603               int foo ()
1604               {
1605                 int a = func_pure ();
1606                 func_non_pure (a);
1607                 a = func_pure ();
1608                 return a;
1609               }
1610
1611          Since foo() has no call-clobbered variables, there is
1612          no relationship between the calls to func_pure and
1613          func_non_pure.  Since func_pure has no side-effects, value
1614          numbering optimizations elide the second call to func_pure.
1615          So, if we have some pure/const and some regular calls in the
1616          program we create .GLOBAL_VAR to avoid missing these
1617          relations.  */
1618       if (ai->num_calls_found * n_clobbered >= (size_t) GLOBAL_VAR_THRESHOLD
1619           || (n_clobbered == 0
1620               && ai->num_calls_found > 0
1621               && ai->num_pure_const_calls_found > 0
1622               && ai->num_calls_found > ai->num_pure_const_calls_found))
1623         create_global_var ();
1624     }
1625
1626   /* Mark all call-clobbered symbols for renaming.  Since the initial
1627      rewrite into SSA ignored all call sites, we may need to rename
1628      .GLOBAL_VAR and the call-clobbered variables.  */
1629   EXECUTE_IF_SET_IN_BITMAP (call_clobbered_vars, 0, i, bi)
1630     {
1631       tree var = referenced_var (i);
1632
1633       /* If the function has calls to clobbering functions and
1634          .GLOBAL_VAR has been created, make it an alias for all
1635          call-clobbered variables.  */
1636       if (global_var && var != global_var)
1637         {
1638           subvar_t svars;
1639           add_may_alias (var, global_var);
1640           if (var_can_have_subvars (var)
1641               && (svars = get_subvars_for_var (var)))
1642             {
1643               subvar_t sv;
1644               for (sv = svars; sv; sv = sv->next)
1645                 bitmap_set_bit (vars_to_rename, var_ann (sv->var)->uid);
1646             }
1647         }
1648       
1649       bitmap_set_bit (vars_to_rename, var_ann (var)->uid);
1650     }
1651 }
1652
1653
1654 /* Return TRUE if pointer PTR may point to variable VAR.
1655    
1656    MEM_ALIAS_SET is the alias set for the memory location pointed-to by PTR
1657         This is needed because when checking for type conflicts we are
1658         interested in the alias set of the memory location pointed-to by
1659         PTR.  The alias set of PTR itself is irrelevant.
1660    
1661    VAR_ALIAS_SET is the alias set for VAR.  */
1662
1663 static bool
1664 may_alias_p (tree ptr, HOST_WIDE_INT mem_alias_set,
1665              tree var, HOST_WIDE_INT var_alias_set)
1666 {
1667   tree mem;
1668   var_ann_t m_ann;
1669
1670   alias_stats.alias_queries++;
1671   alias_stats.simple_queries++;
1672
1673   /* By convention, a variable cannot alias itself.  */
1674   mem = var_ann (ptr)->type_mem_tag;
1675   if (mem == var)
1676     {
1677       alias_stats.alias_noalias++;
1678       alias_stats.simple_resolved++;
1679       return false;
1680     }
1681
1682   m_ann = var_ann (mem);
1683
1684   gcc_assert (m_ann->mem_tag_kind == TYPE_TAG);
1685
1686   alias_stats.tbaa_queries++;
1687
1688   /* If VAR is a pointer with the same alias set as PTR, then dereferencing
1689      PTR can't possibly affect VAR.  Note, that we are specifically testing
1690      for PTR's alias set here, not its pointed-to type.  We also can't
1691      do this check with relaxed aliasing enabled.  */
1692   if (POINTER_TYPE_P (TREE_TYPE (var))
1693       && var_alias_set != 0
1694       && mem_alias_set != 0)
1695     {
1696       HOST_WIDE_INT ptr_alias_set = get_alias_set (ptr);
1697       if (ptr_alias_set == var_alias_set)
1698         {
1699           alias_stats.alias_noalias++;
1700           alias_stats.tbaa_resolved++;
1701           return false;
1702         }
1703     }
1704
1705   /* If the alias sets don't conflict then MEM cannot alias VAR.  */
1706   if (!alias_sets_conflict_p (mem_alias_set, var_alias_set))
1707     {
1708       alias_stats.alias_noalias++;
1709       alias_stats.tbaa_resolved++;
1710       return false;
1711     }
1712   alias_stats.alias_mayalias++;
1713   return true;
1714 }
1715
1716
1717 /* Add ALIAS to the set of variables that may alias VAR.  */
1718
1719 static void
1720 add_may_alias (tree var, tree alias)
1721 {
1722   size_t i;
1723   var_ann_t v_ann = get_var_ann (var);
1724   var_ann_t a_ann = get_var_ann (alias);
1725
1726   gcc_assert (var != alias);
1727
1728   if (v_ann->may_aliases == NULL)
1729     VARRAY_TREE_INIT (v_ann->may_aliases, 2, "aliases");
1730
1731   /* Avoid adding duplicates.  */
1732   for (i = 0; i < VARRAY_ACTIVE_SIZE (v_ann->may_aliases); i++)
1733     if (alias == VARRAY_TREE (v_ann->may_aliases, i))
1734       return;
1735
1736   /* If VAR is a call-clobbered variable, so is its new ALIAS.
1737      FIXME, call-clobbering should only depend on whether an address
1738      escapes.  It should be independent of aliasing.  */
1739   if (is_call_clobbered (var))
1740     mark_call_clobbered (alias);
1741
1742   /* Likewise.  If ALIAS is call-clobbered, so is VAR.  */
1743   else if (is_call_clobbered (alias))
1744     mark_call_clobbered (var);
1745
1746   VARRAY_PUSH_TREE (v_ann->may_aliases, alias);
1747   a_ann->is_alias_tag = 1;
1748 }
1749
1750
1751 /* Replace alias I in the alias sets of VAR with NEW_ALIAS.  */
1752
1753 static void
1754 replace_may_alias (tree var, size_t i, tree new_alias)
1755 {
1756   var_ann_t v_ann = var_ann (var);
1757   VARRAY_TREE (v_ann->may_aliases, i) = new_alias;
1758
1759   /* If VAR is a call-clobbered variable, so is NEW_ALIAS.
1760      FIXME, call-clobbering should only depend on whether an address
1761      escapes.  It should be independent of aliasing.  */
1762   if (is_call_clobbered (var))
1763     mark_call_clobbered (new_alias);
1764
1765   /* Likewise.  If NEW_ALIAS is call-clobbered, so is VAR.  */
1766   else if (is_call_clobbered (new_alias))
1767     mark_call_clobbered (var);
1768 }
1769
1770
1771 /* Mark pointer PTR as pointing to an arbitrary memory location.  */
1772
1773 static void
1774 set_pt_anything (tree ptr)
1775 {
1776   struct ptr_info_def *pi = get_ptr_info (ptr);
1777
1778   pi->pt_anything = 1;
1779   pi->pt_malloc = 0;
1780
1781   /* The pointer used to have a name tag, but we now found it pointing
1782      to an arbitrary location.  The name tag needs to be renamed and
1783      disassociated from PTR.  */
1784   if (pi->name_mem_tag)
1785     {
1786       bitmap_set_bit (vars_to_rename, var_ann (pi->name_mem_tag)->uid);
1787       pi->name_mem_tag = NULL_TREE;
1788     }
1789 }
1790
1791
1792 /* Mark pointer PTR as pointing to a malloc'd memory area.  */
1793
1794 static void
1795 set_pt_malloc (tree ptr)
1796 {
1797   struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
1798
1799   /* If the pointer has already been found to point to arbitrary
1800      memory locations, it is unsafe to mark it as pointing to malloc.  */
1801   if (pi->pt_anything)
1802     return;
1803
1804   pi->pt_malloc = 1;
1805 }
1806
1807
1808 /* Given two different pointers DEST and ORIG.  Merge the points-to
1809    information in ORIG into DEST.  AI contains all the alias
1810    information collected up to this point.  */
1811
1812 static void
1813 merge_pointed_to_info (struct alias_info *ai, tree dest, tree orig)
1814 {
1815   struct ptr_info_def *dest_pi, *orig_pi;
1816
1817   gcc_assert (dest != orig);
1818
1819   /* Make sure we have points-to information for ORIG.  */
1820   collect_points_to_info_for (ai, orig);
1821
1822   dest_pi = get_ptr_info (dest);
1823   orig_pi = SSA_NAME_PTR_INFO (orig);
1824
1825   if (orig_pi)
1826     {
1827       gcc_assert (orig_pi != dest_pi);
1828
1829       /* Notice that we never merge PT_MALLOC.  This attribute is only
1830          true if the pointer is the result of a malloc() call.
1831          Otherwise, we can end up in this situation:
1832
1833          P_i = malloc ();
1834          ...
1835          P_j = P_i + X;
1836
1837          P_j would be marked as PT_MALLOC, however we currently do not
1838          handle cases of more than one pointer pointing to the same
1839          malloc'd area.
1840
1841          FIXME: If the merging comes from an expression that preserves
1842          the PT_MALLOC attribute (copy assignment, address
1843          arithmetic), we ought to merge PT_MALLOC, but then both
1844          pointers would end up getting different name tags because
1845          create_name_tags is not smart enough to determine that the
1846          two come from the same malloc call.  Copy propagation before
1847          aliasing should cure this.  */
1848       dest_pi->pt_malloc = 0;
1849       if (orig_pi->pt_malloc || orig_pi->pt_anything)
1850         set_pt_anything (dest);
1851
1852       dest_pi->pt_null |= orig_pi->pt_null;
1853
1854       if (!dest_pi->pt_anything
1855           && orig_pi->pt_vars
1856           && !bitmap_empty_p (orig_pi->pt_vars))
1857         {
1858           if (dest_pi->pt_vars == NULL)
1859             {
1860               dest_pi->pt_vars = BITMAP_GGC_ALLOC ();
1861               bitmap_copy (dest_pi->pt_vars, orig_pi->pt_vars);
1862             }
1863           else
1864             bitmap_ior_into (dest_pi->pt_vars, orig_pi->pt_vars);
1865         }
1866     }
1867   else
1868     set_pt_anything (dest);
1869 }
1870
1871
1872 /* Add EXPR to the list of expressions pointed-to by PTR.  */
1873
1874 static void
1875 add_pointed_to_expr (struct alias_info *ai, tree ptr, tree expr)
1876 {
1877   if (TREE_CODE (expr) == WITH_SIZE_EXPR)
1878     expr = TREE_OPERAND (expr, 0);
1879
1880   get_ptr_info (ptr);
1881
1882   if (TREE_CODE (expr) == CALL_EXPR
1883       && (call_expr_flags (expr) & (ECF_MALLOC | ECF_MAY_BE_ALLOCA)))
1884     {
1885       /* If EXPR is a malloc-like call, then the area pointed to PTR
1886          is guaranteed to not alias with anything else.  */
1887       set_pt_malloc (ptr);
1888     }
1889   else if (TREE_CODE (expr) == ADDR_EXPR)
1890     {
1891       /* Found P_i = ADDR_EXPR  */
1892       add_pointed_to_var (ai, ptr, expr);
1893     }
1894   else if (TREE_CODE (expr) == SSA_NAME && POINTER_TYPE_P (TREE_TYPE (expr)))
1895     {
1896       /* Found P_i = Q_j.  */
1897       merge_pointed_to_info (ai, ptr, expr);
1898     }
1899   else if (TREE_CODE (expr) == PLUS_EXPR || TREE_CODE (expr) == MINUS_EXPR)
1900     {
1901       /* Found P_i = PLUS_EXPR or P_i = MINUS_EXPR  */
1902       tree op0 = TREE_OPERAND (expr, 0);
1903       tree op1 = TREE_OPERAND (expr, 1);
1904
1905       /* Both operands may be of pointer type.  FIXME: Shouldn't
1906          we just expect PTR + OFFSET always?  */
1907       if (POINTER_TYPE_P (TREE_TYPE (op0))
1908           && TREE_CODE (op0) != INTEGER_CST)
1909         {
1910           if (TREE_CODE (op0) == SSA_NAME)
1911             merge_pointed_to_info (ai, ptr, op0);
1912           else if (TREE_CODE (op0) == ADDR_EXPR)
1913             add_pointed_to_var (ai, ptr, op0);
1914           else
1915             set_pt_anything (ptr);
1916         }
1917
1918       if (POINTER_TYPE_P (TREE_TYPE (op1))
1919           && TREE_CODE (op1) != INTEGER_CST)
1920         {
1921           if (TREE_CODE (op1) == SSA_NAME)
1922             merge_pointed_to_info (ai, ptr, op1);
1923           else if (TREE_CODE (op1) == ADDR_EXPR)
1924             add_pointed_to_var (ai, ptr, op1);
1925           else
1926             set_pt_anything (ptr);
1927         }
1928
1929       /* Neither operand is a pointer?  VAR can be pointing anywhere.
1930          FIXME: Shouldn't we abort here?  If we get here, we found
1931          PTR = INT_CST + INT_CST, which should not be a valid pointer
1932          expression.  */
1933       if (!(POINTER_TYPE_P (TREE_TYPE (op0))
1934             && TREE_CODE (op0) != INTEGER_CST)
1935           && !(POINTER_TYPE_P (TREE_TYPE (op1))
1936                && TREE_CODE (op1) != INTEGER_CST))
1937         set_pt_anything (ptr);
1938     }
1939   else if (integer_zerop (expr))
1940     {
1941       /* EXPR is the NULL pointer.  Mark PTR as pointing to NULL.  */
1942       SSA_NAME_PTR_INFO (ptr)->pt_null = 1;
1943     }
1944   else
1945     {
1946       /* If we can't recognize the expression, assume that PTR may
1947          point anywhere.  */
1948       set_pt_anything (ptr);
1949     }
1950 }
1951
1952
1953 /* If VALUE is of the form &DECL, add DECL to the set of variables
1954    pointed-to by PTR.  Otherwise, add VALUE as a pointed-to expression by
1955    PTR.  AI points to the collected alias information.  */
1956
1957 static void
1958 add_pointed_to_var (struct alias_info *ai, tree ptr, tree value)
1959 {
1960   struct ptr_info_def *pi = get_ptr_info (ptr);
1961   tree pt_var = NULL_TREE;
1962   HOST_WIDE_INT offset, size;
1963   tree addrop;
1964   size_t uid;
1965   tree ref;
1966   subvar_t svars;
1967
1968   gcc_assert (TREE_CODE (value) == ADDR_EXPR);
1969
1970   addrop = TREE_OPERAND (value, 0);
1971   if (REFERENCE_CLASS_P (addrop))
1972     pt_var = get_base_address (addrop);
1973   else 
1974     pt_var = addrop;
1975
1976   /* If this is a component_ref, see if we can get a smaller number of
1977      variables to take the address of.  */
1978   if (TREE_CODE (addrop) == COMPONENT_REF
1979       && (ref = okay_component_ref_for_subvars (addrop, &offset ,&size)))
1980     {    
1981       subvar_t sv;
1982       svars = get_subvars_for_var (ref);
1983
1984       uid = var_ann (pt_var)->uid;
1985       bitmap_set_bit (ai->addresses_needed, uid);
1986       if (pi->pt_vars == NULL)
1987         pi->pt_vars = BITMAP_GGC_ALLOC ();
1988        /* If the variable is a global, mark the pointer as pointing to
1989          global memory (which will make its tag a global variable).  */
1990       if (is_global_var (pt_var))
1991         pi->pt_global_mem = 1;     
1992
1993       for (sv = svars; sv; sv = sv->next)
1994         {
1995           if (overlap_subvar (offset, size, sv, NULL))
1996             bitmap_set_bit (pi->pt_vars, var_ann (sv->var)->uid);
1997         }
1998     }
1999   else if (pt_var && SSA_VAR_P (pt_var))
2000     {
2001     
2002       uid = var_ann (pt_var)->uid;
2003       bitmap_set_bit (ai->addresses_needed, uid);
2004
2005       if (pi->pt_vars == NULL)
2006         pi->pt_vars = BITMAP_GGC_ALLOC ();
2007
2008       /* If this is an aggregate, we may have subvariables for it that need
2009          to be pointed to.  */
2010       if (var_can_have_subvars (pt_var)
2011           && (svars = get_subvars_for_var (pt_var)))
2012         {
2013           subvar_t sv;
2014           for (sv = svars; sv; sv = sv->next)
2015             {
2016               uid = var_ann (sv->var)->uid;
2017               bitmap_set_bit (ai->addresses_needed, uid);             
2018               bitmap_set_bit (pi->pt_vars, uid);
2019             }
2020         }
2021       else      
2022         bitmap_set_bit (pi->pt_vars, uid);        
2023
2024       /* If the variable is a global, mark the pointer as pointing to
2025          global memory (which will make its tag a global variable).  */
2026       if (is_global_var (pt_var))
2027         pi->pt_global_mem = 1;
2028     }
2029 }
2030
2031
2032 /* Callback for walk_use_def_chains to gather points-to information from the
2033    SSA web.
2034    
2035    VAR is an SSA variable or a GIMPLE expression.
2036    
2037    STMT is the statement that generates the SSA variable or, if STMT is a
2038       PHI_NODE, VAR is one of the PHI arguments.
2039
2040    DATA is a pointer to a structure of type ALIAS_INFO.  */
2041
2042 static bool
2043 collect_points_to_info_r (tree var, tree stmt, void *data)
2044 {
2045   struct alias_info *ai = (struct alias_info *) data;
2046
2047   if (dump_file && (dump_flags & TDF_DETAILS))
2048     {
2049       fprintf (dump_file, "Visiting use-def links for ");
2050       print_generic_expr (dump_file, var, dump_flags);
2051       fprintf (dump_file, "\n");
2052     }
2053
2054   switch (TREE_CODE (stmt))
2055     {
2056     case RETURN_EXPR:
2057       if (TREE_CODE (TREE_OPERAND (stmt, 0)) != MODIFY_EXPR)
2058         abort ();
2059       stmt = TREE_OPERAND (stmt, 0);
2060       /* FALLTHRU  */
2061
2062     case MODIFY_EXPR:
2063       {
2064         tree rhs = TREE_OPERAND (stmt, 1);
2065         STRIP_NOPS (rhs);
2066         add_pointed_to_expr (ai, var, rhs);
2067         break;
2068       }
2069
2070     case ASM_EXPR:
2071       /* Pointers defined by __asm__ statements can point anywhere.  */
2072       set_pt_anything (var);
2073       break;
2074
2075     case NOP_EXPR:
2076       if (IS_EMPTY_STMT (stmt))
2077         {
2078           tree decl = SSA_NAME_VAR (var);
2079           
2080           if (TREE_CODE (decl) == PARM_DECL)
2081             add_pointed_to_expr (ai, var, decl);
2082           else if (DECL_INITIAL (decl))
2083             add_pointed_to_expr (ai, var, DECL_INITIAL (decl));
2084           else
2085             add_pointed_to_expr (ai, var, decl);
2086         }
2087       break;
2088
2089     case PHI_NODE:
2090       {
2091         /* It STMT is a PHI node, then VAR is one of its arguments.  The
2092            variable that we are analyzing is the LHS of the PHI node.  */
2093         tree lhs = PHI_RESULT (stmt);
2094
2095         switch (TREE_CODE (var))
2096           {
2097           case ADDR_EXPR:
2098             add_pointed_to_var (ai, lhs, var);
2099             break;
2100             
2101           case SSA_NAME:
2102             /* Avoid unnecessary merges.  */
2103             if (lhs != var)
2104               merge_pointed_to_info (ai, lhs, var);
2105             break;
2106             
2107           default:
2108             gcc_assert (is_gimple_min_invariant (var));
2109             add_pointed_to_expr (ai, lhs, var);
2110             break;
2111           }
2112         break;
2113       }
2114
2115     default:
2116       gcc_unreachable ();
2117     }
2118   
2119   return false;
2120 }
2121
2122
2123 /* Return true if STMT is an "escape" site from the current function.  Escape
2124    sites those statements which might expose the address of a variable
2125    outside the current function.  STMT is an escape site iff:
2126
2127         1- STMT is a function call, or
2128         2- STMT is an __asm__ expression, or
2129         3- STMT is an assignment to a non-local variable, or
2130         4- STMT is a return statement.
2131
2132    AI points to the alias information collected so far.  */
2133
2134 static bool
2135 is_escape_site (tree stmt, struct alias_info *ai)
2136 {
2137   tree call = get_call_expr_in (stmt);
2138   if (call != NULL_TREE)
2139     {
2140       ai->num_calls_found++;
2141
2142       if (!TREE_SIDE_EFFECTS (call))
2143         ai->num_pure_const_calls_found++;
2144
2145       return true;
2146     }
2147   else if (TREE_CODE (stmt) == ASM_EXPR)
2148     return true;
2149   else if (TREE_CODE (stmt) == MODIFY_EXPR)
2150     {
2151       tree lhs = TREE_OPERAND (stmt, 0);
2152
2153       /* Get to the base of _REF nodes.  */
2154       if (TREE_CODE (lhs) != SSA_NAME)
2155         lhs = get_base_address (lhs);
2156
2157       /* If we couldn't recognize the LHS of the assignment, assume that it
2158          is a non-local store.  */
2159       if (lhs == NULL_TREE)
2160         return true;
2161
2162       /* If the RHS is a conversion between a pointer and an integer, the
2163          pointer escapes since we can't track the integer.  */
2164       if ((TREE_CODE (TREE_OPERAND (stmt, 1)) == NOP_EXPR
2165            || TREE_CODE (TREE_OPERAND (stmt, 1)) == CONVERT_EXPR
2166            || TREE_CODE (TREE_OPERAND (stmt, 1)) == VIEW_CONVERT_EXPR)
2167           && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND
2168                                         (TREE_OPERAND (stmt, 1), 0)))
2169           && !POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (stmt, 1))))
2170         return true;
2171
2172       /* If the LHS is an SSA name, it can't possibly represent a non-local
2173          memory store.  */
2174       if (TREE_CODE (lhs) == SSA_NAME)
2175         return false;
2176
2177       /* FIXME: LHS is not an SSA_NAME.  Even if it's an assignment to a
2178          local variables we cannot be sure if it will escape, because we
2179          don't have information about objects not in SSA form.  Need to
2180          implement something along the lines of
2181
2182          J.-D. Choi, M. Gupta, M. J. Serrano, V. C. Sreedhar, and S. P.
2183          Midkiff, ``Escape analysis for java,'' in Proceedings of the
2184          Conference on Object-Oriented Programming Systems, Languages, and
2185          Applications (OOPSLA), pp. 1-19, 1999.  */
2186       return true;
2187     }
2188   else if (TREE_CODE (stmt) == RETURN_EXPR)
2189     return true;
2190
2191   return false;
2192 }
2193
2194
2195 /* Create a new memory tag of type TYPE.  If IS_TYPE_TAG is true, the tag
2196    is considered to represent all the pointers whose pointed-to types are
2197    in the same alias set class.  Otherwise, the tag represents a single
2198    SSA_NAME pointer variable.  */
2199
2200 static tree
2201 create_memory_tag (tree type, bool is_type_tag)
2202 {
2203   var_ann_t ann;
2204   tree tag = create_tmp_var_raw (type, (is_type_tag) ? "TMT" : "NMT");
2205
2206   /* By default, memory tags are local variables.  Alias analysis will
2207      determine whether they should be considered globals.  */
2208   DECL_CONTEXT (tag) = current_function_decl;
2209
2210   /* Memory tags are by definition addressable.  This also prevents
2211      is_gimple_ref frome confusing memory tags with optimizable
2212      variables.  */
2213   TREE_ADDRESSABLE (tag) = 1;
2214
2215   ann = get_var_ann (tag);
2216   ann->mem_tag_kind = (is_type_tag) ? TYPE_TAG : NAME_TAG;
2217   ann->type_mem_tag = NULL_TREE;
2218
2219   /* Add the tag to the symbol table.  */
2220   add_referenced_tmp_var (tag);
2221
2222   return tag;
2223 }
2224
2225
2226 /* Create a name memory tag to represent a specific SSA_NAME pointer P_i.
2227    This is used if P_i has been found to point to a specific set of
2228    variables or to a non-aliased memory location like the address returned
2229    by malloc functions.  */
2230
2231 static tree
2232 get_nmt_for (tree ptr)
2233 {
2234   struct ptr_info_def *pi = get_ptr_info (ptr);
2235   tree tag = pi->name_mem_tag;
2236
2237   if (tag == NULL_TREE)
2238     tag = create_memory_tag (TREE_TYPE (TREE_TYPE (ptr)), false);
2239
2240   /* If PTR is a PARM_DECL, it points to a global variable or malloc,
2241      then its name tag should be considered a global variable.  */
2242   if (TREE_CODE (SSA_NAME_VAR (ptr)) == PARM_DECL
2243       || pi->pt_malloc
2244       || pi->pt_global_mem)
2245     mark_call_clobbered (tag);
2246
2247   return tag;
2248 }
2249
2250
2251 /* Return the type memory tag associated to pointer PTR.  A memory tag is an
2252    artificial variable that represents the memory location pointed-to by
2253    PTR.  It is used to model the effects of pointer de-references on
2254    addressable variables.
2255    
2256    AI points to the data gathered during alias analysis.  This function
2257    populates the array AI->POINTERS.  */
2258
2259 static tree
2260 get_tmt_for (tree ptr, struct alias_info *ai)
2261 {
2262   size_t i;
2263   tree tag;
2264   tree tag_type = TREE_TYPE (TREE_TYPE (ptr));
2265   HOST_WIDE_INT tag_set = get_alias_set (tag_type);
2266
2267   /* To avoid creating unnecessary memory tags, only create one memory tag
2268      per alias set class.  Note that it may be tempting to group
2269      memory tags based on conflicting alias sets instead of
2270      equivalence.  That would be wrong because alias sets are not
2271      necessarily transitive (as demonstrated by the libstdc++ test
2272      23_containers/vector/cons/4.cc).  Given three alias sets A, B, C
2273      such that conflicts (A, B) == true and conflicts (A, C) == true,
2274      it does not necessarily follow that conflicts (B, C) == true.  */
2275   for (i = 0, tag = NULL_TREE; i < ai->num_pointers; i++)
2276     {
2277       struct alias_map_d *curr = ai->pointers[i];
2278       if (tag_set == curr->set)
2279         {
2280           tag = var_ann (curr->var)->type_mem_tag;
2281           break;
2282         }
2283     }
2284
2285   /* If VAR cannot alias with any of the existing memory tags, create a new
2286      tag for PTR and add it to the POINTERS array.  */
2287   if (tag == NULL_TREE)
2288     {
2289       struct alias_map_d *alias_map;
2290
2291       /* If PTR did not have a type tag already, create a new TMT.*
2292          artificial variable representing the memory location
2293          pointed-to by PTR.  */
2294       if (var_ann (ptr)->type_mem_tag == NULL_TREE)
2295         tag = create_memory_tag (tag_type, true);
2296       else
2297         tag = var_ann (ptr)->type_mem_tag;
2298
2299       /* Add PTR to the POINTERS array.  Note that we are not interested in
2300          PTR's alias set.  Instead, we cache the alias set for the memory that
2301          PTR points to.  */
2302       alias_map = xcalloc (1, sizeof (*alias_map));
2303       alias_map->var = ptr;
2304       alias_map->set = tag_set;
2305       ai->pointers[ai->num_pointers++] = alias_map;
2306     }
2307
2308   /* If the pointed-to type is volatile, so is the tag.  */
2309   TREE_THIS_VOLATILE (tag) |= TREE_THIS_VOLATILE (tag_type);
2310
2311   /* Make sure that the type tag has the same alias set as the
2312      pointed-to type.  */
2313   gcc_assert (tag_set == get_alias_set (tag));
2314
2315   return tag;
2316 }
2317
2318
2319 /* Create GLOBAL_VAR, an artificial global variable to act as a
2320    representative of all the variables that may be clobbered by function
2321    calls.  */
2322
2323 static void
2324 create_global_var (void)
2325 {
2326   global_var = build_decl (VAR_DECL, get_identifier (".GLOBAL_VAR"),
2327                            void_type_node);
2328   DECL_ARTIFICIAL (global_var) = 1;
2329   TREE_READONLY (global_var) = 0;
2330   DECL_EXTERNAL (global_var) = 1;
2331   TREE_STATIC (global_var) = 1;
2332   TREE_USED (global_var) = 1;
2333   DECL_CONTEXT (global_var) = NULL_TREE;
2334   TREE_THIS_VOLATILE (global_var) = 0;
2335   TREE_ADDRESSABLE (global_var) = 0;
2336
2337   add_referenced_tmp_var (global_var);
2338   bitmap_set_bit (vars_to_rename, var_ann (global_var)->uid);
2339 }
2340
2341
2342 /* Dump alias statistics on FILE.  */
2343
2344 static void 
2345 dump_alias_stats (FILE *file)
2346 {
2347   const char *funcname
2348     = lang_hooks.decl_printable_name (current_function_decl, 2);
2349   fprintf (file, "\nAlias statistics for %s\n\n", funcname);
2350   fprintf (file, "Total alias queries:\t%u\n", alias_stats.alias_queries);
2351   fprintf (file, "Total alias mayalias results:\t%u\n", 
2352            alias_stats.alias_mayalias);
2353   fprintf (file, "Total alias noalias results:\t%u\n",
2354            alias_stats.alias_noalias);
2355   fprintf (file, "Total simple queries:\t%u\n",
2356            alias_stats.simple_queries);
2357   fprintf (file, "Total simple resolved:\t%u\n",
2358            alias_stats.simple_resolved);
2359   fprintf (file, "Total TBAA queries:\t%u\n",
2360            alias_stats.tbaa_queries);
2361   fprintf (file, "Total TBAA resolved:\t%u\n",
2362            alias_stats.tbaa_resolved);
2363 }
2364   
2365
2366 /* Dump alias information on FILE.  */
2367
2368 void
2369 dump_alias_info (FILE *file)
2370 {
2371   size_t i;
2372   const char *funcname
2373     = lang_hooks.decl_printable_name (current_function_decl, 2);
2374
2375   fprintf (file, "\nFlow-insensitive alias information for %s\n\n", funcname);
2376
2377   fprintf (file, "Aliased symbols\n\n");
2378   for (i = 0; i < num_referenced_vars; i++)
2379     {
2380       tree var = referenced_var (i);
2381       if (may_be_aliased (var))
2382         dump_variable (file, var);
2383     }
2384
2385   fprintf (file, "\nDereferenced pointers\n\n");
2386   for (i = 0; i < num_referenced_vars; i++)
2387     {
2388       tree var = referenced_var (i);
2389       var_ann_t ann = var_ann (var);
2390       if (ann->type_mem_tag)
2391         dump_variable (file, var);
2392     }
2393
2394   fprintf (file, "\nType memory tags\n\n");
2395   for (i = 0; i < num_referenced_vars; i++)
2396     {
2397       tree var = referenced_var (i);
2398       var_ann_t ann = var_ann (var);
2399       if (ann->mem_tag_kind == TYPE_TAG)
2400         dump_variable (file, var);
2401     }
2402
2403   fprintf (file, "\n\nFlow-sensitive alias information for %s\n\n", funcname);
2404
2405   fprintf (file, "SSA_NAME pointers\n\n");
2406   for (i = 1; i < num_ssa_names; i++)
2407     {
2408       tree ptr = ssa_name (i);
2409       struct ptr_info_def *pi;
2410       
2411       if (ptr == NULL_TREE)
2412         continue;
2413
2414       pi = SSA_NAME_PTR_INFO (ptr);
2415       if (!SSA_NAME_IN_FREE_LIST (ptr)
2416           && pi
2417           && pi->name_mem_tag)
2418         dump_points_to_info_for (file, ptr);
2419     }
2420
2421   fprintf (file, "\nName memory tags\n\n");
2422   for (i = 0; i < num_referenced_vars; i++)
2423     {
2424       tree var = referenced_var (i);
2425       var_ann_t ann = var_ann (var);
2426       if (ann->mem_tag_kind == NAME_TAG)
2427         dump_variable (file, var);
2428     }
2429
2430   fprintf (file, "\n");
2431 }
2432
2433
2434 /* Dump alias information on stderr.  */
2435
2436 void
2437 debug_alias_info (void)
2438 {
2439   dump_alias_info (stderr);
2440 }
2441
2442
2443 /* Return the alias information associated with pointer T.  It creates a
2444    new instance if none existed.  */
2445
2446 struct ptr_info_def *
2447 get_ptr_info (tree t)
2448 {
2449   struct ptr_info_def *pi;
2450
2451   gcc_assert (POINTER_TYPE_P (TREE_TYPE (t)));
2452
2453   pi = SSA_NAME_PTR_INFO (t);
2454   if (pi == NULL)
2455     {
2456       pi = ggc_alloc (sizeof (*pi));
2457       memset ((void *)pi, 0, sizeof (*pi));
2458       SSA_NAME_PTR_INFO (t) = pi;
2459     }
2460
2461   return pi;
2462 }
2463
2464
2465 /* Dump points-to information for SSA_NAME PTR into FILE.  */
2466
2467 void
2468 dump_points_to_info_for (FILE *file, tree ptr)
2469 {
2470   struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
2471
2472   print_generic_expr (file, ptr, dump_flags);
2473
2474   if (pi)
2475     {
2476       if (pi->name_mem_tag)
2477         {
2478           fprintf (file, ", name memory tag: ");
2479           print_generic_expr (file, pi->name_mem_tag, dump_flags);
2480         }
2481
2482       if (pi->is_dereferenced)
2483         fprintf (file, ", is dereferenced");
2484
2485       if (pi->value_escapes_p)
2486         fprintf (file, ", its value escapes");
2487
2488       if (pi->pt_anything)
2489         fprintf (file, ", points-to anything");
2490
2491       if (pi->pt_malloc)
2492         fprintf (file, ", points-to malloc");
2493
2494       if (pi->pt_null)
2495         fprintf (file, ", points-to NULL");
2496
2497       if (pi->pt_vars)
2498         {
2499           unsigned ix;
2500           bitmap_iterator bi;
2501
2502           fprintf (file, ", points-to vars: { ");
2503           EXECUTE_IF_SET_IN_BITMAP (pi->pt_vars, 0, ix, bi)
2504             {
2505               print_generic_expr (file, referenced_var (ix), dump_flags);
2506               fprintf (file, " ");
2507             }
2508           fprintf (file, "}");
2509         }
2510     }
2511
2512   fprintf (file, "\n");
2513 }
2514
2515
2516 /* Dump points-to information for VAR into stderr.  */
2517
2518 void
2519 debug_points_to_info_for (tree var)
2520 {
2521   dump_points_to_info_for (stderr, var);
2522 }
2523
2524
2525 /* Dump points-to information into FILE.  NOTE: This function is slow, as
2526    it needs to traverse the whole CFG looking for pointer SSA_NAMEs.  */
2527
2528 void
2529 dump_points_to_info (FILE *file)
2530 {
2531   basic_block bb;
2532   block_stmt_iterator si;
2533   size_t i;
2534   ssa_op_iter iter;
2535   const char *fname =
2536     lang_hooks.decl_printable_name (current_function_decl, 2);
2537
2538   fprintf (file, "\n\nPointed-to sets for pointers in %s\n\n", fname);
2539
2540   /* First dump points-to information for the default definitions of
2541      pointer variables.  This is necessary because default definitions are
2542      not part of the code.  */
2543   for (i = 0; i < num_referenced_vars; i++)
2544     {
2545       tree var = referenced_var (i);
2546       if (POINTER_TYPE_P (TREE_TYPE (var)))
2547         {
2548           var_ann_t ann = var_ann (var);
2549           if (ann->default_def)
2550             dump_points_to_info_for (file, ann->default_def);
2551         }
2552     }
2553
2554   /* Dump points-to information for every pointer defined in the program.  */
2555   FOR_EACH_BB (bb)
2556     {
2557       tree phi;
2558
2559       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
2560         {
2561           tree ptr = PHI_RESULT (phi);
2562           if (POINTER_TYPE_P (TREE_TYPE (ptr)))
2563             dump_points_to_info_for (file, ptr);
2564         }
2565
2566         for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
2567           {
2568             tree stmt = bsi_stmt (si);
2569             tree def;
2570             FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
2571               if (POINTER_TYPE_P (TREE_TYPE (def)))
2572                 dump_points_to_info_for (file, def);
2573           }
2574     }
2575
2576   fprintf (file, "\n");
2577 }
2578
2579
2580 /* Dump points-to info pointed by PTO into STDERR.  */
2581
2582 void
2583 debug_points_to_info (void)
2584 {
2585   dump_points_to_info (stderr);
2586 }
2587
2588 /* Dump to FILE the list of variables that may be aliasing VAR.  */
2589
2590 void
2591 dump_may_aliases_for (FILE *file, tree var)
2592 {
2593   varray_type aliases;
2594   
2595   if (TREE_CODE (var) == SSA_NAME)
2596     var = SSA_NAME_VAR (var);
2597
2598   aliases = var_ann (var)->may_aliases;
2599   if (aliases)
2600     {
2601       size_t i;
2602       fprintf (file, "{ ");
2603       for (i = 0; i < VARRAY_ACTIVE_SIZE (aliases); i++)
2604         {
2605           print_generic_expr (file, VARRAY_TREE (aliases, i), dump_flags);
2606           fprintf (file, " ");
2607         }
2608       fprintf (file, "}");
2609     }
2610 }
2611
2612
2613 /* Dump to stderr the list of variables that may be aliasing VAR.  */
2614
2615 void
2616 debug_may_aliases_for (tree var)
2617 {
2618   dump_may_aliases_for (stderr, var);
2619 }
2620
2621 /* Return true if VAR may be aliased.  */
2622
2623 bool
2624 may_be_aliased (tree var)
2625 {
2626   /* Obviously.  */
2627   if (TREE_ADDRESSABLE (var))
2628     return true;
2629
2630   /* Globally visible variables can have their addresses taken by other
2631      translation units.  */
2632   if (DECL_EXTERNAL (var) || TREE_PUBLIC (var))
2633     return true;
2634
2635   /* Automatic variables can't have their addresses escape any other way.
2636      This must be after the check for global variables, as extern declarations
2637      do not have TREE_STATIC set.  */
2638   if (!TREE_STATIC (var))
2639     return false;
2640
2641   /* If we're in unit-at-a-time mode, then we must have seen all occurrences
2642      of address-of operators, and so we can trust TREE_ADDRESSABLE.  Otherwise
2643      we can only be sure the variable isn't addressable if it's local to the
2644      current function.  */
2645   if (flag_unit_at_a_time)
2646     return false;
2647   if (decl_function_context (var) == current_function_decl)
2648     return false;
2649
2650   return true;
2651 }
2652
2653 /* This structure is simply used during pushing fields onto the fieldstack
2654    to track the offset of the field, since bitpos_of_field gives it relative
2655    to its immediate containing type, and we want it relative to the ultimate
2656    containing object.  */
2657
2658 typedef struct fieldoff
2659 {
2660   tree field;
2661   HOST_WIDE_INT offset;  
2662 } *fieldoff_t;
2663
2664 DEF_VEC_MALLOC_P(fieldoff_t);
2665
2666 /* Return the position, in bits, of FIELD_DECL from the beginning of its
2667    structure. 
2668    Return -1 if the position is conditional or otherwise non-constant
2669    integer.  */
2670
2671 static HOST_WIDE_INT
2672 bitpos_of_field (const tree fdecl)
2673 {
2674
2675   if (TREE_CODE (DECL_FIELD_OFFSET (fdecl)) != INTEGER_CST
2676       || TREE_CODE (DECL_FIELD_BIT_OFFSET (fdecl)) != INTEGER_CST)
2677     return -1;
2678
2679   return (tree_low_cst (DECL_FIELD_OFFSET (fdecl), 1) * 8) 
2680     + tree_low_cst (DECL_FIELD_BIT_OFFSET (fdecl), 1);
2681 }
2682
2683 /* Given a TYPE, and a vector of field offsets FIELDSTACK, push all the fields
2684    of TYPE onto fieldstack, recording their offsets along the way.
2685    OFFSET is used to keep track of the offset in this entire structure, rather
2686    than just the immediately containing structure.  */
2687
2688 static void
2689 push_fields_onto_fieldstack (tree type, VEC(fieldoff_t) **fieldstack, 
2690                              HOST_WIDE_INT offset)
2691 {
2692   fieldoff_t pair;
2693   tree field = TYPE_FIELDS (type);
2694   if (!field)
2695     return;
2696   if (var_can_have_subvars (field)
2697       && TREE_CODE (field) == FIELD_DECL)
2698     {
2699       size_t before = VEC_length (fieldoff_t, *fieldstack);
2700       /* Empty structures may have actual size, like in C++. So see if we
2701          actually end up pushing a field, and if not, if the size is non-zero,
2702          push the field onto the stack */
2703       push_fields_onto_fieldstack (TREE_TYPE (field), fieldstack, offset);
2704       if (before == VEC_length (fieldoff_t, *fieldstack)
2705           && DECL_SIZE (field)
2706           && !integer_zerop (DECL_SIZE (field)))
2707         {
2708           pair = xmalloc (sizeof (struct fieldoff));
2709           pair->field = field;
2710           pair->offset = offset;
2711           VEC_safe_push (fieldoff_t, *fieldstack, pair);
2712         }
2713     }
2714   else if (TREE_CODE (field) == FIELD_DECL)
2715     {
2716       pair = xmalloc (sizeof (struct fieldoff));
2717       pair->field = field;
2718       pair->offset = offset + bitpos_of_field (field);
2719       VEC_safe_push (fieldoff_t, *fieldstack, pair);
2720     }
2721   for (field = TREE_CHAIN (field); field; field = TREE_CHAIN (field))
2722     {
2723       if (TREE_CODE (field) != FIELD_DECL)
2724         continue;
2725       if (var_can_have_subvars (field))
2726         {
2727           size_t before = VEC_length (fieldoff_t, *fieldstack);
2728           push_fields_onto_fieldstack (TREE_TYPE (field), fieldstack, 
2729                                        offset + bitpos_of_field (field));
2730       /* Empty structures may have actual size, like in C++. So see if we
2731          actually end up pushing a field, and if not, if the size is non-zero,
2732          push the field onto the stack */
2733           if (before == VEC_length (fieldoff_t, *fieldstack)
2734               && DECL_SIZE (field)
2735               && !integer_zerop (DECL_SIZE (field)))
2736             {
2737               pair = xmalloc (sizeof (struct fieldoff));
2738               pair->field = field;
2739               pair->offset = offset + bitpos_of_field (field);
2740               VEC_safe_push (fieldoff_t, *fieldstack, pair);
2741             }
2742         }
2743       else
2744         {
2745           pair = xmalloc (sizeof (struct fieldoff));
2746           pair->field = field;
2747           pair->offset = offset + bitpos_of_field (field);
2748           VEC_safe_push (fieldoff_t, *fieldstack, pair);
2749         }
2750     }
2751 }
2752
2753
2754 /* This represents the used range of a variable.  */
2755
2756 typedef struct used_part
2757 {
2758   HOST_WIDE_INT minused;
2759   HOST_WIDE_INT maxused;
2760 } *used_part_t;
2761
2762 /* An array of used_part structures, indexed by variable uid.  */
2763
2764 static used_part_t *used_portions;
2765
2766 /* Given a variable uid, UID, get or create the entry in the used portions
2767    table for the variable.  */
2768
2769 static used_part_t
2770 get_or_create_used_part_for (size_t uid)
2771 {
2772   used_part_t up;
2773   if (used_portions[uid] == NULL)
2774     {
2775       up = xcalloc (1, sizeof (struct used_part));
2776       up->minused = INT_MAX;
2777       up->maxused = 0;
2778     }
2779   else
2780     up = used_portions[uid];
2781   return up;
2782 }
2783
2784             
2785   
2786 /* Given an aggregate VAR, create the subvariables that represent its
2787    fields.  */
2788
2789 static void
2790 create_overlap_variables_for (tree var)
2791 {
2792   VEC(fieldoff_t) *fieldstack = NULL;
2793   used_part_t up;
2794   size_t uid = var_ann (var)->uid;
2795
2796   if (used_portions[uid] == NULL)
2797     return;
2798
2799   push_fields_onto_fieldstack (TREE_TYPE (var), &fieldstack, 0);
2800   if (VEC_length (fieldoff_t, fieldstack) != 0)
2801     {
2802       subvar_t *subvars;
2803       fieldoff_t fo;
2804       bool notokay = false;
2805       int i;
2806
2807       /* Not all fields have DECL_SIZE set, and those that don't, we don't
2808          know their size, and thus, can't handle.
2809          The same is true of fields with DECL_SIZE that is not an integer
2810          constant (such as variable sized fields).
2811          Fields with offsets which are not constant will have an offset < 0 
2812          We *could* handle fields that are constant sized arrays, but
2813          currently don't.  Doing so would require some extra changes to
2814          tree-ssa-operands.c.  */
2815
2816       for (i = 0; VEC_iterate (fieldoff_t, fieldstack, i, fo); i++)
2817         {
2818           if (!DECL_SIZE (fo->field) 
2819               || TREE_CODE (DECL_SIZE (fo->field)) != INTEGER_CST
2820               || TREE_CODE (TREE_TYPE (fo->field)) == ARRAY_TYPE
2821               || fo->offset < 0)
2822             {
2823               notokay = true;
2824               break;
2825             }
2826         }
2827       /* Cleanup after ourselves if we can't create overlap variables.  */
2828       if (notokay)
2829         {
2830           while (VEC_length (fieldoff_t, fieldstack) != 0)
2831             {
2832               fo = VEC_pop (fieldoff_t, fieldstack);
2833               free (fo);
2834             }
2835           VEC_free (fieldoff_t, fieldstack);
2836           return;
2837         }
2838       /* Otherwise, create the variables.  */
2839       subvars = lookup_subvars_for_var (var);
2840       up = used_portions[uid];
2841       
2842       while (VEC_length (fieldoff_t, fieldstack) != 0)
2843         {
2844           subvar_t sv = ggc_alloc (sizeof (struct subvar));
2845           HOST_WIDE_INT fosize;
2846           var_ann_t ann;
2847
2848           fo = VEC_pop (fieldoff_t, fieldstack);          
2849           fosize = TREE_INT_CST_LOW (DECL_SIZE (fo->field));
2850
2851           if ((fo->offset <= up->minused
2852                && fo->offset + fosize <= up->minused)
2853               || fo->offset >= up->maxused)
2854             {
2855               free (fo);
2856               continue;
2857             }
2858
2859           sv->offset = fo->offset;
2860           sv->size = fosize;
2861           sv->next = *subvars;
2862           sv->var = create_tmp_var_raw (TREE_TYPE (fo->field), "SFT");
2863           if (dump_file)
2864             {
2865               fprintf (dump_file, "structure field tag %s created for var %s",
2866                        get_name (sv->var), get_name (var));
2867               fprintf (dump_file, " offset " HOST_WIDE_INT_PRINT_DEC,
2868                        sv->offset);
2869               fprintf (dump_file, " size " HOST_WIDE_INT_PRINT_DEC,
2870                        sv->size);
2871               fprintf (dump_file, "\n");
2872               
2873             }
2874           
2875           /* We need to copy the various flags from var to sv->var, so that
2876              they are is_global_var iff the original variable was.  */
2877
2878           DECL_EXTERNAL (sv->var) = DECL_EXTERNAL (var);
2879           TREE_PUBLIC  (sv->var) = TREE_PUBLIC (var);
2880           TREE_STATIC (sv->var) = TREE_STATIC (var);
2881           TREE_READONLY (sv->var) = TREE_READONLY (var);
2882
2883           /* Like other memory tags, these need to be marked addressable to
2884              keep is_gimple_reg from thinking they are real.  */
2885           TREE_ADDRESSABLE (sv->var) = 1;
2886
2887           DECL_CONTEXT (sv->var) = DECL_CONTEXT (var);
2888
2889           ann = get_var_ann (sv->var);
2890           ann->mem_tag_kind = STRUCT_FIELD; 
2891           ann->type_mem_tag = NULL;     
2892           add_referenced_tmp_var (sv->var);
2893             
2894           *subvars = sv;
2895           free (fo);
2896         }
2897     }
2898   
2899   VEC_free (fieldoff_t, fieldstack);
2900 }
2901
2902
2903 /* Find the conservative answer to the question of what portions of what 
2904    structures are used by this statement.  We assume that if we have a
2905    component ref with a known size + offset, that we only need that part
2906    of the structure.  For unknown cases, or cases where we do something
2907    to the whole structure, we assume we need to create fields for the 
2908    entire structure.  */
2909
2910 static tree
2911 find_used_portions (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
2912 {
2913   switch (TREE_CODE (*tp))
2914     {
2915     case COMPONENT_REF:
2916       {
2917         HOST_WIDE_INT bitsize;
2918         HOST_WIDE_INT bitpos;
2919         tree offset;
2920         enum machine_mode mode;
2921         int unsignedp;
2922         int volatilep;  
2923         tree ref;
2924         ref = get_inner_reference (*tp, &bitsize, &bitpos, &offset, &mode,
2925                                    &unsignedp, &volatilep, false);
2926         if (DECL_P (ref) && offset == NULL && bitsize != -1)
2927           {         
2928             size_t uid = var_ann (ref)->uid;
2929             used_part_t up;
2930
2931             up = get_or_create_used_part_for (uid);         
2932
2933             if (bitpos <= up->minused)
2934               up->minused = bitpos;
2935             if ((bitpos + bitsize >= up->maxused))
2936               up->maxused = bitpos + bitsize;       
2937
2938             used_portions[uid] = up;
2939
2940             *walk_subtrees = 0;
2941             return NULL_TREE;
2942           }
2943         else if (DECL_P (ref))
2944           {
2945             if (DECL_SIZE (ref)
2946                 && var_can_have_subvars (ref)
2947                 && TREE_CODE (DECL_SIZE (ref)) == INTEGER_CST)
2948               {
2949                 used_part_t up;
2950                 size_t uid = var_ann (ref)->uid;
2951
2952                 up = get_or_create_used_part_for (uid);
2953
2954                 up->minused = 0;
2955                 up->maxused = TREE_INT_CST_LOW (DECL_SIZE (ref));
2956
2957                 used_portions[uid] = up;
2958
2959                 *walk_subtrees = 0;
2960                 return NULL_TREE;
2961               }
2962           }
2963       }
2964       break;
2965     case VAR_DECL:
2966     case PARM_DECL:
2967       {
2968         tree var = *tp;
2969         if (DECL_SIZE (var)
2970             && var_can_have_subvars (var)
2971             && TREE_CODE (DECL_SIZE (var)) == INTEGER_CST)
2972           {
2973             used_part_t up;
2974             size_t uid = var_ann (var)->uid;        
2975             
2976             up = get_or_create_used_part_for (uid);
2977  
2978             up->minused = 0;
2979             up->maxused = TREE_INT_CST_LOW (DECL_SIZE (var));
2980
2981             used_portions[uid] = up;
2982             *walk_subtrees = 0;
2983             return NULL_TREE;
2984           }
2985       }
2986       break;
2987       
2988     default:
2989       break;
2990       
2991     }
2992   return NULL_TREE;
2993 }
2994
2995 /* We are about to create some new referenced variables, and we need the
2996    before size.  */
2997
2998 static size_t old_referenced_vars;
2999
3000
3001 /* Create structure field variables for structures used in this function.  */
3002
3003 static void
3004 create_structure_vars (void)
3005 {
3006   basic_block bb;
3007   size_t i;
3008
3009   old_referenced_vars = num_referenced_vars;
3010   used_portions = xcalloc (num_referenced_vars, sizeof (used_part_t));
3011   
3012   FOR_EACH_BB (bb)
3013     {
3014       block_stmt_iterator bsi;
3015       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
3016         {
3017           walk_tree_without_duplicates (bsi_stmt_ptr (bsi), 
3018                                         find_used_portions,
3019                                         NULL);
3020         }
3021     }
3022   for (i = 0; i < old_referenced_vars; i++)
3023     {
3024       tree var = referenced_var (i);
3025       /* The C++ FE creates vars without DECL_SIZE set, for some reason.  */
3026       if (var     
3027           && DECL_SIZE (var)
3028           && var_can_have_subvars (var)
3029           && var_ann (var)->mem_tag_kind == NOT_A_TAG
3030           && TREE_CODE (DECL_SIZE (var)) == INTEGER_CST)
3031         create_overlap_variables_for (var);
3032     }
3033   for (i = 0; i < old_referenced_vars; i++)
3034     free (used_portions[i]);
3035
3036   free (used_portions);
3037 }
3038
3039 static bool
3040 gate_structure_vars (void)
3041 {
3042   return flag_tree_salias != 0;
3043 }
3044
3045 struct tree_opt_pass pass_create_structure_vars = 
3046 {
3047   "salias",              /* name */
3048   gate_structure_vars,   /* gate */
3049   create_structure_vars, /* execute */
3050   NULL,                  /* sub */
3051   NULL,                  /* next */
3052   0,                     /* static_pass_number */
3053   0,                     /* tv_id */
3054   PROP_cfg,              /* properties_required */
3055   0,                     /* properties_provided */
3056   0,                     /* properties_destroyed */
3057   0,                     /* todo_flags_start */
3058   TODO_dump_func,        /* todo_flags_finish */
3059   0                      /* letter */
3060 };
3061