OSDN Git Service

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