OSDN Git Service

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