OSDN Git Service

Oops - forgot to include ChangeLog entry for m32r patch
[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 (offset == sv->offset && size == sv->size)
1996             bitmap_set_bit (pi->pt_vars, var_ann (sv->var)->uid);
1997           else if (offset >= sv->offset && offset < (sv->offset + sv->size))
1998             bitmap_set_bit (pi->pt_vars, var_ann (sv->var)->uid);
1999           else if (offset < sv->offset 
2000                    && (offset + size > sv->offset))
2001             bitmap_set_bit (pi->pt_vars, var_ann (sv->var)->uid);
2002         }
2003     }
2004   else if (pt_var && SSA_VAR_P (pt_var))
2005     {
2006     
2007       uid = var_ann (pt_var)->uid;
2008       bitmap_set_bit (ai->addresses_needed, uid);
2009
2010       if (pi->pt_vars == NULL)
2011         pi->pt_vars = BITMAP_GGC_ALLOC ();
2012
2013       /* If this is an aggregate, we may have subvariables for it that need
2014          to be pointed to.  */
2015       if (var_can_have_subvars (pt_var)
2016           && (svars = get_subvars_for_var (pt_var)))
2017         {
2018           subvar_t sv;
2019           for (sv = svars; sv; sv = sv->next)
2020             {
2021               uid = var_ann (sv->var)->uid;
2022               bitmap_set_bit (ai->addresses_needed, uid);             
2023               bitmap_set_bit (pi->pt_vars, uid);
2024             }
2025         }
2026       else      
2027         bitmap_set_bit (pi->pt_vars, uid);        
2028
2029       /* If the variable is a global, mark the pointer as pointing to
2030          global memory (which will make its tag a global variable).  */
2031       if (is_global_var (pt_var))
2032         pi->pt_global_mem = 1;
2033     }
2034 }
2035
2036
2037 /* Callback for walk_use_def_chains to gather points-to information from the
2038    SSA web.
2039    
2040    VAR is an SSA variable or a GIMPLE expression.
2041    
2042    STMT is the statement that generates the SSA variable or, if STMT is a
2043       PHI_NODE, VAR is one of the PHI arguments.
2044
2045    DATA is a pointer to a structure of type ALIAS_INFO.  */
2046
2047 static bool
2048 collect_points_to_info_r (tree var, tree stmt, void *data)
2049 {
2050   struct alias_info *ai = (struct alias_info *) data;
2051
2052   if (dump_file && (dump_flags & TDF_DETAILS))
2053     {
2054       fprintf (dump_file, "Visiting use-def links for ");
2055       print_generic_expr (dump_file, var, dump_flags);
2056       fprintf (dump_file, "\n");
2057     }
2058
2059   switch (TREE_CODE (stmt))
2060     {
2061     case RETURN_EXPR:
2062       if (TREE_CODE (TREE_OPERAND (stmt, 0)) != MODIFY_EXPR)
2063         abort ();
2064       stmt = TREE_OPERAND (stmt, 0);
2065       /* FALLTHRU  */
2066
2067     case MODIFY_EXPR:
2068       {
2069         tree rhs = TREE_OPERAND (stmt, 1);
2070         STRIP_NOPS (rhs);
2071         add_pointed_to_expr (ai, var, rhs);
2072         break;
2073       }
2074
2075     case ASM_EXPR:
2076       /* Pointers defined by __asm__ statements can point anywhere.  */
2077       set_pt_anything (var);
2078       break;
2079
2080     case NOP_EXPR:
2081       if (IS_EMPTY_STMT (stmt))
2082         {
2083           tree decl = SSA_NAME_VAR (var);
2084           
2085           if (TREE_CODE (decl) == PARM_DECL)
2086             add_pointed_to_expr (ai, var, decl);
2087           else if (DECL_INITIAL (decl))
2088             add_pointed_to_expr (ai, var, DECL_INITIAL (decl));
2089           else
2090             add_pointed_to_expr (ai, var, decl);
2091         }
2092       break;
2093
2094     case PHI_NODE:
2095       {
2096         /* It STMT is a PHI node, then VAR is one of its arguments.  The
2097            variable that we are analyzing is the LHS of the PHI node.  */
2098         tree lhs = PHI_RESULT (stmt);
2099
2100         switch (TREE_CODE (var))
2101           {
2102           case ADDR_EXPR:
2103             add_pointed_to_var (ai, lhs, var);
2104             break;
2105             
2106           case SSA_NAME:
2107             /* Avoid unnecessary merges.  */
2108             if (lhs != var)
2109               merge_pointed_to_info (ai, lhs, var);
2110             break;
2111             
2112           default:
2113             gcc_assert (is_gimple_min_invariant (var));
2114             add_pointed_to_expr (ai, lhs, var);
2115             break;
2116           }
2117         break;
2118       }
2119
2120     default:
2121       gcc_unreachable ();
2122     }
2123   
2124   return false;
2125 }
2126
2127
2128 /* Return true if STMT is an "escape" site from the current function.  Escape
2129    sites those statements which might expose the address of a variable
2130    outside the current function.  STMT is an escape site iff:
2131
2132         1- STMT is a function call, or
2133         2- STMT is an __asm__ expression, or
2134         3- STMT is an assignment to a non-local variable, or
2135         4- STMT is a return statement.
2136
2137    AI points to the alias information collected so far.  */
2138
2139 static bool
2140 is_escape_site (tree stmt, struct alias_info *ai)
2141 {
2142   tree call = get_call_expr_in (stmt);
2143   if (call != NULL_TREE)
2144     {
2145       ai->num_calls_found++;
2146
2147       if (!TREE_SIDE_EFFECTS (call))
2148         ai->num_pure_const_calls_found++;
2149
2150       return true;
2151     }
2152   else if (TREE_CODE (stmt) == ASM_EXPR)
2153     return true;
2154   else if (TREE_CODE (stmt) == MODIFY_EXPR)
2155     {
2156       tree lhs = TREE_OPERAND (stmt, 0);
2157
2158       /* Get to the base of _REF nodes.  */
2159       if (TREE_CODE (lhs) != SSA_NAME)
2160         lhs = get_base_address (lhs);
2161
2162       /* If we couldn't recognize the LHS of the assignment, assume that it
2163          is a non-local store.  */
2164       if (lhs == NULL_TREE)
2165         return true;
2166
2167       /* If the RHS is a conversion between a pointer and an integer, the
2168          pointer escapes since we can't track the integer.  */
2169       if ((TREE_CODE (TREE_OPERAND (stmt, 1)) == NOP_EXPR
2170            || TREE_CODE (TREE_OPERAND (stmt, 1)) == CONVERT_EXPR
2171            || TREE_CODE (TREE_OPERAND (stmt, 1)) == VIEW_CONVERT_EXPR)
2172           && POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND
2173                                         (TREE_OPERAND (stmt, 1), 0)))
2174           && !POINTER_TYPE_P (TREE_TYPE (TREE_OPERAND (stmt, 1))))
2175         return true;
2176
2177       /* If the LHS is an SSA name, it can't possibly represent a non-local
2178          memory store.  */
2179       if (TREE_CODE (lhs) == SSA_NAME)
2180         return false;
2181
2182       /* FIXME: LHS is not an SSA_NAME.  Even if it's an assignment to a
2183          local variables we cannot be sure if it will escape, because we
2184          don't have information about objects not in SSA form.  Need to
2185          implement something along the lines of
2186
2187          J.-D. Choi, M. Gupta, M. J. Serrano, V. C. Sreedhar, and S. P.
2188          Midkiff, ``Escape analysis for java,'' in Proceedings of the
2189          Conference on Object-Oriented Programming Systems, Languages, and
2190          Applications (OOPSLA), pp. 1-19, 1999.  */
2191       return true;
2192     }
2193   else if (TREE_CODE (stmt) == RETURN_EXPR)
2194     return true;
2195
2196   return false;
2197 }
2198
2199
2200 /* Create a new memory tag of type TYPE.  If IS_TYPE_TAG is true, the tag
2201    is considered to represent all the pointers whose pointed-to types are
2202    in the same alias set class.  Otherwise, the tag represents a single
2203    SSA_NAME pointer variable.  */
2204
2205 static tree
2206 create_memory_tag (tree type, bool is_type_tag)
2207 {
2208   var_ann_t ann;
2209   tree tag = create_tmp_var_raw (type, (is_type_tag) ? "TMT" : "NMT");
2210
2211   /* By default, memory tags are local variables.  Alias analysis will
2212      determine whether they should be considered globals.  */
2213   DECL_CONTEXT (tag) = current_function_decl;
2214
2215   /* Memory tags are by definition addressable.  This also prevents
2216      is_gimple_ref frome confusing memory tags with optimizable
2217      variables.  */
2218   TREE_ADDRESSABLE (tag) = 1;
2219
2220   ann = get_var_ann (tag);
2221   ann->mem_tag_kind = (is_type_tag) ? TYPE_TAG : NAME_TAG;
2222   ann->type_mem_tag = NULL_TREE;
2223
2224   /* Add the tag to the symbol table.  */
2225   add_referenced_tmp_var (tag);
2226
2227   return tag;
2228 }
2229
2230
2231 /* Create a name memory tag to represent a specific SSA_NAME pointer P_i.
2232    This is used if P_i has been found to point to a specific set of
2233    variables or to a non-aliased memory location like the address returned
2234    by malloc functions.  */
2235
2236 static tree
2237 get_nmt_for (tree ptr)
2238 {
2239   struct ptr_info_def *pi = get_ptr_info (ptr);
2240   tree tag = pi->name_mem_tag;
2241
2242   if (tag == NULL_TREE)
2243     tag = create_memory_tag (TREE_TYPE (TREE_TYPE (ptr)), false);
2244
2245   /* If PTR is a PARM_DECL, it points to a global variable or malloc,
2246      then its name tag should be considered a global variable.  */
2247   if (TREE_CODE (SSA_NAME_VAR (ptr)) == PARM_DECL
2248       || pi->pt_malloc
2249       || pi->pt_global_mem)
2250     mark_call_clobbered (tag);
2251
2252   return tag;
2253 }
2254
2255
2256 /* Return the type memory tag associated to pointer PTR.  A memory tag is an
2257    artificial variable that represents the memory location pointed-to by
2258    PTR.  It is used to model the effects of pointer de-references on
2259    addressable variables.
2260    
2261    AI points to the data gathered during alias analysis.  This function
2262    populates the array AI->POINTERS.  */
2263
2264 static tree
2265 get_tmt_for (tree ptr, struct alias_info *ai)
2266 {
2267   size_t i;
2268   tree tag;
2269   tree tag_type = TREE_TYPE (TREE_TYPE (ptr));
2270   HOST_WIDE_INT tag_set = get_alias_set (tag_type);
2271
2272   /* To avoid creating unnecessary memory tags, only create one memory tag
2273      per alias set class.  Note that it may be tempting to group
2274      memory tags based on conflicting alias sets instead of
2275      equivalence.  That would be wrong because alias sets are not
2276      necessarily transitive (as demonstrated by the libstdc++ test
2277      23_containers/vector/cons/4.cc).  Given three alias sets A, B, C
2278      such that conflicts (A, B) == true and conflicts (A, C) == true,
2279      it does not necessarily follow that conflicts (B, C) == true.  */
2280   for (i = 0, tag = NULL_TREE; i < ai->num_pointers; i++)
2281     {
2282       struct alias_map_d *curr = ai->pointers[i];
2283       if (tag_set == curr->set)
2284         {
2285           tag = var_ann (curr->var)->type_mem_tag;
2286           break;
2287         }
2288     }
2289
2290   /* If VAR cannot alias with any of the existing memory tags, create a new
2291      tag for PTR and add it to the POINTERS array.  */
2292   if (tag == NULL_TREE)
2293     {
2294       struct alias_map_d *alias_map;
2295
2296       /* If PTR did not have a type tag already, create a new TMT.*
2297          artificial variable representing the memory location
2298          pointed-to by PTR.  */
2299       if (var_ann (ptr)->type_mem_tag == NULL_TREE)
2300         tag = create_memory_tag (tag_type, true);
2301       else
2302         tag = var_ann (ptr)->type_mem_tag;
2303
2304       /* Add PTR to the POINTERS array.  Note that we are not interested in
2305          PTR's alias set.  Instead, we cache the alias set for the memory that
2306          PTR points to.  */
2307       alias_map = xcalloc (1, sizeof (*alias_map));
2308       alias_map->var = ptr;
2309       alias_map->set = tag_set;
2310       ai->pointers[ai->num_pointers++] = alias_map;
2311     }
2312
2313   /* If the pointed-to type is volatile, so is the tag.  */
2314   TREE_THIS_VOLATILE (tag) |= TREE_THIS_VOLATILE (tag_type);
2315
2316   /* Make sure that the type tag has the same alias set as the
2317      pointed-to type.  */
2318   gcc_assert (tag_set == get_alias_set (tag));
2319
2320   return tag;
2321 }
2322
2323
2324 /* Create GLOBAL_VAR, an artificial global variable to act as a
2325    representative of all the variables that may be clobbered by function
2326    calls.  */
2327
2328 static void
2329 create_global_var (void)
2330 {
2331   global_var = build_decl (VAR_DECL, get_identifier (".GLOBAL_VAR"),
2332                            void_type_node);
2333   DECL_ARTIFICIAL (global_var) = 1;
2334   TREE_READONLY (global_var) = 0;
2335   DECL_EXTERNAL (global_var) = 1;
2336   TREE_STATIC (global_var) = 1;
2337   TREE_USED (global_var) = 1;
2338   DECL_CONTEXT (global_var) = NULL_TREE;
2339   TREE_THIS_VOLATILE (global_var) = 0;
2340   TREE_ADDRESSABLE (global_var) = 0;
2341
2342   add_referenced_tmp_var (global_var);
2343   bitmap_set_bit (vars_to_rename, var_ann (global_var)->uid);
2344 }
2345
2346
2347 /* Dump alias statistics on FILE.  */
2348
2349 static void 
2350 dump_alias_stats (FILE *file)
2351 {
2352   const char *funcname
2353     = lang_hooks.decl_printable_name (current_function_decl, 2);
2354   fprintf (file, "\nAlias statistics for %s\n\n", funcname);
2355   fprintf (file, "Total alias queries:\t%u\n", alias_stats.alias_queries);
2356   fprintf (file, "Total alias mayalias results:\t%u\n", 
2357            alias_stats.alias_mayalias);
2358   fprintf (file, "Total alias noalias results:\t%u\n",
2359            alias_stats.alias_noalias);
2360   fprintf (file, "Total simple queries:\t%u\n",
2361            alias_stats.simple_queries);
2362   fprintf (file, "Total simple resolved:\t%u\n",
2363            alias_stats.simple_resolved);
2364   fprintf (file, "Total TBAA queries:\t%u\n",
2365            alias_stats.tbaa_queries);
2366   fprintf (file, "Total TBAA resolved:\t%u\n",
2367            alias_stats.tbaa_resolved);
2368 }
2369   
2370
2371 /* Dump alias information on FILE.  */
2372
2373 void
2374 dump_alias_info (FILE *file)
2375 {
2376   size_t i;
2377   const char *funcname
2378     = lang_hooks.decl_printable_name (current_function_decl, 2);
2379
2380   fprintf (file, "\nFlow-insensitive alias information for %s\n\n", funcname);
2381
2382   fprintf (file, "Aliased symbols\n\n");
2383   for (i = 0; i < num_referenced_vars; i++)
2384     {
2385       tree var = referenced_var (i);
2386       if (may_be_aliased (var))
2387         dump_variable (file, var);
2388     }
2389
2390   fprintf (file, "\nDereferenced pointers\n\n");
2391   for (i = 0; i < num_referenced_vars; i++)
2392     {
2393       tree var = referenced_var (i);
2394       var_ann_t ann = var_ann (var);
2395       if (ann->type_mem_tag)
2396         dump_variable (file, var);
2397     }
2398
2399   fprintf (file, "\nType memory tags\n\n");
2400   for (i = 0; i < num_referenced_vars; i++)
2401     {
2402       tree var = referenced_var (i);
2403       var_ann_t ann = var_ann (var);
2404       if (ann->mem_tag_kind == TYPE_TAG)
2405         dump_variable (file, var);
2406     }
2407
2408   fprintf (file, "\n\nFlow-sensitive alias information for %s\n\n", funcname);
2409
2410   fprintf (file, "SSA_NAME pointers\n\n");
2411   for (i = 1; i < num_ssa_names; i++)
2412     {
2413       tree ptr = ssa_name (i);
2414       struct ptr_info_def *pi;
2415       
2416       if (ptr == NULL_TREE)
2417         continue;
2418
2419       pi = SSA_NAME_PTR_INFO (ptr);
2420       if (!SSA_NAME_IN_FREE_LIST (ptr)
2421           && pi
2422           && pi->name_mem_tag)
2423         dump_points_to_info_for (file, ptr);
2424     }
2425
2426   fprintf (file, "\nName memory tags\n\n");
2427   for (i = 0; i < num_referenced_vars; i++)
2428     {
2429       tree var = referenced_var (i);
2430       var_ann_t ann = var_ann (var);
2431       if (ann->mem_tag_kind == NAME_TAG)
2432         dump_variable (file, var);
2433     }
2434
2435   fprintf (file, "\n");
2436 }
2437
2438
2439 /* Dump alias information on stderr.  */
2440
2441 void
2442 debug_alias_info (void)
2443 {
2444   dump_alias_info (stderr);
2445 }
2446
2447
2448 /* Return the alias information associated with pointer T.  It creates a
2449    new instance if none existed.  */
2450
2451 struct ptr_info_def *
2452 get_ptr_info (tree t)
2453 {
2454   struct ptr_info_def *pi;
2455
2456   gcc_assert (POINTER_TYPE_P (TREE_TYPE (t)));
2457
2458   pi = SSA_NAME_PTR_INFO (t);
2459   if (pi == NULL)
2460     {
2461       pi = ggc_alloc (sizeof (*pi));
2462       memset ((void *)pi, 0, sizeof (*pi));
2463       SSA_NAME_PTR_INFO (t) = pi;
2464     }
2465
2466   return pi;
2467 }
2468
2469
2470 /* Dump points-to information for SSA_NAME PTR into FILE.  */
2471
2472 void
2473 dump_points_to_info_for (FILE *file, tree ptr)
2474 {
2475   struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
2476
2477   print_generic_expr (file, ptr, dump_flags);
2478
2479   if (pi)
2480     {
2481       if (pi->name_mem_tag)
2482         {
2483           fprintf (file, ", name memory tag: ");
2484           print_generic_expr (file, pi->name_mem_tag, dump_flags);
2485         }
2486
2487       if (pi->is_dereferenced)
2488         fprintf (file, ", is dereferenced");
2489
2490       if (pi->value_escapes_p)
2491         fprintf (file, ", its value escapes");
2492
2493       if (pi->pt_anything)
2494         fprintf (file, ", points-to anything");
2495
2496       if (pi->pt_malloc)
2497         fprintf (file, ", points-to malloc");
2498
2499       if (pi->pt_null)
2500         fprintf (file, ", points-to NULL");
2501
2502       if (pi->pt_vars)
2503         {
2504           unsigned ix;
2505           bitmap_iterator bi;
2506
2507           fprintf (file, ", points-to vars: { ");
2508           EXECUTE_IF_SET_IN_BITMAP (pi->pt_vars, 0, ix, bi)
2509             {
2510               print_generic_expr (file, referenced_var (ix), dump_flags);
2511               fprintf (file, " ");
2512             }
2513           fprintf (file, "}");
2514         }
2515     }
2516
2517   fprintf (file, "\n");
2518 }
2519
2520
2521 /* Dump points-to information for VAR into stderr.  */
2522
2523 void
2524 debug_points_to_info_for (tree var)
2525 {
2526   dump_points_to_info_for (stderr, var);
2527 }
2528
2529
2530 /* Dump points-to information into FILE.  NOTE: This function is slow, as
2531    it needs to traverse the whole CFG looking for pointer SSA_NAMEs.  */
2532
2533 void
2534 dump_points_to_info (FILE *file)
2535 {
2536   basic_block bb;
2537   block_stmt_iterator si;
2538   size_t i;
2539   ssa_op_iter iter;
2540   const char *fname =
2541     lang_hooks.decl_printable_name (current_function_decl, 2);
2542
2543   fprintf (file, "\n\nPointed-to sets for pointers in %s\n\n", fname);
2544
2545   /* First dump points-to information for the default definitions of
2546      pointer variables.  This is necessary because default definitions are
2547      not part of the code.  */
2548   for (i = 0; i < num_referenced_vars; i++)
2549     {
2550       tree var = referenced_var (i);
2551       if (POINTER_TYPE_P (TREE_TYPE (var)))
2552         {
2553           var_ann_t ann = var_ann (var);
2554           if (ann->default_def)
2555             dump_points_to_info_for (file, ann->default_def);
2556         }
2557     }
2558
2559   /* Dump points-to information for every pointer defined in the program.  */
2560   FOR_EACH_BB (bb)
2561     {
2562       tree phi;
2563
2564       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
2565         {
2566           tree ptr = PHI_RESULT (phi);
2567           if (POINTER_TYPE_P (TREE_TYPE (ptr)))
2568             dump_points_to_info_for (file, ptr);
2569         }
2570
2571         for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
2572           {
2573             tree stmt = bsi_stmt (si);
2574             tree def;
2575             FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
2576               if (POINTER_TYPE_P (TREE_TYPE (def)))
2577                 dump_points_to_info_for (file, def);
2578           }
2579     }
2580
2581   fprintf (file, "\n");
2582 }
2583
2584
2585 /* Dump points-to info pointed by PTO into STDERR.  */
2586
2587 void
2588 debug_points_to_info (void)
2589 {
2590   dump_points_to_info (stderr);
2591 }
2592
2593 /* Dump to FILE the list of variables that may be aliasing VAR.  */
2594
2595 void
2596 dump_may_aliases_for (FILE *file, tree var)
2597 {
2598   varray_type aliases;
2599   
2600   if (TREE_CODE (var) == SSA_NAME)
2601     var = SSA_NAME_VAR (var);
2602
2603   aliases = var_ann (var)->may_aliases;
2604   if (aliases)
2605     {
2606       size_t i;
2607       fprintf (file, "{ ");
2608       for (i = 0; i < VARRAY_ACTIVE_SIZE (aliases); i++)
2609         {
2610           print_generic_expr (file, VARRAY_TREE (aliases, i), dump_flags);
2611           fprintf (file, " ");
2612         }
2613       fprintf (file, "}");
2614     }
2615 }
2616
2617
2618 /* Dump to stderr the list of variables that may be aliasing VAR.  */
2619
2620 void
2621 debug_may_aliases_for (tree var)
2622 {
2623   dump_may_aliases_for (stderr, var);
2624 }
2625
2626 /* Return true if VAR may be aliased.  */
2627
2628 bool
2629 may_be_aliased (tree var)
2630 {
2631   /* Obviously.  */
2632   if (TREE_ADDRESSABLE (var))
2633     return true;
2634
2635   /* Globally visible variables can have their addresses taken by other
2636      translation units.  */
2637   if (DECL_EXTERNAL (var) || TREE_PUBLIC (var))
2638     return true;
2639
2640   /* Automatic variables can't have their addresses escape any other way.
2641      This must be after the check for global variables, as extern declarations
2642      do not have TREE_STATIC set.  */
2643   if (!TREE_STATIC (var))
2644     return false;
2645
2646   /* If we're in unit-at-a-time mode, then we must have seen all occurrences
2647      of address-of operators, and so we can trust TREE_ADDRESSABLE.  Otherwise
2648      we can only be sure the variable isn't addressable if it's local to the
2649      current function.  */
2650   if (flag_unit_at_a_time)
2651     return false;
2652   if (decl_function_context (var) == current_function_decl)
2653     return false;
2654
2655   return true;
2656 }
2657
2658 /* This structure is simply used during pushing fields onto the fieldstack
2659    to track the offset of the field, since bitpos_of_field gives it relative
2660    to its immediate containing type, and we want it relative to the ultimate
2661    containing object.  */
2662
2663 typedef struct fieldoff
2664 {
2665   tree field;
2666   HOST_WIDE_INT offset;  
2667 } *fieldoff_t;
2668
2669 DEF_VEC_MALLOC_P(fieldoff_t);
2670
2671 /* Return the position, in bits, of FIELD_DECL from the beginning of its
2672    structure. 
2673    Return -1 if the position is conditional or otherwise non-constant
2674    integer.  */
2675
2676 static HOST_WIDE_INT
2677 bitpos_of_field (const tree fdecl)
2678 {
2679
2680   if (TREE_CODE (DECL_FIELD_OFFSET (fdecl)) != INTEGER_CST
2681       || TREE_CODE (DECL_FIELD_BIT_OFFSET (fdecl)) != INTEGER_CST)
2682     return -1;
2683
2684   return (tree_low_cst (DECL_FIELD_OFFSET (fdecl), 1) * 8) 
2685     + tree_low_cst (DECL_FIELD_BIT_OFFSET (fdecl), 1);
2686 }
2687
2688 /* Given a TYPE, and a vector of field offsets FIELDSTACK, push all the fields
2689    of TYPE onto fieldstack, recording their offsets along the way.
2690    OFFSET is used to keep track of the offset in this entire structure, rather
2691    than just the immediately containing structure.  */
2692
2693 static void
2694 push_fields_onto_fieldstack (tree type, VEC(fieldoff_t) **fieldstack, 
2695                              HOST_WIDE_INT offset)
2696 {
2697   fieldoff_t pair;
2698   tree field = TYPE_FIELDS (type);
2699   if (!field)
2700     return;
2701   if (var_can_have_subvars (field)
2702       && TREE_CODE (field) == FIELD_DECL)
2703     {
2704       size_t before = VEC_length (fieldoff_t, *fieldstack);
2705       /* Empty structures may have actual size, like in C++. So see if we
2706          actually end up pushing a field, and if not, if the size is non-zero,
2707          push the field onto the stack */
2708       push_fields_onto_fieldstack (TREE_TYPE (field), fieldstack, offset);
2709       if (before == VEC_length (fieldoff_t, *fieldstack)
2710           && DECL_SIZE (field)
2711           && !integer_zerop (DECL_SIZE (field)))
2712         {
2713           pair = xmalloc (sizeof (struct fieldoff));
2714           pair->field = field;
2715           pair->offset = offset;
2716           VEC_safe_push (fieldoff_t, *fieldstack, pair);
2717         }
2718     }
2719   else if (TREE_CODE (field) == FIELD_DECL)
2720     {
2721       pair = xmalloc (sizeof (struct fieldoff));
2722       pair->field = field;
2723       pair->offset = offset + bitpos_of_field (field);
2724       VEC_safe_push (fieldoff_t, *fieldstack, pair);
2725     }
2726   for (field = TREE_CHAIN (field); field; field = TREE_CHAIN (field))
2727     {
2728       if (TREE_CODE (field) != FIELD_DECL)
2729         continue;
2730       if (var_can_have_subvars (field))
2731         {
2732           size_t before = VEC_length (fieldoff_t, *fieldstack);
2733           push_fields_onto_fieldstack (TREE_TYPE (field), fieldstack, 
2734                                        offset + bitpos_of_field (field));
2735       /* Empty structures may have actual size, like in C++. So see if we
2736          actually end up pushing a field, and if not, if the size is non-zero,
2737          push the field onto the stack */
2738           if (before == VEC_length (fieldoff_t, *fieldstack)
2739               && DECL_SIZE (field)
2740               && !integer_zerop (DECL_SIZE (field)))
2741             {
2742               pair = xmalloc (sizeof (struct fieldoff));
2743               pair->field = field;
2744               pair->offset = offset + bitpos_of_field (field);
2745               VEC_safe_push (fieldoff_t, *fieldstack, pair);
2746             }
2747         }
2748       else
2749         {
2750           pair = xmalloc (sizeof (struct fieldoff));
2751           pair->field = field;
2752           pair->offset = offset + bitpos_of_field (field);
2753           VEC_safe_push (fieldoff_t, *fieldstack, pair);
2754         }
2755     }
2756 }
2757
2758
2759 /* This represents the used range of a variable.  */
2760
2761 typedef struct used_part
2762 {
2763   HOST_WIDE_INT minused;
2764   HOST_WIDE_INT maxused;
2765 } *used_part_t;
2766
2767 /* An array of used_part structures, indexed by variable uid.  */
2768
2769 static used_part_t *used_portions;
2770
2771 /* Given a variable uid, UID, get or create the entry in the used portions
2772    table for the variable.  */
2773
2774 static used_part_t
2775 get_or_create_used_part_for (size_t uid)
2776 {
2777   used_part_t up;
2778   if (used_portions[uid] == NULL)
2779     {
2780       up = xcalloc (1, sizeof (struct used_part));
2781       up->minused = INT_MAX;
2782       up->maxused = 0;
2783     }
2784   else
2785     up = used_portions[uid];
2786   return up;
2787 }
2788
2789             
2790   
2791 /* Given an aggregate VAR, create the subvariables that represent its
2792    fields.  */
2793
2794 static void
2795 create_overlap_variables_for (tree var)
2796 {
2797   VEC(fieldoff_t) *fieldstack = NULL;
2798   used_part_t up;
2799   size_t uid = var_ann (var)->uid;
2800
2801   if (used_portions[uid] == NULL)
2802     return;
2803
2804   push_fields_onto_fieldstack (TREE_TYPE (var), &fieldstack, 0);
2805   if (VEC_length (fieldoff_t, fieldstack) != 0)
2806     {
2807       subvar_t *subvars;
2808       fieldoff_t fo;
2809       bool notokay = false;
2810       int i;
2811
2812       /* Not all fields have DECL_SIZE set, and those that don't, we don't
2813          know their size, and thus, can't handle.
2814          The same is true of fields with DECL_SIZE that is not an integer
2815          constant (such as variable sized fields).
2816          Fields with offsets which are not constant will have an offset < 0 
2817          We *could* handle fields that are constant sized arrays, but
2818          currently don't.  Doing so would require some extra changes to
2819          tree-ssa-operands.c.  */
2820
2821       for (i = 0; VEC_iterate (fieldoff_t, fieldstack, i, fo); i++)
2822         {
2823           if (!DECL_SIZE (fo->field) 
2824               || TREE_CODE (DECL_SIZE (fo->field)) != INTEGER_CST
2825               || TREE_CODE (TREE_TYPE (fo->field)) == ARRAY_TYPE
2826               || fo->offset < 0)
2827             {
2828               notokay = true;
2829               break;
2830             }
2831         }
2832       /* Cleanup after ourselves if we can't create overlap variables.  */
2833       if (notokay)
2834         {
2835           while (VEC_length (fieldoff_t, fieldstack) != 0)
2836             {
2837               fo = VEC_pop (fieldoff_t, fieldstack);
2838               free (fo);
2839             }
2840           VEC_free (fieldoff_t, fieldstack);
2841           return;
2842         }
2843       /* Otherwise, create the variables.  */
2844       subvars = lookup_subvars_for_var (var);
2845       up = used_portions[uid];
2846       
2847       while (VEC_length (fieldoff_t, fieldstack) != 0)
2848         {
2849           subvar_t sv = ggc_alloc (sizeof (struct subvar));
2850           HOST_WIDE_INT fosize;
2851           var_ann_t ann;
2852
2853           fo = VEC_pop (fieldoff_t, fieldstack);          
2854           fosize = TREE_INT_CST_LOW (DECL_SIZE (fo->field));
2855
2856           if ((fo->offset <= up->minused
2857                && fo->offset + fosize <= up->minused)
2858               || fo->offset >= up->maxused)
2859             {
2860               free (fo);
2861               continue;
2862             }
2863
2864           sv->offset = fo->offset;
2865           sv->size = fosize;
2866           sv->next = *subvars;
2867           sv->var = create_tmp_var_raw (TREE_TYPE (fo->field), "SFT");
2868           if (dump_file)
2869             {
2870               fprintf (dump_file, "structure field tag %s created for var %s",
2871                        get_name (sv->var), get_name (var));
2872               fprintf (dump_file, " offset " HOST_WIDE_INT_PRINT_DEC,
2873                        sv->offset);
2874               fprintf (dump_file, " size " HOST_WIDE_INT_PRINT_DEC,
2875                        sv->size);
2876               fprintf (dump_file, "\n");
2877               
2878             }
2879           
2880           /* We need to copy the various flags from var to sv->var, so that
2881              they are is_global_var iff the original variable was.  */
2882
2883           DECL_EXTERNAL (sv->var) = DECL_EXTERNAL (var);
2884           TREE_PUBLIC  (sv->var) = TREE_PUBLIC (var);
2885           TREE_STATIC (sv->var) = TREE_STATIC (var);
2886           TREE_READONLY (sv->var) = TREE_READONLY (var);
2887
2888           /* Like other memory tags, these need to be marked addressable to
2889              keep is_gimple_reg from thinking they are real.  */
2890           TREE_ADDRESSABLE (sv->var) = 1;
2891
2892           DECL_CONTEXT (sv->var) = DECL_CONTEXT (var);
2893
2894           ann = get_var_ann (sv->var);
2895           ann->mem_tag_kind = STRUCT_FIELD; 
2896           ann->type_mem_tag = NULL;     
2897           add_referenced_tmp_var (sv->var);
2898             
2899           *subvars = sv;
2900           free (fo);
2901         }
2902     }
2903   
2904   VEC_free (fieldoff_t, fieldstack);
2905 }
2906
2907
2908 /* Find the conservative answer to the question of what portions of what 
2909    structures are used by this statement.  We assume that if we have a
2910    component ref with a known size + offset, that we only need that part
2911    of the structure.  For unknown cases, or cases where we do something
2912    to the whole structure, we assume we need to create fields for the 
2913    entire structure.  */
2914
2915 static tree
2916 find_used_portions (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
2917 {
2918   switch (TREE_CODE (*tp))
2919     {
2920     case COMPONENT_REF:
2921       {
2922         HOST_WIDE_INT bitsize;
2923         HOST_WIDE_INT bitpos;
2924         tree offset;
2925         enum machine_mode mode;
2926         int unsignedp;
2927         int volatilep;  
2928         tree ref;
2929         ref = get_inner_reference (*tp, &bitsize, &bitpos, &offset, &mode,
2930                                    &unsignedp, &volatilep, false);
2931         if (DECL_P (ref) && offset == NULL && bitsize != -1)
2932           {         
2933             size_t uid = var_ann (ref)->uid;
2934             used_part_t up;
2935
2936             up = get_or_create_used_part_for (uid);         
2937
2938             if (bitpos <= up->minused)
2939               up->minused = bitpos;
2940             if ((bitpos + bitsize >= up->maxused))
2941               up->maxused = bitpos + bitsize;       
2942
2943             used_portions[uid] = up;
2944
2945             *walk_subtrees = 0;
2946             return NULL_TREE;
2947           }
2948         else if (DECL_P (ref))
2949           {
2950             if (DECL_SIZE (ref)
2951                 && var_can_have_subvars (ref)
2952                 && TREE_CODE (DECL_SIZE (ref)) == INTEGER_CST)
2953               {
2954                 used_part_t up;
2955                 size_t uid = var_ann (ref)->uid;
2956
2957                 up = get_or_create_used_part_for (uid);
2958
2959                 up->minused = 0;
2960                 up->maxused = TREE_INT_CST_LOW (DECL_SIZE (ref));
2961
2962                 used_portions[uid] = up;
2963
2964                 *walk_subtrees = 0;
2965                 return NULL_TREE;
2966               }
2967           }
2968       }
2969       break;
2970     case VAR_DECL:
2971     case PARM_DECL:
2972       {
2973         tree var = *tp;
2974         if (DECL_SIZE (var)
2975             && var_can_have_subvars (var)
2976             && TREE_CODE (DECL_SIZE (var)) == INTEGER_CST)
2977           {
2978             used_part_t up;
2979             size_t uid = var_ann (var)->uid;        
2980             
2981             up = get_or_create_used_part_for (uid);
2982  
2983             up->minused = 0;
2984             up->maxused = TREE_INT_CST_LOW (DECL_SIZE (var));
2985
2986             used_portions[uid] = up;
2987             *walk_subtrees = 0;
2988             return NULL_TREE;
2989           }
2990       }
2991       break;
2992       
2993     default:
2994       break;
2995       
2996     }
2997   return NULL_TREE;
2998 }
2999
3000 /* We are about to create some new referenced variables, and we need the
3001    before size.  */
3002
3003 static size_t old_referenced_vars;
3004
3005
3006 /* Create structure field variables for structures used in this function.  */
3007
3008 static void
3009 create_structure_vars (void)
3010 {
3011   basic_block bb;
3012   size_t i;
3013
3014   old_referenced_vars = num_referenced_vars;
3015   used_portions = xcalloc (num_referenced_vars, sizeof (used_part_t));
3016   
3017   FOR_EACH_BB (bb)
3018     {
3019       block_stmt_iterator bsi;
3020       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
3021         {
3022           walk_tree_without_duplicates (bsi_stmt_ptr (bsi), 
3023                                         find_used_portions,
3024                                         NULL);
3025         }
3026     }
3027   for (i = 0; i < old_referenced_vars; i++)
3028     {
3029       tree var = referenced_var (i);
3030       /* The C++ FE creates vars without DECL_SIZE set, for some reason.  */
3031       if (var     
3032           && DECL_SIZE (var)
3033           && var_can_have_subvars (var)
3034           && var_ann (var)->mem_tag_kind == NOT_A_TAG
3035           && TREE_CODE (DECL_SIZE (var)) == INTEGER_CST)
3036         create_overlap_variables_for (var);
3037     }
3038   for (i = 0; i < old_referenced_vars; i++)
3039     free (used_portions[i]);
3040
3041   free (used_portions);
3042 }
3043
3044 static bool
3045 gate_structure_vars (void)
3046 {
3047   return flag_tree_salias != 0;
3048 }
3049
3050 struct tree_opt_pass pass_create_structure_vars = 
3051 {
3052   "salias",              /* name */
3053   gate_structure_vars,   /* gate */
3054   create_structure_vars, /* execute */
3055   NULL,                  /* sub */
3056   NULL,                  /* next */
3057   0,                     /* static_pass_number */
3058   0,                     /* tv_id */
3059   PROP_cfg,              /* properties_required */
3060   0,                     /* properties_provided */
3061   0,                     /* properties_destroyed */
3062   0,                     /* todo_flags_start */
3063   TODO_dump_func,        /* todo_flags_finish */
3064   0                      /* letter */
3065 };
3066