OSDN Git Service

* tree-ssa-alias.c (compute_memory_partitions): Use
[pf3gnuchains/gcc-fork.git] / gcc / tree-ssa-alias.c
1 /* Alias analysis for trees.
2    Copyright (C) 2004, 2005, 2006, 2007 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 3, 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 COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "tree.h"
26 #include "rtl.h"
27 #include "tm_p.h"
28 #include "hard-reg-set.h"
29 #include "basic-block.h"
30 #include "timevar.h"
31 #include "expr.h"
32 #include "ggc.h"
33 #include "langhooks.h"
34 #include "flags.h"
35 #include "function.h"
36 #include "diagnostic.h"
37 #include "tree-dump.h"
38 #include "tree-gimple.h"
39 #include "tree-flow.h"
40 #include "tree-inline.h"
41 #include "tree-pass.h"
42 #include "tree-ssa-structalias.h"
43 #include "convert.h"
44 #include "params.h"
45 #include "ipa-type-escape.h"
46 #include "vec.h"
47 #include "bitmap.h"
48 #include "vecprim.h"
49 #include "pointer-set.h"
50 #include "alloc-pool.h"
51
52 /* Broad overview of how aliasing works:
53    
54    First we compute points-to sets, which is done in
55    tree-ssa-structalias.c
56       
57    During points-to set constraint finding, a bunch of little bits of
58    information is collected.
59    This is not done because it is necessary for points-to, but because
60    points-to has to walk every statement anyway.  The function performing
61    this collecting is update_alias_info.
62
63    Bits update_alias_info collects include:
64    1. Directly escaping variables and variables whose value escapes
65    (using is_escape_site).  This is the set of variables and values that
66    escape prior to transitive closure of the clobbers.
67    2.  The set of variables dereferenced on the LHS (into
68    dereferenced_ptr_stores) 
69    3. The set of variables dereferenced on the RHS (into
70    dereferenced_ptr_loads) 
71    4. The set of all pointers we saw.
72    5. The number of loads and stores for each variable
73    6. The number of statements touching memory
74    7. The set of address taken variables.
75    
76    
77    #1 is computed by a combination of is_escape_site, and counting the
78    number of uses/deref operators.  This function properly accounts for
79    situations like &ptr->field, which is *not* a dereference.
80    
81    After points-to sets are computed, the sets themselves still
82    contain points-to specific variables, such as a variable that says
83    the pointer points to anything, a variable that says the pointer
84    points to readonly memory, etc.
85
86    These are eliminated in a later phase, as we will see.
87
88    The rest of the phases are located in tree-ssa-alias.c
89
90    The next phase after points-to set computation is called
91    "setup_pointers_and_addressables"
92
93    This pass does 3 main things:
94    
95    1. All variables that can have TREE_ADDRESSABLE removed safely (IE
96    non-globals whose address is not taken), have TREE_ADDRESSABLE
97    removed.
98    2. All variables that may be aliased (which is the set of addressable
99    variables and globals) at all, are marked for renaming, and have
100    symbol memory tags created for them.
101    3. All variables which are stored into have their SMT's added to
102    written vars. 
103
104
105    After this function is run, all variables that will ever have an
106    SMT, have one, though its aliases are not filled in.
107
108    The next phase is to compute flow-insensitive aliasing, which in
109    our case, is a misnomer.  it is really computing aliasing that
110    requires no transitive closure to be correct.  In particular, it
111    uses stack vs non-stack, TBAA, etc, to determine whether two
112    symbols could *ever* alias .  This phase works by going through all
113    the pointers we collected during update_alias_info, and for every
114    addressable variable in the program, seeing if they alias.  If so,
115    the addressable variable is added to the symbol memory tag for the
116    pointer.
117
118    As part of this, we handle symbol memory tags that conflict but
119    have no aliases in common, by forcing them to have a symbol in
120    common (through unioning alias sets or adding one as an alias of
121    the other), or by adding one as an alias of another.  The case of
122    conflicts with no aliases in common occurs mainly due to aliasing
123    we cannot see.  In particular, it generally means we have a load
124    through a pointer whose value came from outside the function.
125    Without an addressable symbol to point to, they would get the wrong
126    answer.
127
128    After flow insensitive aliasing is computed, we compute name tags
129    (called compute_flow_sensitive_info).  We walk each pointer we
130    collected and see if it has a usable points-to set.  If so, we
131    generate a name tag using that pointer, and make an alias bitmap for
132    it.  Name tags are shared between all things with the same alias
133    bitmap.  The alias bitmap will be translated from what points-to
134    computed.  In particular, the "anything" variable in points-to will be
135    transformed into a pruned set of SMT's and their aliases that
136    compute_flow_insensitive_aliasing computed.
137    Note that since 4.3, every pointer that points-to computed a solution for
138    will get a name tag (whereas before 4.3, only those whose set did
139    *not* include the anything variable would).  At the point where name
140    tags are all assigned, symbol memory tags are dead, and could be
141    deleted, *except* on global variables.  Global variables still use
142    symbol memory tags as of right now.
143
144    After name tags are computed, the set of clobbered variables is
145    transitively closed.  In particular, we compute the set of clobbered
146    variables based on the initial set of clobbers, plus the aliases of
147    pointers which either escape, or have their value escape.
148
149    After this, maybe_create_global_var is run, which handles a corner
150    case where we have no call clobbered variables, but have pure and
151    non-pure functions.
152    
153    Staring at this function, I now remember it is a hack for the fact
154    that we do not mark all globals in the program as call clobbered for a
155    function unless they are actually used in that function.  Instead,  we
156    only mark the set that is actually clobbered.  As a result, you can
157    end up with situations where you have no call clobbered vars set.
158    
159    After maybe_create_global_var, we set pointers with the REF_ALL flag
160    to have alias sets that include all clobbered
161    memory tags and variables.
162    
163    After this, memory partitioning is computed (by the function
164    compute_memory_partitions) and alias sets are reworked accordingly.
165
166    Lastly, we delete partitions with no symbols, and clean up after
167    ourselves.  */
168
169 /* Structure to map a variable to its alias set.  */
170 struct alias_map_d
171 {
172   /* Variable and its alias set.  */
173   tree var;
174   alias_set_type set;
175 };
176
177
178 /* Counters used to display statistics on alias analysis.  */
179 struct alias_stats_d
180 {
181   unsigned int alias_queries;
182   unsigned int alias_mayalias;
183   unsigned int alias_noalias;
184   unsigned int simple_queries;
185   unsigned int simple_resolved;
186   unsigned int tbaa_queries;
187   unsigned int tbaa_resolved;
188   unsigned int structnoaddress_queries;
189   unsigned int structnoaddress_resolved;
190 };
191
192
193 /* Local variables.  */
194 static struct alias_stats_d alias_stats;
195 static bitmap_obstack alias_bitmap_obstack;
196
197 /* Local functions.  */
198 static void compute_flow_insensitive_aliasing (struct alias_info *);
199 static void finalize_ref_all_pointers (struct alias_info *);
200 static void dump_alias_stats (FILE *);
201 static bool may_alias_p (tree, alias_set_type, tree, alias_set_type, bool);
202 static tree create_memory_tag (tree type, bool is_type_tag);
203 static tree get_smt_for (tree, struct alias_info *);
204 static tree get_nmt_for (tree);
205 static void add_may_alias (tree, tree);
206 static struct alias_info *init_alias_info (void);
207 static void delete_alias_info (struct alias_info *);
208 static void compute_flow_sensitive_aliasing (struct alias_info *);
209 static void setup_pointers_and_addressables (struct alias_info *);
210 static void create_global_var (void);
211 static void maybe_create_global_var (void);
212 static void set_pt_anything (tree);
213
214 void debug_mp_info (VEC(mem_sym_stats_t,heap) *);
215
216 static alloc_pool mem_sym_stats_pool;
217
218 /* Return memory reference stats for symbol VAR.  Create a new slot in
219    cfun->gimple_df->mem_sym_stats if needed.  */
220
221 static struct mem_sym_stats_d *
222 get_mem_sym_stats_for (tree var)
223 {
224   void **slot;
225   struct mem_sym_stats_d *stats;
226   struct pointer_map_t *map = gimple_mem_ref_stats (cfun)->mem_sym_stats;
227   
228   gcc_assert (map);
229
230   slot = pointer_map_insert (map, var);
231   if (*slot == NULL)
232     {
233       stats = pool_alloc (mem_sym_stats_pool);
234       memset (stats, 0, sizeof (*stats));
235       stats->var = var;
236       *slot = (void *) stats;
237     }
238   else
239     stats = (struct mem_sym_stats_d *) *slot;
240
241   return stats;
242 }
243
244
245 /* Set MPT to be the memory partition associated with symbol SYM.  */
246
247 static inline void
248 set_memory_partition (tree sym, tree mpt)
249 {
250 #if defined ENABLE_CHECKING
251   if (mpt)
252     gcc_assert (TREE_CODE (mpt) == MEMORY_PARTITION_TAG
253                 && !is_gimple_reg (sym));
254 #endif
255
256   var_ann (sym)->mpt = mpt;
257   if (mpt)
258     {
259       if (MPT_SYMBOLS (mpt) == NULL)
260         MPT_SYMBOLS (mpt) = BITMAP_ALLOC (&alias_bitmap_obstack);
261
262       bitmap_set_bit (MPT_SYMBOLS (mpt), DECL_UID (sym));
263
264       /* MPT inherits the call-clobbering attributes from SYM.  */
265       if (is_call_clobbered (sym))
266         {
267           MTAG_GLOBAL (mpt) = 1;
268           mark_call_clobbered (mpt, ESCAPE_IS_GLOBAL);
269         }
270     }
271 }
272
273
274 /* Mark variable VAR as being non-addressable.  */
275
276 static void
277 mark_non_addressable (tree var)
278 {
279   tree mpt;
280
281   if (!TREE_ADDRESSABLE (var))
282     return;
283
284   mpt = memory_partition (var);
285
286   if (!MTAG_P (var))
287     var_ann (var)->call_clobbered = false;
288
289   bitmap_clear_bit (gimple_call_clobbered_vars (cfun), DECL_UID (var));
290   TREE_ADDRESSABLE (var) = 0;
291
292   if (mpt)
293     {
294       /* Note that it's possible for a symbol to have an associated
295          MPT and the MPT have a NULL empty set.  During
296          init_alias_info, all MPTs get their sets cleared out, but the
297          symbols still point to the old MPTs that used to hold them.
298          This is done so that compute_memory_partitions can now which
299          symbols are losing or changing partitions and mark them for
300          renaming.  */
301       if (MPT_SYMBOLS (mpt))
302         bitmap_clear_bit (MPT_SYMBOLS (mpt), DECL_UID (var));
303       set_memory_partition (var, NULL_TREE);
304     }
305 }
306
307
308 /* qsort comparison function to sort type/name tags by DECL_UID.  */
309
310 static int
311 sort_tags_by_id (const void *pa, const void *pb)
312 {
313   const_tree const a = *(const_tree const *)pa;
314   const_tree const b = *(const_tree const *)pb;
315  
316   return DECL_UID (a) - DECL_UID (b);
317 }
318
319 /* Initialize WORKLIST to contain those memory tags that are marked call
320    clobbered.  Initialized WORKLIST2 to contain the reasons these
321    memory tags escaped.  */
322
323 static void
324 init_transitive_clobber_worklist (VEC (tree, heap) **worklist,
325                                   VEC (int, heap) **worklist2)
326 {
327   referenced_var_iterator rvi;
328   tree curr;
329
330   FOR_EACH_REFERENCED_VAR (curr, rvi)
331     {
332       if (MTAG_P (curr) && is_call_clobbered (curr))
333         {
334           VEC_safe_push (tree, heap, *worklist, curr);
335           VEC_safe_push (int, heap, *worklist2, var_ann (curr)->escape_mask);
336         }
337     }
338 }
339
340 /* Add ALIAS to WORKLIST (and the reason for escaping REASON to WORKLIST2) if
341    ALIAS is not already marked call clobbered, and is a memory
342    tag.  */
343
344 static void
345 add_to_worklist (tree alias, VEC (tree, heap) **worklist,
346                  VEC (int, heap) **worklist2,
347                  int reason)
348 {
349   if (MTAG_P (alias) && !is_call_clobbered (alias))
350     {
351       VEC_safe_push (tree, heap, *worklist, alias);
352       VEC_safe_push (int, heap, *worklist2, reason);
353     }
354 }
355
356 /* Mark aliases of TAG as call clobbered, and place any tags on the
357    alias list that were not already call clobbered on WORKLIST.  */
358
359 static void
360 mark_aliases_call_clobbered (tree tag, VEC (tree, heap) **worklist,
361                              VEC (int, heap) **worklist2)
362 {
363   bitmap aliases;
364   bitmap_iterator bi;
365   unsigned int i;
366   tree entry;
367   var_ann_t ta = var_ann (tag);
368
369   if (!MTAG_P (tag))
370     return;
371   aliases = may_aliases (tag);
372   if (!aliases)
373     return;
374
375   EXECUTE_IF_SET_IN_BITMAP (aliases, 0, i, bi)
376     {
377       entry = referenced_var (i);
378       if (!unmodifiable_var_p (entry))
379         {
380           add_to_worklist (entry, worklist, worklist2, ta->escape_mask);
381           mark_call_clobbered (entry, ta->escape_mask);
382         }
383     }
384 }
385
386 /* Tags containing global vars need to be marked as global.
387    Tags containing call clobbered vars need to be marked as call
388    clobbered. */
389
390 static void
391 compute_tag_properties (void)
392 {
393   referenced_var_iterator rvi;
394   tree tag;
395   bool changed = true;
396   VEC (tree, heap) *taglist = NULL;
397
398   FOR_EACH_REFERENCED_VAR (tag, rvi)
399     {
400       if (!MTAG_P (tag) || TREE_CODE (tag) == STRUCT_FIELD_TAG)
401         continue;
402       VEC_safe_push (tree, heap, taglist, tag);
403     }
404
405   /* We sort the taglist by DECL_UID, for two reasons.
406      1. To get a sequential ordering to make the bitmap accesses
407      faster.
408      2. Because of the way we compute aliases, it's more likely that
409      an earlier tag is included in a later tag, and this will reduce
410      the number of iterations.
411
412      If we had a real tag graph, we would just topo-order it and be
413      done with it.  */
414   qsort (VEC_address (tree, taglist),
415          VEC_length (tree, taglist),
416          sizeof (tree),
417          sort_tags_by_id);
418
419   /* Go through each tag not marked as global, and if it aliases
420      global vars, mark it global. 
421      
422      If the tag contains call clobbered vars, mark it call
423      clobbered.  
424
425      This loop iterates because tags may appear in the may-aliases
426      list of other tags when we group.  */
427
428   while (changed)
429     {
430       unsigned int k;
431
432       changed = false;      
433       for (k = 0; VEC_iterate (tree, taglist, k, tag); k++)
434         {
435           bitmap ma;
436           bitmap_iterator bi;
437           unsigned int i;
438           tree entry;
439           bool tagcc = is_call_clobbered (tag);
440           bool tagglobal = MTAG_GLOBAL (tag);
441           
442           if (tagcc && tagglobal)
443             continue;
444           
445           ma = may_aliases (tag);
446           if (!ma)
447             continue;
448
449           EXECUTE_IF_SET_IN_BITMAP (ma, 0, i, bi)
450             {
451               entry = referenced_var (i);
452               /* Call clobbered entries cause the tag to be marked
453                  call clobbered.  */
454               if (!tagcc && is_call_clobbered (entry))
455                 {
456                   mark_call_clobbered (tag, var_ann (entry)->escape_mask);
457                   tagcc = true;
458                   changed = true;
459                 }
460
461               /* Global vars cause the tag to be marked global.  */
462               if (!tagglobal && is_global_var (entry))
463                 {
464                   MTAG_GLOBAL (tag) = true;
465                   changed = true;
466                   tagglobal = true;
467                 }
468
469               /* Early exit once both global and cc are set, since the
470                  loop can't do any more than that.  */
471               if (tagcc && tagglobal)
472                 break;
473             }
474         }
475     }
476   VEC_free (tree, heap, taglist);
477 }
478
479 /* Set up the initial variable clobbers and globalness.
480    When this function completes, only tags whose aliases need to be
481    clobbered will be set clobbered.  Tags clobbered because they   
482    contain call clobbered vars are handled in compute_tag_properties.  */
483
484 static void
485 set_initial_properties (struct alias_info *ai)
486 {
487   unsigned int i;
488   referenced_var_iterator rvi;
489   tree var;
490   tree ptr;
491
492   FOR_EACH_REFERENCED_VAR (var, rvi)
493     {
494       if (is_global_var (var) 
495           && (!var_can_have_subvars (var)
496               || get_subvars_for_var (var) == NULL))
497         {
498           if (!unmodifiable_var_p (var))
499             mark_call_clobbered (var, ESCAPE_IS_GLOBAL);
500         }
501       else if (TREE_CODE (var) == PARM_DECL
502                && gimple_default_def (cfun, var)
503                && POINTER_TYPE_P (TREE_TYPE (var)))
504         {
505           tree def = gimple_default_def (cfun, var);
506           get_ptr_info (def)->value_escapes_p = 1;
507           get_ptr_info (def)->escape_mask |= ESCAPE_IS_PARM;      
508         }
509     }
510
511   for (i = 0; VEC_iterate (tree, ai->processed_ptrs, i, ptr); i++)
512     {
513       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
514       tree tag = symbol_mem_tag (SSA_NAME_VAR (ptr));
515       
516       if (pi->value_escapes_p)
517         {
518           /* If PTR escapes then its associated memory tags and
519              pointed-to variables are call-clobbered.  */
520           if (pi->name_mem_tag)
521             mark_call_clobbered (pi->name_mem_tag, pi->escape_mask);
522
523           if (tag)
524             mark_call_clobbered (tag, pi->escape_mask);
525
526           if (pi->pt_vars)
527             {
528               bitmap_iterator bi;
529               unsigned int j;         
530               EXECUTE_IF_SET_IN_BITMAP (pi->pt_vars, 0, j, bi)
531                 if (!unmodifiable_var_p (referenced_var (j)))
532                   mark_call_clobbered (referenced_var (j), pi->escape_mask);
533             }
534         }
535
536       /* If the name tag is call clobbered, so is the symbol tag
537          associated with the base VAR_DECL.  */
538       if (pi->name_mem_tag
539           && tag
540           && is_call_clobbered (pi->name_mem_tag))
541         mark_call_clobbered (tag, pi->escape_mask);
542
543       /* Name tags and symbol tags that we don't know where they point
544          to, might point to global memory, and thus, are clobbered.
545
546          FIXME:  This is not quite right.  They should only be
547          clobbered if value_escapes_p is true, regardless of whether
548          they point to global memory or not.
549          So removing this code and fixing all the bugs would be nice.
550          It is the cause of a bunch of clobbering.  */
551       if ((pi->pt_global_mem || pi->pt_anything) 
552           && pi->is_dereferenced && pi->name_mem_tag)
553         {
554           mark_call_clobbered (pi->name_mem_tag, ESCAPE_IS_GLOBAL);
555           MTAG_GLOBAL (pi->name_mem_tag) = true;
556         }
557       
558       if ((pi->pt_global_mem || pi->pt_anything) 
559           && pi->is_dereferenced
560           && tag)
561         {
562           mark_call_clobbered (tag, ESCAPE_IS_GLOBAL);
563           MTAG_GLOBAL (tag) = true;
564         }
565     }
566 }
567
568 /* Compute which variables need to be marked call clobbered because
569    their tag is call clobbered, and which tags need to be marked
570    global because they contain global variables.  */
571
572 static void
573 compute_call_clobbered (struct alias_info *ai)
574 {
575   VEC (tree, heap) *worklist = NULL;
576   VEC(int,heap) *worklist2 = NULL;
577   
578   timevar_push (TV_CALL_CLOBBER);
579   set_initial_properties (ai);
580   init_transitive_clobber_worklist (&worklist, &worklist2);
581   while (VEC_length (tree, worklist) != 0)
582     {
583       tree curr = VEC_pop (tree, worklist);
584       int reason = VEC_pop (int, worklist2);
585       
586       mark_call_clobbered (curr, reason);
587       mark_aliases_call_clobbered (curr, &worklist, &worklist2);
588     }
589   VEC_free (tree, heap, worklist);
590   VEC_free (int, heap, worklist2);
591   compute_tag_properties ();
592   timevar_pop (TV_CALL_CLOBBER);
593 }
594
595
596 /* Dump memory partition information to FILE.  */
597
598 static void
599 dump_memory_partitions (FILE *file)
600 {
601   unsigned i, npart;
602   unsigned long nsyms;
603   tree mpt;
604
605   fprintf (file, "\nMemory partitions\n\n");
606   for (i = 0, npart = 0, nsyms = 0;
607        VEC_iterate (tree, gimple_ssa_operands (cfun)->mpt_table, i, mpt);
608        i++)
609     {
610       if (mpt)
611         {
612           bitmap syms = MPT_SYMBOLS (mpt);
613           unsigned long n = (syms) ? bitmap_count_bits (syms) : 0;
614
615           fprintf (file, "#%u: ", i);
616           print_generic_expr (file, mpt, 0);
617           fprintf (file, ": %lu elements: ", n);
618           dump_decl_set (file, syms);
619           npart++;
620           nsyms += n;
621         }
622     }
623
624   fprintf (file, "\n%u memory partitions holding %lu symbols\n", npart, nsyms);
625 }
626
627
628 /* Dump memory partition information to stderr.  */
629
630 void
631 debug_memory_partitions (void)
632 {
633   dump_memory_partitions (stderr);
634 }
635
636
637 /* Return true if memory partitioning is required given the memory
638    reference estimates in STATS.  */
639
640 static inline bool
641 need_to_partition_p (struct mem_ref_stats_d *stats)
642 {
643   long num_vops = stats->num_vuses + stats->num_vdefs;
644   long avg_vops = CEIL (num_vops, stats->num_mem_stmts);
645   return (num_vops > (long) MAX_ALIASED_VOPS
646           && avg_vops > (long) AVG_ALIASED_VOPS);
647 }
648
649
650 /* Count the actual number of virtual operators in CFUN.  Note that
651    this is only meaningful after virtual operands have been populated,
652    so it should be invoked at the end of compute_may_aliases.
653
654    The number of virtual operators are stored in *NUM_VDEFS_P and
655    *NUM_VUSES_P, the number of partitioned symbols in
656    *NUM_PARTITIONED_P and the number of unpartitioned symbols in
657    *NUM_UNPARTITIONED_P.
658
659    If any of these pointers is NULL the corresponding count is not
660    computed.  */
661
662 static void
663 count_mem_refs (long *num_vuses_p, long *num_vdefs_p,
664                 long *num_partitioned_p, long *num_unpartitioned_p)
665 {
666   block_stmt_iterator bsi;
667   basic_block bb;
668   long num_vdefs, num_vuses, num_partitioned, num_unpartitioned;
669   referenced_var_iterator rvi;
670   tree sym;
671
672   num_vuses = num_vdefs = num_partitioned = num_unpartitioned = 0;
673
674   if (num_vuses_p || num_vdefs_p)
675     FOR_EACH_BB (bb)
676       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
677         {
678           tree stmt = bsi_stmt (bsi);
679           if (stmt_references_memory_p (stmt))
680             {
681               num_vuses += NUM_SSA_OPERANDS (stmt, SSA_OP_VUSE);
682               num_vdefs += NUM_SSA_OPERANDS (stmt, SSA_OP_VDEF);
683             }
684         }
685
686   if (num_partitioned_p || num_unpartitioned_p)
687     FOR_EACH_REFERENCED_VAR (sym, rvi)
688       {
689         if (is_gimple_reg (sym))
690           continue;
691
692         if (memory_partition (sym))
693           num_partitioned++;
694         else
695           num_unpartitioned++;
696       }
697
698   if (num_vdefs_p)
699     *num_vdefs_p = num_vdefs;
700
701   if (num_vuses_p)
702     *num_vuses_p = num_vuses;
703
704   if (num_partitioned_p)
705     *num_partitioned_p = num_partitioned;
706
707   if (num_unpartitioned_p)
708     *num_unpartitioned_p = num_unpartitioned;
709 }
710
711
712 /* Dump memory reference stats for function CFUN to FILE.  */
713
714 void
715 dump_mem_ref_stats (FILE *file)
716 {
717   long actual_num_vuses, actual_num_vdefs;
718   long num_partitioned, num_unpartitioned;
719   struct mem_ref_stats_d *stats;
720   
721   stats = gimple_mem_ref_stats (cfun);
722
723   count_mem_refs (&actual_num_vuses, &actual_num_vdefs, &num_partitioned,
724                   &num_unpartitioned);
725
726   fprintf (file, "\nMemory reference statistics for %s\n\n", 
727            lang_hooks.decl_printable_name (current_function_decl, 2));
728
729   fprintf (file, "Number of memory statements:     %ld\n",
730            stats->num_mem_stmts);
731   fprintf (file, "Number of call sites:            %ld\n",
732            stats->num_call_sites);
733   fprintf (file, "Number of pure/const call sites: %ld\n",
734            stats->num_pure_const_call_sites);
735   fprintf (file, "Number of asm sites:             %ld\n",
736            stats->num_asm_sites);
737   fprintf (file, "Estimated number of loads:       %ld (%ld/stmt)\n",
738            stats->num_vuses,
739            (stats->num_mem_stmts)
740            ? CEIL (stats->num_vuses, stats->num_mem_stmts)
741            : 0);
742   fprintf (file, "Actual number of loads:          %ld (%ld/stmt)\n",
743            actual_num_vuses, 
744            (stats->num_mem_stmts)
745            ? CEIL (actual_num_vuses, stats->num_mem_stmts)
746            : 0);
747
748   if (actual_num_vuses > stats->num_vuses + (stats->num_vuses / 25))
749     fprintf (file, "\t(warning: estimation is lower by more than 25%%)\n");
750
751   fprintf (file, "Estimated number of stores:      %ld (%ld/stmt)\n",
752            stats->num_vdefs,
753            (stats->num_mem_stmts)
754            ? CEIL (stats->num_vdefs, stats->num_mem_stmts)
755            : 0);
756   fprintf (file, "Actual number of stores:         %ld (%ld/stmt)\n",
757            actual_num_vdefs, 
758            (stats->num_mem_stmts)
759            ? CEIL (actual_num_vdefs, stats->num_mem_stmts)
760            : 0);
761
762   if (actual_num_vdefs > stats->num_vdefs + (stats->num_vdefs / 25))
763     fprintf (file, "\t(warning: estimation is lower by more than 25%%)\n");
764
765   fprintf (file, "Partitioning thresholds:         MAX = %d   AVG = %d "
766            "(%sNEED TO PARTITION)\n", MAX_ALIASED_VOPS, AVG_ALIASED_VOPS,
767            stats->num_mem_stmts && need_to_partition_p (stats) ? "" : "NO ");
768   fprintf (file, "Number of partitioned symbols:   %ld\n", num_partitioned);
769   fprintf (file, "Number of unpartitioned symbols: %ld\n", num_unpartitioned);
770 }
771
772
773 /* Dump memory reference stats for function FN to stderr.  */
774
775 void
776 debug_mem_ref_stats (void)
777 {
778   dump_mem_ref_stats (stderr);
779 }
780
781
782 /* Dump memory reference stats for variable VAR to FILE.  */
783
784 static void
785 dump_mem_sym_stats (FILE *file, tree var)
786 {
787   mem_sym_stats_t stats = mem_sym_stats (cfun, var);
788
789   if (stats == NULL)
790     return;
791
792   fprintf (file, "read frequency: %6ld, write frequency: %6ld, "
793            "direct reads: %3ld, direct writes: %3ld, "
794            "indirect reads: %4ld, indirect writes: %4ld, symbol: ",
795            stats->frequency_reads, stats->frequency_writes,
796            stats->num_direct_reads, stats->num_direct_writes,
797            stats->num_indirect_reads, stats->num_indirect_writes);
798   print_generic_expr (file, stats->var, 0);
799   fprintf (file, ", tags: ");
800   dump_decl_set (file, stats->parent_tags);
801 }
802
803
804 /* Dump memory reference stats for variable VAR to stderr.  */
805
806 void
807 debug_mem_sym_stats (tree var)
808 {
809   dump_mem_sym_stats (stderr, var);
810 }
811
812
813 /* Dump memory reference stats for all memory symbols to FILE.  */
814
815 static void
816 dump_all_mem_sym_stats (FILE *file)
817 {
818   referenced_var_iterator rvi;
819   tree sym;
820
821   FOR_EACH_REFERENCED_VAR (sym, rvi)
822     {
823       if (is_gimple_reg (sym))
824         continue;
825
826       dump_mem_sym_stats (file, sym);
827     }
828 }
829
830
831 /* Dump memory reference stats for all memory symbols to stderr.  */
832
833 void
834 debug_all_mem_sym_stats (void)
835 {
836   dump_all_mem_sym_stats (stderr);
837 }
838
839
840 /* Dump the MP_INFO array to FILE.  */
841
842 static void
843 dump_mp_info (FILE *file, VEC(mem_sym_stats_t,heap) *mp_info)
844 {
845   unsigned i;
846   mem_sym_stats_t mp_p;
847
848   for (i = 0; VEC_iterate (mem_sym_stats_t, mp_info, i, mp_p); i++)
849     if (!mp_p->partitioned_p)
850       dump_mem_sym_stats (file, mp_p->var);
851 }
852
853
854 /* Dump the MP_INFO array to stderr.  */
855
856 void
857 debug_mp_info (VEC(mem_sym_stats_t,heap) *mp_info)
858 {
859   dump_mp_info (stderr, mp_info);
860 }
861
862
863 /* Update memory reference stats for symbol VAR in statement STMT.
864    NUM_DIRECT_READS and NUM_DIRECT_WRITES specify the number of times
865    that VAR is read/written in STMT (indirect reads/writes are not
866    recorded by this function, see compute_memory_partitions).  */
867
868 void
869 update_mem_sym_stats_from_stmt (tree var, tree stmt, long num_direct_reads,
870                                 long num_direct_writes)
871 {
872   mem_sym_stats_t stats;
873
874   gcc_assert (num_direct_reads >= 0 && num_direct_writes >= 0);
875
876   stats = get_mem_sym_stats_for (var);
877
878   stats->num_direct_reads += num_direct_reads;
879   stats->frequency_reads += ((long) bb_for_stmt (stmt)->frequency
880                              * num_direct_reads);
881
882   stats->num_direct_writes += num_direct_writes;
883   stats->frequency_writes += ((long) bb_for_stmt (stmt)->frequency
884                               * num_direct_writes);
885 }
886
887
888 /* The list is sorted by increasing partitioning score (PSCORE).
889    This score is computed such that symbols with high scores are
890    those that are least likely to be partitioned.  Given a symbol
891    MP->VAR, PSCORE(S) is the result of the following weighted sum
892
893    PSCORE(S) =   FW * 64 + FR * 32
894                + DW * 16 + DR *  8 
895                + IW *  4 + IR *  2
896                + NO_ALIAS
897
898    where
899
900    FW           Execution frequency of writes to S
901    FR           Execution frequency of reads from S
902    DW           Number of direct writes to S
903    DR           Number of direct reads from S
904    IW           Number of indirect writes to S
905    IR           Number of indirect reads from S
906    NO_ALIAS     State of the NO_ALIAS* flags
907
908    The basic idea here is that symbols that are frequently
909    written-to in hot paths of the code are the last to be considered
910    for partitioning.  */
911
912 static inline long
913 pscore (mem_sym_stats_t mp)
914 {
915   return mp->frequency_writes * 64 + mp->frequency_reads * 32
916          + mp->num_direct_writes * 16 + mp->num_direct_reads * 8
917          + mp->num_indirect_writes * 4 + mp->num_indirect_reads * 2
918          + var_ann (mp->var)->noalias_state;
919 }
920
921
922 /* Given two MP_INFO entries MP1 and MP2, return -1 if MP1->VAR should
923    be partitioned before MP2->VAR, 0 if they are the same or 1 if
924    MP1->VAR should be partitioned after MP2->VAR.  */
925
926 static inline int
927 compare_mp_info_entries (mem_sym_stats_t mp1, mem_sym_stats_t mp2)
928 {
929   long pscore1 = pscore (mp1);
930   long pscore2 = pscore (mp2);
931
932   if (pscore1 < pscore2)
933     return -1;
934   else if (pscore1 > pscore2)
935     return 1;
936   else
937     return 0;
938 }
939
940
941 /* Comparison routine for qsort.  The list is sorted by increasing
942    partitioning score (PSCORE).  This score is computed such that
943    symbols with high scores are those that are least likely to be
944    partitioned.  */
945
946 static int
947 mp_info_cmp (const void *p, const void *q)
948 {
949   mem_sym_stats_t e1 = *((const mem_sym_stats_t *) p);
950   mem_sym_stats_t e2 = *((const mem_sym_stats_t *) q);
951   return compare_mp_info_entries (e1, e2);
952 }
953
954
955 /* Sort the array of reference counts used to compute memory partitions.
956    Elements are sorted in ascending order of execution frequency and 
957    descending order of virtual operators needed.  */
958
959 static inline void
960 sort_mp_info (VEC(mem_sym_stats_t,heap) *list)
961 {
962   unsigned num = VEC_length (mem_sym_stats_t, list);
963
964   if (num < 2)
965     return;
966
967   if (num == 2)
968     {
969       if (compare_mp_info_entries (VEC_index (mem_sym_stats_t, list, 0),
970                                    VEC_index (mem_sym_stats_t, list, 1)) > 0)
971         {  
972           /* Swap elements if they are in the wrong order.  */
973           mem_sym_stats_t tmp = VEC_index (mem_sym_stats_t, list, 0);
974           VEC_replace (mem_sym_stats_t, list, 0,
975                        VEC_index (mem_sym_stats_t, list, 1));
976           VEC_replace (mem_sym_stats_t, list, 1, tmp);
977         }
978
979       return;
980     }
981
982   /* There are 3 or more elements, call qsort.  */
983   qsort (VEC_address (mem_sym_stats_t, list),
984          VEC_length (mem_sym_stats_t, list), 
985          sizeof (mem_sym_stats_t),
986          mp_info_cmp);
987 }
988
989
990 /* Return the memory partition tag (MPT) associated with memory
991    symbol SYM.  */
992
993 static tree
994 get_mpt_for (tree sym)
995 {
996   tree mpt;
997
998   /* Don't create a new tag unnecessarily.  */
999   mpt = memory_partition (sym);
1000   if (mpt == NULL_TREE)
1001     {
1002       mpt = create_tag_raw (MEMORY_PARTITION_TAG, TREE_TYPE (sym), "MPT");
1003       TREE_ADDRESSABLE (mpt) = 0;
1004       add_referenced_var (mpt);
1005       VEC_safe_push (tree, heap, gimple_ssa_operands (cfun)->mpt_table, mpt);
1006       gcc_assert (MPT_SYMBOLS (mpt) == NULL);
1007       set_memory_partition (sym, mpt);
1008     }
1009
1010   return mpt;
1011 }
1012
1013
1014 /* Add MP_P->VAR to a memory partition and return the partition.  */
1015
1016 static tree
1017 find_partition_for (mem_sym_stats_t mp_p)
1018 {
1019   unsigned i;
1020   VEC(tree,heap) *mpt_table;
1021   tree mpt;
1022
1023   mpt_table = gimple_ssa_operands (cfun)->mpt_table;
1024   mpt = NULL_TREE;
1025
1026   /* Find an existing partition for MP_P->VAR.  */
1027   for (i = 0; VEC_iterate (tree, mpt_table, i, mpt); i++)
1028     {
1029       mem_sym_stats_t mpt_stats;
1030
1031       /* If MPT does not have any symbols yet, use it.  */
1032       if (MPT_SYMBOLS (mpt) == NULL)
1033         break;
1034
1035       /* Otherwise, see if MPT has common parent tags with MP_P->VAR,
1036          but avoid grouping clobbered variables with non-clobbered
1037          variables (otherwise, this tends to creates a single memory
1038          partition because other call-clobbered variables may have
1039          common parent tags with non-clobbered ones).  */
1040       mpt_stats = get_mem_sym_stats_for (mpt);
1041       if (mp_p->parent_tags
1042           && mpt_stats->parent_tags
1043           && is_call_clobbered (mpt) == is_call_clobbered (mp_p->var)
1044           && bitmap_intersect_p (mpt_stats->parent_tags, mp_p->parent_tags))
1045         break;
1046
1047       /* If no common parent tags are found, see if both MPT and
1048          MP_P->VAR are call-clobbered.  */
1049       if (is_call_clobbered (mpt) && is_call_clobbered (mp_p->var))
1050         break;
1051     }
1052
1053   if (mpt == NULL_TREE)
1054     mpt = get_mpt_for (mp_p->var);
1055   else
1056     set_memory_partition (mp_p->var, mpt);
1057
1058   mp_p->partitioned_p = true;
1059
1060   mark_sym_for_renaming (mp_p->var);
1061   mark_sym_for_renaming (mpt);
1062
1063   return mpt;
1064 }
1065
1066
1067 /* Rewrite the alias set for TAG to use the newly created partitions.
1068    If TAG is NULL, rewrite the set of call-clobbered variables.
1069    NEW_ALIASES is a scratch bitmap to build the new set of aliases for
1070    TAG.  */
1071
1072 static void
1073 rewrite_alias_set_for (tree tag, bitmap new_aliases)
1074 {
1075   bitmap_iterator bi;
1076   unsigned i;
1077   tree mpt, sym;
1078
1079   EXECUTE_IF_SET_IN_BITMAP (MTAG_ALIASES (tag), 0, i, bi)
1080     {
1081       sym = referenced_var (i);
1082       mpt = memory_partition (sym);
1083       if (mpt)
1084         bitmap_set_bit (new_aliases, DECL_UID (mpt));
1085       else
1086         bitmap_set_bit (new_aliases, DECL_UID (sym));
1087     }
1088
1089   /* Rebuild the may-alias array for TAG.  */
1090   bitmap_copy (MTAG_ALIASES (tag), new_aliases);
1091 }
1092
1093
1094 /* Determine how many virtual operands can be saved by partitioning
1095    MP_P->VAR into MPT.  When a symbol S is thrown inside a partition
1096    P, every virtual operand that used to reference S will now
1097    reference P.  Whether it reduces the number of virtual operands
1098    depends on:
1099
1100    1- Direct references to S are never saved.  Instead of the virtual
1101       operand to S, we will now have a virtual operand to P.
1102
1103    2- Indirect references to S are reduced only for those memory tags
1104       holding S that already had other symbols partitioned into P.
1105       For instance, if a memory tag T has the alias set { a b S c },
1106       the first time we partition S into P, the alias set will become
1107       { a b P c }, so no virtual operands will be saved. However, if
1108       we now partition symbol 'c' into P, then the alias set for T
1109       will become { a b P }, so we will be saving one virtual operand
1110       for every indirect reference to 'c'.
1111
1112    3- Is S is call-clobbered, we save as many virtual operands as
1113       call/asm sites exist in the code, but only if other
1114       call-clobbered symbols have been grouped into P.  The first
1115       call-clobbered symbol that we group does not produce any
1116       savings.
1117
1118    MEM_REF_STATS points to CFUN's memory reference information.  */
1119
1120 static void
1121 estimate_vop_reduction (struct mem_ref_stats_d *mem_ref_stats,
1122                         mem_sym_stats_t mp_p, tree mpt)
1123 {
1124   unsigned i;
1125   bitmap_iterator bi;
1126   mem_sym_stats_t mpt_stats;
1127
1128   /* We should only get symbols with indirect references here.  */
1129   gcc_assert (mp_p->num_indirect_reads > 0 || mp_p->num_indirect_writes > 0);
1130
1131   /* Note that the only statistics we keep for MPT is the set of
1132      parent tags to know which memory tags have had alias members
1133      partitioned, and the indicator has_call_clobbered_vars.
1134      Reference counts are not important for MPT.  */
1135   mpt_stats = get_mem_sym_stats_for (mpt);
1136
1137   /* Traverse all the parent tags for MP_P->VAR.  For every tag T, if
1138      partition P is already grouping aliases of T, then reduce the
1139      number of virtual operands by the number of direct references
1140      to T.  */
1141   if (mp_p->parent_tags)
1142     {
1143       if (mpt_stats->parent_tags == NULL)
1144         mpt_stats->parent_tags = BITMAP_ALLOC (&alias_bitmap_obstack);
1145
1146       EXECUTE_IF_SET_IN_BITMAP (mp_p->parent_tags, 0, i, bi)
1147         {
1148           if (bitmap_bit_p (mpt_stats->parent_tags, i))
1149             {
1150               /* Partition MPT is already partitioning symbols in the
1151                  alias set for TAG.  This means that we are now saving
1152                  1 virtual operand for every direct reference to TAG.  */
1153               tree tag = referenced_var (i);
1154               mem_sym_stats_t tag_stats = mem_sym_stats (cfun, tag);
1155               mem_ref_stats->num_vuses -= tag_stats->num_direct_reads;
1156               mem_ref_stats->num_vdefs -= tag_stats->num_direct_writes;
1157             }
1158           else
1159             {
1160               /* This is the first symbol in tag I's alias set that is
1161                  being grouped under MPT.  We will not save any
1162                  virtual operands this time, but record that MPT is
1163                  grouping a symbol from TAG's alias set so that the
1164                  next time we get the savings.  */
1165               bitmap_set_bit (mpt_stats->parent_tags, i);
1166             }
1167         }
1168     }
1169
1170   /* If MP_P->VAR is call-clobbered, and MPT is already grouping
1171      call-clobbered symbols, then we will save as many virtual
1172      operands as asm/call sites there are.  */
1173   if (is_call_clobbered (mp_p->var))
1174     {
1175       if (mpt_stats->has_call_clobbered_vars)
1176         mem_ref_stats->num_vdefs -= mem_ref_stats->num_call_sites
1177                                     + mem_ref_stats->num_asm_sites;
1178       else
1179         mpt_stats->has_call_clobbered_vars = true;
1180     }
1181 }
1182
1183
1184 /* Helper for compute_memory_partitions.  Transfer reference counts
1185    from pointers to their pointed-to sets.  Counters for pointers were
1186    computed by update_alias_info.  MEM_REF_STATS points to CFUN's
1187    memory reference information.  */
1188
1189 static void
1190 update_reference_counts (struct mem_ref_stats_d *mem_ref_stats)
1191 {
1192   unsigned i;
1193   bitmap_iterator bi;
1194   mem_sym_stats_t sym_stats;
1195
1196   for (i = 1; i < num_ssa_names; i++)
1197     {
1198       tree ptr;
1199       struct ptr_info_def *pi;
1200
1201       ptr = ssa_name (i);
1202       if (ptr
1203           && POINTER_TYPE_P (TREE_TYPE (ptr))
1204           && (pi = SSA_NAME_PTR_INFO (ptr)) != NULL
1205           && pi->is_dereferenced)
1206         {
1207           unsigned j;
1208           bitmap_iterator bj;
1209           tree tag;
1210           mem_sym_stats_t ptr_stats, tag_stats;
1211
1212           /* If PTR has flow-sensitive points-to information, use
1213              PTR's name tag, otherwise use the symbol tag associated
1214              with PTR's symbol.  */
1215           if (pi->name_mem_tag)
1216             tag = pi->name_mem_tag;
1217           else
1218             tag = symbol_mem_tag (SSA_NAME_VAR (ptr));
1219
1220           ptr_stats = get_mem_sym_stats_for (ptr);
1221           tag_stats = get_mem_sym_stats_for (tag);
1222
1223           /* TAG has as many direct references as dereferences we
1224              found for its parent pointer.  */
1225           tag_stats->num_direct_reads += ptr_stats->num_direct_reads;
1226           tag_stats->num_direct_writes += ptr_stats->num_direct_writes;
1227
1228           /* All the dereferences of pointer PTR are considered direct
1229              references to PTR's memory tag (TAG).  In turn,
1230              references to TAG will become virtual operands for every
1231              symbol in TAG's alias set.  So, for every symbol ALIAS in
1232              TAG's alias set, add as many indirect references to ALIAS
1233              as direct references there are for TAG.  */
1234           if (MTAG_ALIASES (tag))
1235             EXECUTE_IF_SET_IN_BITMAP (MTAG_ALIASES (tag), 0, j, bj)
1236               {
1237                 tree alias = referenced_var (j);
1238                 sym_stats = get_mem_sym_stats_for (alias);
1239
1240                 /* All the direct references to TAG are indirect references
1241                    to ALIAS.  */
1242                 sym_stats->num_indirect_reads += ptr_stats->num_direct_reads;
1243                 sym_stats->num_indirect_writes += ptr_stats->num_direct_writes;
1244                 sym_stats->frequency_reads += ptr_stats->frequency_reads;
1245                 sym_stats->frequency_writes += ptr_stats->frequency_writes;
1246
1247                 /* Indicate that TAG is one of ALIAS's parent tags.  */
1248                 if (sym_stats->parent_tags == NULL)
1249                   sym_stats->parent_tags = BITMAP_ALLOC (&alias_bitmap_obstack);
1250                 bitmap_set_bit (sym_stats->parent_tags, DECL_UID (tag));
1251               }
1252         }
1253     }
1254
1255   /* Call-clobbered symbols are indirectly written at every
1256      call/asm site.  */
1257   EXECUTE_IF_SET_IN_BITMAP (gimple_call_clobbered_vars (cfun), 0, i, bi)
1258     {
1259       tree sym = referenced_var (i);
1260       sym_stats = get_mem_sym_stats_for (sym);
1261       sym_stats->num_indirect_writes += mem_ref_stats->num_call_sites
1262                                         + mem_ref_stats->num_asm_sites;
1263     }
1264
1265   /* Addressable symbols are indirectly written at some ASM sites.
1266      Since only ASM sites that clobber memory actually affect
1267      addressable symbols, this is an over-estimation.  */
1268   EXECUTE_IF_SET_IN_BITMAP (gimple_addressable_vars (cfun), 0, i, bi)
1269     {
1270       tree sym = referenced_var (i);
1271       sym_stats = get_mem_sym_stats_for (sym);
1272       sym_stats->num_indirect_writes += mem_ref_stats->num_asm_sites;
1273     }
1274 }
1275
1276
1277 /* Helper for compute_memory_partitions.  Add all memory symbols to
1278    *MP_INFO_P and compute the initial estimate for the total number of
1279    virtual operands needed.  MEM_REF_STATS points to CFUN's memory
1280    reference information.  On exit, *TAGS_P will contain the list of
1281    memory tags whose alias set need to be rewritten after
1282    partitioning.  */
1283
1284 static void
1285 build_mp_info (struct mem_ref_stats_d *mem_ref_stats,
1286                  VEC(mem_sym_stats_t,heap) **mp_info_p,
1287                  VEC(tree,heap) **tags_p)
1288 {
1289   tree var;
1290   referenced_var_iterator rvi;
1291
1292   FOR_EACH_REFERENCED_VAR (var, rvi)
1293     {
1294       mem_sym_stats_t sym_stats;
1295       tree old_mpt;
1296
1297       /* We are only interested in memory symbols other than MPTs.  */
1298       if (is_gimple_reg (var) || TREE_CODE (var) == MEMORY_PARTITION_TAG)
1299         continue;
1300
1301       /* Collect memory tags into the TAGS array so that we can
1302          rewrite their alias sets after partitioning.  */
1303       if (MTAG_P (var) && MTAG_ALIASES (var))
1304         VEC_safe_push (tree, heap, *tags_p, var);
1305
1306       /* Since we are going to re-compute partitions, any symbols that
1307          used to belong to a partition must be detached from it and
1308          marked for renaming.  */
1309       if ((old_mpt = memory_partition (var)) != NULL)
1310         {
1311           mark_sym_for_renaming (old_mpt);
1312           set_memory_partition (var, NULL_TREE);
1313           mark_sym_for_renaming (var);
1314         }
1315
1316       sym_stats = get_mem_sym_stats_for (var);
1317
1318       /* Add VAR's reference info to MP_INFO.  Note that the only
1319          symbols that make sense to partition are those that have
1320          indirect references.  If a symbol S is always directly
1321          referenced, partitioning it will not reduce the number of
1322          virtual operators.  The only symbols that are profitable to
1323          partition are those that belong to alias sets and/or are
1324          call-clobbered.  */
1325       if (sym_stats->num_indirect_reads > 0
1326           || sym_stats->num_indirect_writes > 0)
1327         VEC_safe_push (mem_sym_stats_t, heap, *mp_info_p, sym_stats);
1328
1329       /* Update the number of estimated VOPS.  Note that direct
1330          references to memory tags are always counted as indirect
1331          references to their alias set members, so if a memory tag has
1332          aliases, do not count its direct references to avoid double
1333          accounting.  */
1334       if (!MTAG_P (var) || !MTAG_ALIASES (var))
1335         {
1336           mem_ref_stats->num_vuses += sym_stats->num_direct_reads;
1337           mem_ref_stats->num_vdefs += sym_stats->num_direct_writes;
1338         }
1339
1340       mem_ref_stats->num_vuses += sym_stats->num_indirect_reads;
1341       mem_ref_stats->num_vdefs += sym_stats->num_indirect_writes;
1342     }
1343 }
1344
1345
1346 /* Compute memory partitions.  A memory partition (MPT) is an
1347    arbitrary grouping of memory symbols, such that references to one
1348    member of the group is considered a reference to all the members of
1349    the group.
1350    
1351    As opposed to alias sets in memory tags, the grouping into
1352    partitions is completely arbitrary and only done to reduce the
1353    number of virtual operands.  The only rule that needs to be
1354    observed when creating memory partitions is that given two memory
1355    partitions MPT.i and MPT.j, they must not contain symbols in
1356    common.
1357
1358    Memory partitions are used when putting the program into Memory-SSA
1359    form.  In particular, in Memory-SSA PHI nodes are not computed for
1360    individual memory symbols.  They are computed for memory
1361    partitions.  This reduces the amount of PHI nodes in the SSA graph
1362    at the expense of precision (i.e., it makes unrelated stores affect
1363    each other).
1364    
1365    However, it is possible to increase precision by changing this
1366    partitioning scheme.  For instance, if the partitioning scheme is
1367    such that get_mpt_for is the identity function (that is,
1368    get_mpt_for (s) = s), this will result in ultimate precision at the
1369    expense of huge SSA webs.
1370
1371    At the other extreme, a partitioning scheme that groups all the
1372    symbols in the same set results in minimal SSA webs and almost
1373    total loss of precision.
1374
1375    There partitioning heuristic uses three parameters to decide the
1376    order in which symbols are processed.  The list of symbols is
1377    sorted so that symbols that are more likely to be partitioned are
1378    near the top of the list:
1379
1380    - Execution frequency.  If a memory references is in a frequently
1381      executed code path, grouping it into a partition may block useful
1382      transformations and cause sub-optimal code generation.  So, the
1383      partition heuristic tries to avoid grouping symbols with high
1384      execution frequency scores.  Execution frequency is taken
1385      directly from the basic blocks where every reference is made (see
1386      update_mem_sym_stats_from_stmt), which in turn uses the
1387      profile guided machinery, so if the program is compiled with PGO
1388      enabled, more accurate partitioning decisions will be made.
1389
1390    - Number of references.  Symbols with few references in the code,
1391      are partitioned before symbols with many references.
1392
1393    - NO_ALIAS attributes.  Symbols with any of the NO_ALIAS*
1394      attributes are partitioned after symbols marked MAY_ALIAS.
1395
1396    Once the list is sorted, the partitioning proceeds as follows:
1397
1398    1- For every symbol S in MP_INFO, create a new memory partition MP,
1399       if necessary.  To avoid memory partitions that contain symbols
1400       from non-conflicting alias sets, memory partitions are
1401       associated to the memory tag that holds S in its alias set.  So,
1402       when looking for a memory partition for S, the memory partition
1403       associated with one of the memory tags holding S is chosen.  If
1404       none exists, a new one is created.
1405
1406    2- Add S to memory partition MP.
1407
1408    3- Reduce by 1 the number of VOPS for every memory tag holding S.
1409
1410    4- If the total number of VOPS is less than MAX_ALIASED_VOPS or the
1411       average number of VOPS per statement is less than
1412       AVG_ALIASED_VOPS, stop.  Otherwise, go to the next symbol in the
1413       list.  */
1414
1415 static void
1416 compute_memory_partitions (void)
1417 {
1418   tree tag;
1419   unsigned i;
1420   mem_sym_stats_t mp_p;
1421   VEC(mem_sym_stats_t,heap) *mp_info;
1422   bitmap new_aliases;
1423   VEC(tree,heap) *tags;
1424   struct mem_ref_stats_d *mem_ref_stats;
1425   int prev_max_aliased_vops;
1426
1427   mem_ref_stats = gimple_mem_ref_stats (cfun);
1428   gcc_assert (mem_ref_stats->num_vuses == 0 && mem_ref_stats->num_vdefs == 0);
1429
1430   if (mem_ref_stats->num_mem_stmts == 0)
1431     return;
1432
1433   timevar_push (TV_MEMORY_PARTITIONING);
1434
1435   mp_info = NULL;
1436   tags = NULL;
1437   prev_max_aliased_vops = MAX_ALIASED_VOPS;
1438
1439   /* Since we clearly cannot lower the number of virtual operators
1440      below the total number of memory statements in the function, we
1441      may need to adjust MAX_ALIASED_VOPS beforehand.  */
1442   if (MAX_ALIASED_VOPS < mem_ref_stats->num_mem_stmts)
1443     MAX_ALIASED_VOPS = mem_ref_stats->num_mem_stmts;
1444
1445   /* Update reference stats for all the pointed-to variables and
1446      memory tags.  */
1447   update_reference_counts (mem_ref_stats);
1448
1449   /* Add all the memory symbols to MP_INFO.  */
1450   build_mp_info (mem_ref_stats, &mp_info, &tags);
1451
1452   /* No partitions required if we are below the threshold.  */
1453   if (!need_to_partition_p (mem_ref_stats))
1454     {
1455       if (dump_file)
1456         fprintf (dump_file, "\nMemory partitioning NOT NEEDED for %s\n",
1457                  get_name (current_function_decl));
1458       goto done;
1459     }
1460
1461   /* Sort the MP_INFO array so that symbols that should be partitioned
1462      first are near the top of the list.  */
1463   sort_mp_info (mp_info);
1464
1465   if (dump_file)
1466     {
1467       fprintf (dump_file, "\nMemory partitioning NEEDED for %s\n\n",
1468                get_name (current_function_decl));
1469       fprintf (dump_file, "Memory symbol references before partitioning:\n");
1470       dump_mp_info (dump_file, mp_info);
1471     }
1472
1473   /* Create partitions for variables in MP_INFO until we have enough
1474      to lower the total number of VOPS below MAX_ALIASED_VOPS or if
1475      the average number of VOPS per statement is below
1476      AVG_ALIASED_VOPS.  */
1477   for (i = 0; VEC_iterate (mem_sym_stats_t, mp_info, i, mp_p); i++)
1478     {
1479       tree mpt;
1480
1481       /* If we are below the threshold, stop.  */
1482       if (!need_to_partition_p (mem_ref_stats))
1483         break;
1484
1485       mpt = find_partition_for (mp_p);
1486       estimate_vop_reduction (mem_ref_stats, mp_p, mpt);
1487     }
1488
1489   /* After partitions have been created, rewrite alias sets to use
1490      them instead of the original symbols.  This way, if the alias set
1491      was computed as { a b c d e f }, and the subset { b e f } was
1492      grouped into partition MPT.3, then the new alias set for the tag
1493      will be  { a c d MPT.3 }.
1494      
1495      Note that this is not strictly necessary.  The operand scanner
1496      will always check if a symbol belongs to a partition when adding
1497      virtual operands.  However, by reducing the size of the alias
1498      sets to be scanned, the work needed inside the operand scanner is
1499      significantly reduced.  */
1500   new_aliases = BITMAP_ALLOC (&alias_bitmap_obstack);
1501
1502   for (i = 0; VEC_iterate (tree, tags, i, tag); i++)
1503     {
1504       rewrite_alias_set_for (tag, new_aliases);
1505       bitmap_clear (new_aliases);
1506     }
1507
1508   BITMAP_FREE (new_aliases);
1509
1510   if (dump_file)
1511     {
1512       fprintf (dump_file, "\nMemory symbol references after partitioning:\n");
1513       dump_mp_info (dump_file, mp_info);
1514     }
1515
1516 done:
1517   /* Free allocated memory.  */
1518   VEC_free (mem_sym_stats_t, heap, mp_info);
1519   VEC_free (tree, heap, tags);
1520
1521   MAX_ALIASED_VOPS = prev_max_aliased_vops;
1522
1523   timevar_pop (TV_MEMORY_PARTITIONING);
1524 }
1525
1526
1527 /* Compute may-alias information for every variable referenced in function
1528    FNDECL.
1529
1530    Alias analysis proceeds in 3 main phases:
1531
1532    1- Points-to and escape analysis.
1533
1534    This phase walks the use-def chains in the SSA web looking for three
1535    things:
1536
1537         * Assignments of the form P_i = &VAR
1538         * Assignments of the form P_i = malloc()
1539         * Pointers and ADDR_EXPR that escape the current function.
1540
1541    The concept of 'escaping' is the same one used in the Java world.  When
1542    a pointer or an ADDR_EXPR escapes, it means that it has been exposed
1543    outside of the current function.  So, assignment to global variables,
1544    function arguments and returning a pointer are all escape sites, as are
1545    conversions between pointers and integers.
1546
1547    This is where we are currently limited.  Since not everything is renamed
1548    into SSA, we lose track of escape properties when a pointer is stashed
1549    inside a field in a structure, for instance.  In those cases, we are
1550    assuming that the pointer does escape.
1551
1552    We use escape analysis to determine whether a variable is
1553    call-clobbered.  Simply put, if an ADDR_EXPR escapes, then the variable
1554    is call-clobbered.  If a pointer P_i escapes, then all the variables
1555    pointed-to by P_i (and its memory tag) also escape.
1556
1557    2- Compute flow-sensitive aliases
1558
1559    We have two classes of memory tags.  Memory tags associated with the
1560    pointed-to data type of the pointers in the program.  These tags are
1561    called "symbol memory tag" (SMT).  The other class are those associated
1562    with SSA_NAMEs, called "name memory tag" (NMT). The basic idea is that
1563    when adding operands for an INDIRECT_REF *P_i, we will first check
1564    whether P_i has a name tag, if it does we use it, because that will have
1565    more precise aliasing information.  Otherwise, we use the standard symbol
1566    tag.
1567
1568    In this phase, we go through all the pointers we found in points-to
1569    analysis and create alias sets for the name memory tags associated with
1570    each pointer P_i.  If P_i escapes, we mark call-clobbered the variables
1571    it points to and its tag.
1572
1573
1574    3- Compute flow-insensitive aliases
1575
1576    This pass will compare the alias set of every symbol memory tag and
1577    every addressable variable found in the program.  Given a symbol
1578    memory tag SMT and an addressable variable V.  If the alias sets of
1579    SMT and V conflict (as computed by may_alias_p), then V is marked
1580    as an alias tag and added to the alias set of SMT.
1581
1582    For instance, consider the following function:
1583
1584             foo (int i)
1585             {
1586               int *p, a, b;
1587             
1588               if (i > 10)
1589                 p = &a;
1590               else
1591                 p = &b;
1592             
1593               *p = 3;
1594               a = b + 2;
1595               return *p;
1596             }
1597
1598    After aliasing analysis has finished, the symbol memory tag for pointer
1599    'p' will have two aliases, namely variables 'a' and 'b'.  Every time
1600    pointer 'p' is dereferenced, we want to mark the operation as a
1601    potential reference to 'a' and 'b'.
1602
1603             foo (int i)
1604             {
1605               int *p, a, b;
1606
1607               if (i_2 > 10)
1608                 p_4 = &a;
1609               else
1610                 p_6 = &b;
1611               # p_1 = PHI <p_4(1), p_6(2)>;
1612
1613               # a_7 = VDEF <a_3>;
1614               # b_8 = VDEF <b_5>;
1615               *p_1 = 3;
1616
1617               # a_9 = VDEF <a_7>
1618               # VUSE <b_8>
1619               a_9 = b_8 + 2;
1620
1621               # VUSE <a_9>;
1622               # VUSE <b_8>;
1623               return *p_1;
1624             }
1625
1626    In certain cases, the list of may aliases for a pointer may grow too
1627    large.  This may cause an explosion in the number of virtual operands
1628    inserted in the code.  Resulting in increased memory consumption and
1629    compilation time.
1630
1631    When the number of virtual operands needed to represent aliased
1632    loads and stores grows too large (configurable with option --param
1633    max-aliased-vops and --param avg-aliased-vops), alias sets are
1634    grouped to avoid severe compile-time slow downs and memory
1635    consumption. See compute_memory_partitions.  */
1636
1637 unsigned int
1638 compute_may_aliases (void)
1639 {
1640   struct alias_info *ai;
1641
1642   timevar_push (TV_TREE_MAY_ALIAS);
1643   
1644   memset (&alias_stats, 0, sizeof (alias_stats));
1645
1646   /* Initialize aliasing information.  */
1647   ai = init_alias_info ();
1648
1649   /* For each pointer P_i, determine the sets of variables that P_i may
1650      point-to.  For every addressable variable V, determine whether the
1651      address of V escapes the current function, making V call-clobbered
1652      (i.e., whether &V is stored in a global variable or if its passed as a
1653      function call argument).  */
1654   compute_points_to_sets (ai);
1655
1656   /* Collect all pointers and addressable variables, compute alias sets,
1657      create memory tags for pointers and promote variables whose address is
1658      not needed anymore.  */
1659   setup_pointers_and_addressables (ai);
1660
1661   /* Compute type-based flow-insensitive aliasing for all the type
1662      memory tags.  */
1663   compute_flow_insensitive_aliasing (ai);
1664
1665   /* Compute flow-sensitive, points-to based aliasing for all the name
1666      memory tags.  */
1667   compute_flow_sensitive_aliasing (ai);
1668   
1669   /* Compute call clobbering information.  */
1670   compute_call_clobbered (ai);
1671
1672   /* If the program makes no reference to global variables, but it
1673      contains a mixture of pure and non-pure functions, then we need
1674      to create use-def and def-def links between these functions to
1675      avoid invalid transformations on them.  */
1676   maybe_create_global_var ();
1677
1678   /* If the program contains ref-all pointers, finalize may-alias information
1679      for them.  This pass needs to be run after call-clobbering information
1680      has been computed.  */
1681   if (ai->ref_all_symbol_mem_tag)
1682     finalize_ref_all_pointers (ai);
1683
1684   /* Compute memory partitions for every memory variable.  */
1685   compute_memory_partitions ();
1686
1687   /* Remove partitions with no symbols.  Partitions may end up with an
1688      empty MPT_SYMBOLS set if a previous round of alias analysis
1689      needed to partition more symbols.  Since we don't need those
1690      partitions anymore, remove them to free up the space.  */
1691   {
1692     tree mpt;
1693     unsigned i;
1694     VEC(tree,heap) *mpt_table;
1695
1696     mpt_table = gimple_ssa_operands (cfun)->mpt_table;
1697     i = 0;
1698     while (i < VEC_length (tree, mpt_table))
1699       {
1700         mpt = VEC_index (tree, mpt_table, i);
1701         if (MPT_SYMBOLS (mpt) == NULL)
1702           VEC_unordered_remove (tree, mpt_table, i);
1703         else
1704           i++;
1705       }
1706   }
1707
1708   /* Populate all virtual operands and newly promoted register operands.  */
1709   {
1710     block_stmt_iterator bsi;
1711     basic_block bb;
1712     FOR_EACH_BB (bb)
1713       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
1714         update_stmt_if_modified (bsi_stmt (bsi));
1715   }
1716
1717   /* Debugging dumps.  */
1718   if (dump_file)
1719     {
1720       dump_mem_ref_stats (dump_file);
1721       dump_alias_info (dump_file);
1722       dump_points_to_info (dump_file);
1723
1724       if (dump_flags & TDF_STATS)
1725         dump_alias_stats (dump_file);
1726
1727       if (dump_flags & TDF_DETAILS)
1728         dump_referenced_vars (dump_file);
1729     }
1730
1731   /* Report strict aliasing violations.  */
1732   strict_aliasing_warning_backend ();
1733
1734   /* Deallocate memory used by aliasing data structures.  */
1735   delete_alias_info (ai);
1736
1737   if (need_ssa_update_p ())
1738     update_ssa (TODO_update_ssa);
1739
1740   timevar_pop (TV_TREE_MAY_ALIAS);
1741   
1742   return 0;
1743 }
1744
1745 /* Data structure used to count the number of dereferences to PTR
1746    inside an expression.  */
1747 struct count_ptr_d
1748 {
1749   tree ptr;
1750   unsigned count;
1751 };
1752
1753
1754 /* Helper for count_uses_and_derefs.  Called by walk_tree to look for
1755    (ALIGN/MISALIGNED_)INDIRECT_REF nodes for the pointer passed in DATA.  */
1756
1757 static tree
1758 count_ptr_derefs (tree *tp, int *walk_subtrees, void *data)
1759 {
1760   struct count_ptr_d *count_p = (struct count_ptr_d *) data;
1761
1762   /* Do not walk inside ADDR_EXPR nodes.  In the expression &ptr->fld,
1763      pointer 'ptr' is *not* dereferenced, it is simply used to compute
1764      the address of 'fld' as 'ptr + offsetof(fld)'.  */
1765   if (TREE_CODE (*tp) == ADDR_EXPR)
1766     {
1767       *walk_subtrees = 0;
1768       return NULL_TREE;
1769     }
1770
1771   if (INDIRECT_REF_P (*tp) && TREE_OPERAND (*tp, 0) == count_p->ptr)
1772     count_p->count++;
1773
1774   return NULL_TREE;
1775 }
1776
1777
1778 /* Count the number of direct and indirect uses for pointer PTR in
1779    statement STMT.  The number of direct uses is stored in
1780    *NUM_USES_P.  Indirect references are counted separately depending
1781    on whether they are store or load operations.  The counts are
1782    stored in *NUM_STORES_P and *NUM_LOADS_P.  */
1783
1784 void
1785 count_uses_and_derefs (tree ptr, tree stmt, unsigned *num_uses_p,
1786                        unsigned *num_loads_p, unsigned *num_stores_p)
1787 {
1788   ssa_op_iter i;
1789   tree use;
1790
1791   *num_uses_p = 0;
1792   *num_loads_p = 0;
1793   *num_stores_p = 0;
1794
1795   /* Find out the total number of uses of PTR in STMT.  */
1796   FOR_EACH_SSA_TREE_OPERAND (use, stmt, i, SSA_OP_USE)
1797     if (use == ptr)
1798       (*num_uses_p)++;
1799
1800   /* Now count the number of indirect references to PTR.  This is
1801      truly awful, but we don't have much choice.  There are no parent
1802      pointers inside INDIRECT_REFs, so an expression like
1803      '*x_1 = foo (x_1, *x_1)' needs to be traversed piece by piece to
1804      find all the indirect and direct uses of x_1 inside.  The only
1805      shortcut we can take is the fact that GIMPLE only allows
1806      INDIRECT_REFs inside the expressions below.  */
1807   if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
1808       || (TREE_CODE (stmt) == RETURN_EXPR
1809           && TREE_CODE (TREE_OPERAND (stmt, 0)) == GIMPLE_MODIFY_STMT)
1810       || TREE_CODE (stmt) == ASM_EXPR
1811       || TREE_CODE (stmt) == CALL_EXPR)
1812     {
1813       tree lhs, rhs;
1814
1815       if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT)
1816         {
1817           lhs = GIMPLE_STMT_OPERAND (stmt, 0);
1818           rhs = GIMPLE_STMT_OPERAND (stmt, 1);
1819         }
1820       else if (TREE_CODE (stmt) == RETURN_EXPR)
1821         {
1822           tree e = TREE_OPERAND (stmt, 0);
1823           lhs = GIMPLE_STMT_OPERAND (e, 0);
1824           rhs = GIMPLE_STMT_OPERAND (e, 1);
1825         }
1826       else if (TREE_CODE (stmt) == ASM_EXPR)
1827         {
1828           lhs = ASM_OUTPUTS (stmt);
1829           rhs = ASM_INPUTS (stmt);
1830         }
1831       else
1832         {
1833           lhs = NULL_TREE;
1834           rhs = stmt;
1835         }
1836
1837       if (lhs
1838           && (TREE_CODE (lhs) == TREE_LIST
1839               || EXPR_P (lhs)
1840               || GIMPLE_STMT_P (lhs)))
1841         {
1842           struct count_ptr_d count;
1843           count.ptr = ptr;
1844           count.count = 0;
1845           walk_tree (&lhs, count_ptr_derefs, &count, NULL);
1846           *num_stores_p = count.count;
1847         }
1848
1849       if (rhs
1850           && (TREE_CODE (rhs) == TREE_LIST
1851               || EXPR_P (rhs)
1852               || GIMPLE_STMT_P (rhs)))
1853         {
1854           struct count_ptr_d count;
1855           count.ptr = ptr;
1856           count.count = 0;
1857           walk_tree (&rhs, count_ptr_derefs, &count, NULL);
1858           *num_loads_p = count.count;
1859         }
1860     }
1861
1862   gcc_assert (*num_uses_p >= *num_loads_p + *num_stores_p);
1863 }
1864
1865 /* Remove memory references stats for function FN.  */
1866
1867 void
1868 delete_mem_ref_stats (struct function *fn)
1869 {
1870   if (gimple_mem_ref_stats (fn)->mem_sym_stats)
1871     {
1872       free_alloc_pool (mem_sym_stats_pool);
1873       pointer_map_destroy (gimple_mem_ref_stats (fn)->mem_sym_stats);
1874     }
1875   gimple_mem_ref_stats (fn)->mem_sym_stats = NULL;
1876 }
1877
1878
1879 /* Initialize memory reference stats.  */
1880
1881 static void
1882 init_mem_ref_stats (void)
1883 {
1884   struct mem_ref_stats_d *mem_ref_stats = gimple_mem_ref_stats (cfun);
1885
1886   mem_sym_stats_pool = create_alloc_pool ("Mem sym stats",
1887                                           sizeof (struct mem_sym_stats_d),
1888                                           100);
1889   memset (mem_ref_stats, 0, sizeof (struct mem_ref_stats_d));
1890   mem_ref_stats->mem_sym_stats = pointer_map_create ();
1891 }
1892
1893
1894 /* Helper for init_alias_info.  Reset existing aliasing information.  */
1895
1896 static void
1897 reset_alias_info (void)
1898 {
1899   referenced_var_iterator rvi;
1900   tree var;
1901   unsigned i;
1902   bitmap active_nmts, all_nmts;
1903
1904   /* Clear the set of addressable variables.  We do not need to clear
1905      the TREE_ADDRESSABLE bit on every symbol because we are going to
1906      re-compute addressability here.  */
1907   bitmap_clear (gimple_addressable_vars (cfun));
1908
1909   active_nmts = BITMAP_ALLOC (&alias_bitmap_obstack);
1910   all_nmts = BITMAP_ALLOC (&alias_bitmap_obstack);
1911
1912   /* Clear flow-insensitive alias information from each symbol.  */
1913   FOR_EACH_REFERENCED_VAR (var, rvi)
1914     {
1915       if (is_gimple_reg (var))
1916         continue;
1917
1918       if (MTAG_P (var))
1919         MTAG_ALIASES (var) = NULL;
1920
1921       /* Memory partition information will be computed from scratch.  */
1922       if (TREE_CODE (var) == MEMORY_PARTITION_TAG)
1923         MPT_SYMBOLS (var) = NULL;
1924
1925       /* Collect all the name tags to determine if we have any
1926          orphaned that need to be removed from the IL.  A name tag
1927          will be orphaned if it is not associated with any active SSA
1928          name.  */
1929       if (TREE_CODE (var) == NAME_MEMORY_TAG)
1930         bitmap_set_bit (all_nmts, DECL_UID (var));
1931
1932       /* Since we are about to re-discover call-clobbered
1933          variables, clear the call-clobbered flag.  Variables that
1934          are intrinsically call-clobbered (globals, local statics,
1935          etc) will not be marked by the aliasing code, so we can't
1936          remove them from CALL_CLOBBERED_VARS.  
1937
1938          NB: STRUCT_FIELDS are still call clobbered if they are for a
1939          global variable, so we *don't* clear their call clobberedness
1940          just because they are tags, though we will clear it if they
1941          aren't for global variables.  */
1942       if (TREE_CODE (var) == NAME_MEMORY_TAG
1943           || TREE_CODE (var) == SYMBOL_MEMORY_TAG
1944           || TREE_CODE (var) == MEMORY_PARTITION_TAG
1945           || !is_global_var (var))
1946         clear_call_clobbered (var);
1947     }
1948
1949   /* Clear flow-sensitive points-to information from each SSA name.  */
1950   for (i = 1; i < num_ssa_names; i++)
1951     {
1952       tree name = ssa_name (i);
1953
1954       if (!name || !POINTER_TYPE_P (TREE_TYPE (name)))
1955         continue;
1956
1957       if (SSA_NAME_PTR_INFO (name))
1958         {
1959           struct ptr_info_def *pi = SSA_NAME_PTR_INFO (name);
1960
1961           /* Clear all the flags but keep the name tag to
1962              avoid creating new temporaries unnecessarily.  If
1963              this pointer is found to point to a subset or
1964              superset of its former points-to set, then a new
1965              tag will need to be created in create_name_tags.  */
1966           pi->pt_anything = 0;
1967           pi->pt_null = 0;
1968           pi->value_escapes_p = 0;
1969           pi->is_dereferenced = 0;
1970           if (pi->pt_vars)
1971             bitmap_clear (pi->pt_vars);
1972
1973           /* Add NAME's name tag to the set of active tags.  */
1974           if (pi->name_mem_tag)
1975             bitmap_set_bit (active_nmts, DECL_UID (pi->name_mem_tag));
1976         }
1977     }
1978
1979   /* Name memory tags that are no longer associated with an SSA name
1980      are considered stale and should be removed from the IL.  All the
1981      name tags that are in the set ALL_NMTS but not in ACTIVE_NMTS are
1982      considered stale and marked for renaming.  */
1983   bitmap_and_compl_into (all_nmts, active_nmts);
1984   mark_set_for_renaming (all_nmts);
1985
1986   BITMAP_FREE (all_nmts);
1987   BITMAP_FREE (active_nmts);
1988 }
1989
1990
1991 /* Initialize the data structures used for alias analysis.  */
1992
1993 static struct alias_info *
1994 init_alias_info (void)
1995 {
1996   struct alias_info *ai;
1997   referenced_var_iterator rvi;
1998   tree var;
1999
2000   ai = XCNEW (struct alias_info);
2001   ai->ssa_names_visited = sbitmap_alloc (num_ssa_names);
2002   sbitmap_zero (ai->ssa_names_visited);
2003   ai->processed_ptrs = VEC_alloc (tree, heap, 50);
2004   ai->written_vars = pointer_set_create ();
2005   ai->dereferenced_ptrs_store = pointer_set_create ();
2006   ai->dereferenced_ptrs_load = pointer_set_create ();
2007
2008   /* Clear out all memory reference stats.  */
2009   init_mem_ref_stats ();
2010
2011   /* If aliases have been computed before, clear existing information.  */
2012   if (gimple_aliases_computed_p (cfun))
2013     reset_alias_info ();
2014   else
2015     {
2016       /* If this is the first time we compute aliasing information,
2017          every non-register symbol will need to be put into SSA form
2018          (the initial SSA form only operates on GIMPLE registers).  */
2019       FOR_EACH_REFERENCED_VAR (var, rvi)
2020         if (!is_gimple_reg (var))
2021           mark_sym_for_renaming (var);
2022     }
2023
2024   /* Next time, we will need to reset alias information.  */
2025   cfun->gimple_df->aliases_computed_p = true;
2026   if (alias_bitmap_obstack.elements != NULL)
2027     bitmap_obstack_release (&alias_bitmap_obstack);    
2028   bitmap_obstack_initialize (&alias_bitmap_obstack);
2029
2030   return ai;
2031 }
2032
2033
2034 /* Deallocate memory used by alias analysis.  */
2035
2036 static void
2037 delete_alias_info (struct alias_info *ai)
2038 {
2039   size_t i;
2040
2041   sbitmap_free (ai->ssa_names_visited);
2042
2043   VEC_free (tree, heap, ai->processed_ptrs);
2044
2045   for (i = 0; i < ai->num_addressable_vars; i++)
2046     free (ai->addressable_vars[i]);
2047   free (ai->addressable_vars);
2048   
2049   for (i = 0; i < ai->num_pointers; i++)
2050     free (ai->pointers[i]);
2051   free (ai->pointers);
2052
2053   pointer_set_destroy (ai->written_vars);
2054   pointer_set_destroy (ai->dereferenced_ptrs_store);
2055   pointer_set_destroy (ai->dereferenced_ptrs_load);
2056   free (ai);
2057
2058   delete_mem_ref_stats (cfun);
2059   delete_points_to_sets ();
2060 }
2061
2062
2063 /* Used for hashing to identify pointer infos with identical
2064    pt_vars bitmaps.  */
2065
2066 static int
2067 eq_ptr_info (const void *p1, const void *p2)
2068 {
2069   const struct ptr_info_def *n1 = (const struct ptr_info_def *) p1;
2070   const struct ptr_info_def *n2 = (const struct ptr_info_def *) p2;
2071   return bitmap_equal_p (n1->pt_vars, n2->pt_vars);
2072 }
2073
2074 static hashval_t
2075 ptr_info_hash (const void *p)
2076 {
2077   const struct ptr_info_def *n = (const struct ptr_info_def *) p;
2078   return bitmap_hash (n->pt_vars);
2079 }
2080
2081
2082 /* Create name tags for all the pointers that have been dereferenced.
2083    We only create a name tag for a pointer P if P is found to point to
2084    a set of variables (so that we can alias them to *P) or if it is
2085    the result of a call to malloc (which means that P cannot point to
2086    anything else nor alias any other variable).
2087
2088    If two pointers P and Q point to the same set of variables, they
2089    are assigned the same name tag.  */
2090
2091 static void
2092 create_name_tags (void)
2093 {
2094   size_t i;
2095   VEC (tree, heap) *with_ptvars = NULL;
2096   tree ptr;
2097   htab_t ptr_hash;
2098
2099   /* Collect the list of pointers with a non-empty points to set.  */
2100   for (i = 1; i < num_ssa_names; i++)
2101     {
2102       tree ptr = ssa_name (i);
2103       struct ptr_info_def *pi;
2104
2105       if (!ptr
2106           || !POINTER_TYPE_P (TREE_TYPE (ptr))
2107           || !SSA_NAME_PTR_INFO (ptr))
2108         continue;
2109
2110       pi = SSA_NAME_PTR_INFO (ptr);
2111
2112       if (pi->pt_anything || !pi->is_dereferenced)
2113         {
2114           /* No name tags for pointers that have not been
2115              dereferenced or point to an arbitrary location.  */
2116           pi->name_mem_tag = NULL_TREE;
2117           continue;
2118         }
2119
2120       /* Set pt_anything on the pointers without pt_vars filled in so
2121          that they are assigned a symbol tag.  */
2122       if (pi->pt_vars && !bitmap_empty_p (pi->pt_vars)) 
2123         VEC_safe_push (tree, heap, with_ptvars, ptr);
2124       else
2125         set_pt_anything (ptr);
2126     }
2127   
2128   /* If we didn't find any pointers with pt_vars set, we're done.  */
2129   if (!with_ptvars)
2130     return;
2131
2132   ptr_hash = htab_create (10, ptr_info_hash, eq_ptr_info, NULL);
2133
2134   /* Now go through the pointers with pt_vars, and find a name tag
2135      with the same pt_vars as this pointer, or create one if one
2136      doesn't exist.  */
2137   for (i = 0; VEC_iterate (tree, with_ptvars, i, ptr); i++)
2138     {
2139       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
2140       tree old_name_tag = pi->name_mem_tag;
2141       struct ptr_info_def **slot;
2142       
2143       /* If PTR points to a set of variables, check if we don't
2144          have another pointer Q with the same points-to set before
2145          creating a tag.  If so, use Q's tag instead of creating a
2146          new one.
2147          
2148          This is important for not creating unnecessary symbols
2149          and also for copy propagation.  If we ever need to
2150          propagate PTR into Q or vice-versa, we would run into
2151          problems if they both had different name tags because
2152          they would have different SSA version numbers (which
2153          would force us to take the name tags in and out of SSA).  */
2154       slot = (struct ptr_info_def **) htab_find_slot (ptr_hash, pi, INSERT);
2155       if (*slot)
2156         pi->name_mem_tag = (*slot)->name_mem_tag;
2157       else
2158         {
2159           *slot = pi;
2160
2161           /* If we didn't find a pointer with the same points-to set
2162              as PTR, create a new name tag if needed.  */
2163           if (pi->name_mem_tag == NULL_TREE)
2164             pi->name_mem_tag = get_nmt_for (ptr);
2165         }
2166       
2167       /* If the new name tag computed for PTR is different than
2168          the old name tag that it used to have, then the old tag
2169          needs to be removed from the IL, so we mark it for
2170          renaming.  */
2171       if (old_name_tag && old_name_tag != pi->name_mem_tag)
2172         mark_sym_for_renaming (old_name_tag);
2173
2174       /* Inherit volatility from the pointed-to type.  */
2175       TREE_THIS_VOLATILE (pi->name_mem_tag)
2176         |= TREE_THIS_VOLATILE (TREE_TYPE (TREE_TYPE (ptr)));
2177       
2178       /* Mark the new name tag for renaming.  */
2179       mark_sym_for_renaming (pi->name_mem_tag);
2180     }
2181
2182   htab_delete (ptr_hash);
2183
2184   VEC_free (tree, heap, with_ptvars);
2185 }
2186
2187
2188 /* Union the alias set SET into the may-aliases for TAG.  */
2189
2190 static void
2191 union_alias_set_into (tree tag, bitmap set)
2192 {
2193   bitmap ma = MTAG_ALIASES (tag);
2194   
2195   if (bitmap_empty_p (set))
2196     return;
2197   
2198   if (!ma)
2199     ma = MTAG_ALIASES (tag) = BITMAP_ALLOC (&alias_bitmap_obstack);
2200   bitmap_ior_into (ma, set);
2201 }
2202
2203
2204 /* For every pointer P_i in AI->PROCESSED_PTRS, create may-alias sets for
2205    the name memory tag (NMT) associated with P_i.  If P_i escapes, then its
2206    name tag and the variables it points-to are call-clobbered.  Finally, if
2207    P_i escapes and we could not determine where it points to, then all the
2208    variables in the same alias set as *P_i are marked call-clobbered.  This
2209    is necessary because we must assume that P_i may take the address of any
2210    variable in the same alias set.  */
2211
2212 static void
2213 compute_flow_sensitive_aliasing (struct alias_info *ai)
2214 {
2215   size_t i;
2216   tree ptr;
2217   
2218   timevar_push (TV_FLOW_SENSITIVE);
2219   set_used_smts ();
2220   
2221   for (i = 0; VEC_iterate (tree, ai->processed_ptrs, i, ptr); i++)
2222     {
2223       if (!find_what_p_points_to (ptr))
2224         set_pt_anything (ptr);
2225     }
2226
2227   create_name_tags ();
2228
2229   for (i = 0; VEC_iterate (tree, ai->processed_ptrs, i, ptr); i++)
2230     {
2231       struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
2232       tree tag = symbol_mem_tag (SSA_NAME_VAR (ptr));
2233
2234       /* Set up aliasing information for PTR's name memory tag (if it has
2235          one).  Note that only pointers that have been dereferenced will
2236          have a name memory tag.  */
2237       if (pi->name_mem_tag && pi->pt_vars)
2238         {
2239           if (!bitmap_empty_p (pi->pt_vars))
2240             {
2241               union_alias_set_into (pi->name_mem_tag, pi->pt_vars);
2242               union_alias_set_into (tag, pi->pt_vars);
2243               bitmap_clear_bit (MTAG_ALIASES (tag), DECL_UID (tag));
2244             
2245               /* It may be the case that this the tag uid was the only
2246                  bit we had set in the aliases list, and in this case,
2247                  we don't want to keep an empty bitmap, as this
2248                  asserts in tree-ssa-operands.c .  */
2249               if (bitmap_empty_p (MTAG_ALIASES (tag)))
2250                 BITMAP_FREE (MTAG_ALIASES (tag));
2251             }
2252         }
2253     }
2254   timevar_pop (TV_FLOW_SENSITIVE);
2255 }
2256
2257
2258 /* Return TRUE if at least one symbol in TAG2's alias set is also
2259    present in TAG1's alias set.  */
2260
2261 static bool
2262 have_common_aliases_p (bitmap tag1aliases, bitmap tag2aliases)
2263 {
2264
2265   /* This is the old behavior of have_common_aliases_p, which is to
2266      return false if both sets are empty, or one set is and the other
2267      isn't.  */
2268      if ((tag1aliases == NULL && tag2aliases != NULL)
2269       || (tag2aliases == NULL && tag1aliases != NULL)
2270       || (tag1aliases == NULL && tag2aliases == NULL))
2271     return false;
2272
2273   return bitmap_intersect_p (tag1aliases, tag2aliases);
2274 }
2275
2276 /* Compute type-based alias sets.  Traverse all the pointers and
2277    addressable variables found in setup_pointers_and_addressables.
2278    
2279    For every pointer P in AI->POINTERS and addressable variable V in
2280    AI->ADDRESSABLE_VARS, add V to the may-alias sets of P's symbol
2281    memory tag (SMT) if their alias sets conflict.  V is then marked as
2282    an aliased symbol so that the operand scanner knows that statements
2283    containing V have aliased operands.  */
2284
2285 static void
2286 compute_flow_insensitive_aliasing (struct alias_info *ai)
2287 {
2288   size_t i;
2289
2290   timevar_push (TV_FLOW_INSENSITIVE);
2291   /* For every pointer P, determine which addressable variables may alias
2292      with P's symbol memory tag.  */
2293   for (i = 0; i < ai->num_pointers; i++)
2294     {
2295       size_t j;
2296       struct alias_map_d *p_map = ai->pointers[i];
2297       tree tag = symbol_mem_tag (p_map->var);
2298       tree var;
2299
2300       /* Call-clobbering information is not finalized yet at this point.  */
2301       if (PTR_IS_REF_ALL (p_map->var))
2302         continue;
2303
2304       for (j = 0; j < ai->num_addressable_vars; j++)
2305         {
2306           struct alias_map_d *v_map;
2307           var_ann_t v_ann;
2308           bool tag_stored_p, var_stored_p;
2309           
2310           v_map = ai->addressable_vars[j];
2311           var = v_map->var;
2312           v_ann = var_ann (var);
2313
2314           /* Skip memory tags and variables that have never been
2315              written to.  We also need to check if the variables are
2316              call-clobbered because they may be overwritten by
2317              function calls.  */
2318           tag_stored_p = pointer_set_contains (ai->written_vars, tag)
2319                          || is_call_clobbered (tag);
2320           var_stored_p = pointer_set_contains (ai->written_vars, var)
2321                          || is_call_clobbered (var);
2322           if (!tag_stored_p && !var_stored_p)
2323             continue;
2324              
2325           if (may_alias_p (p_map->var, p_map->set, var, v_map->set, false))
2326             {
2327               /* We should never have a var with subvars here, because
2328                  they shouldn't get into the set of addressable vars */
2329               gcc_assert (!var_can_have_subvars (var)
2330                           || get_subvars_for_var (var) == NULL);
2331
2332               /* Add VAR to TAG's may-aliases set.  */
2333               add_may_alias (tag, var);
2334             }
2335         }
2336     }
2337
2338   /* Since this analysis is based exclusively on symbols, it fails to
2339      handle cases where two pointers P and Q have different memory
2340      tags with conflicting alias set numbers but no aliased symbols in
2341      common.
2342
2343      For example, suppose that we have two memory tags SMT.1 and SMT.2
2344      such that
2345      
2346                 may-aliases (SMT.1) = { a }
2347                 may-aliases (SMT.2) = { b }
2348
2349      and the alias set number of SMT.1 conflicts with that of SMT.2.
2350      Since they don't have symbols in common, loads and stores from
2351      SMT.1 and SMT.2 will seem independent of each other, which will
2352      lead to the optimizers making invalid transformations (see
2353      testsuite/gcc.c-torture/execute/pr15262-[12].c).
2354
2355      To avoid this problem, we do a final traversal of AI->POINTERS
2356      looking for pairs of pointers that have no aliased symbols in
2357      common and yet have conflicting alias set numbers.  */
2358   for (i = 0; i < ai->num_pointers; i++)
2359     {
2360       size_t j;
2361       struct alias_map_d *p_map1 = ai->pointers[i];
2362       tree tag1 = symbol_mem_tag (p_map1->var);
2363       bitmap may_aliases1 = MTAG_ALIASES (tag1);
2364
2365       if (PTR_IS_REF_ALL (p_map1->var))
2366         continue;
2367
2368       for (j = i + 1; j < ai->num_pointers; j++)
2369         {
2370           struct alias_map_d *p_map2 = ai->pointers[j];
2371           tree tag2 = symbol_mem_tag (p_map2->var);
2372           bitmap may_aliases2 = may_aliases (tag2);
2373
2374           if (PTR_IS_REF_ALL (p_map2->var))
2375             continue;
2376
2377           /* If the pointers may not point to each other, do nothing.  */
2378           if (!may_alias_p (p_map1->var, p_map1->set, tag2, p_map2->set, true))
2379             continue;
2380
2381           /* The two pointers may alias each other.  If they already have
2382              symbols in common, do nothing.  */
2383           if (have_common_aliases_p (may_aliases1, may_aliases2))
2384             continue;
2385
2386           if (may_aliases2 && !bitmap_empty_p (may_aliases2))
2387             {
2388               union_alias_set_into (tag1, may_aliases2);
2389             }
2390           else
2391             {
2392               /* Since TAG2 does not have any aliases of its own, add
2393                  TAG2 itself to the alias set of TAG1.  */
2394               add_may_alias (tag1, tag2);
2395             }
2396         }
2397
2398     }
2399   timevar_pop (TV_FLOW_INSENSITIVE);
2400 }
2401
2402
2403 /* Finalize may-alias information for ref-all pointers.  Traverse all
2404    the addressable variables found in setup_pointers_and_addressables.
2405
2406    If flow-sensitive alias analysis has attached a name memory tag to
2407    a ref-all pointer, we will use it for the dereferences because that
2408    will have more precise aliasing information.  But if there is no
2409    name tag, we will use a special symbol tag that aliases all the
2410    call-clobbered addressable variables.  */
2411
2412 static void
2413 finalize_ref_all_pointers (struct alias_info *ai)
2414 {
2415   size_t i;
2416
2417   /* First add the real call-clobbered variables.  */
2418   for (i = 0; i < ai->num_addressable_vars; i++)
2419     {
2420       tree var = ai->addressable_vars[i]->var;
2421       if (is_call_clobbered (var))
2422         add_may_alias (ai->ref_all_symbol_mem_tag, var);
2423     }
2424
2425   /* Then add the call-clobbered pointer memory tags.  See
2426      compute_flow_insensitive_aliasing for the rationale.  */
2427   for (i = 0; i < ai->num_pointers; i++)
2428     {
2429       tree ptr = ai->pointers[i]->var, tag;
2430       /* Avoid adding to self and clean up.  */
2431       if (PTR_IS_REF_ALL (ptr))
2432         {
2433           struct ptr_info_def *pi = get_ptr_info (ptr);
2434           if (pi->is_dereferenced)
2435             pi->pt_anything = 0;
2436           continue;
2437         }
2438       tag = symbol_mem_tag (ptr);
2439       if (is_call_clobbered (tag))
2440         add_may_alias (ai->ref_all_symbol_mem_tag, tag);
2441     }
2442
2443 }
2444
2445
2446 /* Create a new alias set entry for VAR in AI->ADDRESSABLE_VARS.  */
2447
2448 static void
2449 create_alias_map_for (tree var, struct alias_info *ai)
2450 {
2451   struct alias_map_d *alias_map;
2452   alias_map = XCNEW (struct alias_map_d);
2453   alias_map->var = var;
2454   alias_map->set = get_alias_set (var);
2455   ai->addressable_vars[ai->num_addressable_vars++] = alias_map;
2456 }
2457
2458
2459 /* Create memory tags for all the dereferenced pointers and build the
2460    ADDRESSABLE_VARS and POINTERS arrays used for building the may-alias
2461    sets.  Based on the address escape and points-to information collected
2462    earlier, this pass will also clear the TREE_ADDRESSABLE flag from those
2463    variables whose address is not needed anymore.  */
2464
2465 static void
2466 setup_pointers_and_addressables (struct alias_info *ai)
2467 {
2468   size_t num_addressable_vars, num_pointers;
2469   referenced_var_iterator rvi;
2470   tree var;
2471   VEC (tree, heap) *varvec = NULL;
2472   safe_referenced_var_iterator srvi;
2473
2474   /* Size up the arrays ADDRESSABLE_VARS and POINTERS.  */
2475   num_addressable_vars = num_pointers = 0;
2476   
2477   FOR_EACH_REFERENCED_VAR (var, rvi)
2478     {
2479       if (may_be_aliased (var))
2480         num_addressable_vars++;
2481
2482       if (POINTER_TYPE_P (TREE_TYPE (var)))
2483         {
2484           /* Since we don't keep track of volatile variables, assume that
2485              these pointers are used in indirect store operations.  */
2486           if (TREE_THIS_VOLATILE (var))
2487             pointer_set_insert (ai->dereferenced_ptrs_store, var);
2488
2489           num_pointers++;
2490         }
2491     }
2492
2493   /* Create ADDRESSABLE_VARS and POINTERS.  Note that these arrays are
2494      always going to be slightly bigger than we actually need them
2495      because some TREE_ADDRESSABLE variables will be marked
2496      non-addressable below and only pointers with unique symbol tags are
2497      going to be added to POINTERS.  */
2498   ai->addressable_vars = XCNEWVEC (struct alias_map_d *, num_addressable_vars);
2499   ai->pointers = XCNEWVEC (struct alias_map_d *, num_pointers);
2500   ai->num_addressable_vars = 0;
2501   ai->num_pointers = 0;
2502
2503   FOR_EACH_REFERENCED_VAR_SAFE (var, varvec, srvi)
2504     {
2505       subvar_t svars;
2506
2507       /* Name memory tags already have flow-sensitive aliasing
2508          information, so they need not be processed by
2509          compute_flow_insensitive_aliasing.  Similarly, symbol memory
2510          tags are already accounted for when we process their
2511          associated pointer. 
2512       
2513          Structure fields, on the other hand, have to have some of this
2514          information processed for them, but it's pointless to mark them
2515          non-addressable (since they are fake variables anyway).  */
2516       if (MTAG_P (var) && TREE_CODE (var) != STRUCT_FIELD_TAG)
2517         continue;
2518
2519       /* Remove the ADDRESSABLE flag from every addressable variable whose
2520          address is not needed anymore.  This is caused by the propagation
2521          of ADDR_EXPR constants into INDIRECT_REF expressions and the
2522          removal of dead pointer assignments done by the early scalar
2523          cleanup passes.  */
2524       if (TREE_ADDRESSABLE (var))
2525         {
2526           if (!bitmap_bit_p (gimple_addressable_vars (cfun), DECL_UID (var))
2527               && TREE_CODE (var) != RESULT_DECL
2528               && !is_global_var (var))
2529             {
2530               bool okay_to_mark = true;
2531
2532               /* Since VAR is now a regular GIMPLE register, we will need
2533                  to rename VAR into SSA afterwards.  */
2534               mark_sym_for_renaming (var);
2535
2536               /* If VAR can have sub-variables, and any of its
2537                  sub-variables has its address taken, then we cannot
2538                  remove the addressable flag from VAR.  */
2539               if (var_can_have_subvars (var)
2540                   && (svars = get_subvars_for_var (var)))
2541                 {
2542                   subvar_t sv;
2543
2544                   for (sv = svars; sv; sv = sv->next)
2545                     {         
2546                       if (bitmap_bit_p (gimple_addressable_vars (cfun),
2547                                         DECL_UID (sv->var)))
2548                         okay_to_mark = false;
2549                       mark_sym_for_renaming (sv->var);
2550                     }
2551                 }
2552
2553               /* The address of VAR is not needed, remove the
2554                  addressable bit, so that it can be optimized as a
2555                  regular variable.  */
2556               if (okay_to_mark)
2557                 {
2558                   /* The memory partition holding VAR will no longer
2559                      contain VAR, and statements referencing it will need
2560                      to be updated.  */
2561                   if (memory_partition (var))
2562                     mark_sym_for_renaming (memory_partition (var));
2563
2564                   mark_non_addressable (var);
2565                 }
2566             }
2567         }
2568
2569       /* Global variables and addressable locals may be aliased.  Create an
2570          entry in ADDRESSABLE_VARS for VAR.  */
2571       if (may_be_aliased (var))
2572         {
2573           if (!var_can_have_subvars (var)
2574               || get_subvars_for_var (var) == NULL)
2575             create_alias_map_for (var, ai);
2576
2577           mark_sym_for_renaming (var);
2578         }
2579
2580       /* Add pointer variables that have been dereferenced to the POINTERS
2581          array and create a symbol memory tag for them.  */
2582       if (POINTER_TYPE_P (TREE_TYPE (var)))
2583         {
2584           if ((pointer_set_contains (ai->dereferenced_ptrs_store, var)
2585                || pointer_set_contains (ai->dereferenced_ptrs_load, var)))
2586             {
2587               tree tag, old_tag;
2588               var_ann_t t_ann;
2589
2590               /* If pointer VAR still doesn't have a memory tag
2591                  associated with it, create it now or re-use an
2592                  existing one.  */
2593               tag = get_smt_for (var, ai);
2594               t_ann = var_ann (tag);
2595
2596               /* The symbol tag will need to be renamed into SSA
2597                  afterwards. Note that we cannot do this inside
2598                  get_smt_for because aliasing may run multiple times
2599                  and we only create symbol tags the first time.  */
2600               mark_sym_for_renaming (tag);
2601
2602               /* Similarly, if pointer VAR used to have another type
2603                  tag, we will need to process it in the renamer to
2604                  remove the stale virtual operands.  */
2605               old_tag = symbol_mem_tag (var);
2606               if (old_tag)
2607                 mark_sym_for_renaming (old_tag);
2608
2609               /* Associate the tag with pointer VAR.  */
2610               set_symbol_mem_tag (var, tag);
2611
2612               /* If pointer VAR has been used in a store operation,
2613                  then its memory tag must be marked as written-to.  */
2614               if (pointer_set_contains (ai->dereferenced_ptrs_store, var))
2615                 pointer_set_insert (ai->written_vars, tag);
2616             }
2617           else
2618             {
2619               /* The pointer has not been dereferenced.  If it had a
2620                  symbol memory tag, remove it and mark the old tag for
2621                  renaming to remove it out of the IL.  */
2622               tree tag = symbol_mem_tag (var);
2623               if (tag)
2624                 {
2625                   mark_sym_for_renaming (tag);
2626                   set_symbol_mem_tag (var, NULL_TREE);
2627                 }
2628             }
2629         }
2630     }
2631
2632   VEC_free (tree, heap, varvec);
2633 }
2634
2635
2636 /* Determine whether to use .GLOBAL_VAR to model call clobbering
2637    semantics.  If the function makes no references to global
2638    variables and contains at least one call to a non-pure function,
2639    then we need to mark the side-effects of the call using .GLOBAL_VAR
2640    to represent all possible global memory referenced by the callee.  */
2641
2642 static void
2643 maybe_create_global_var (void)
2644 {
2645   /* No need to create it, if we have one already.  */
2646   if (gimple_global_var (cfun) == NULL_TREE)
2647     {
2648       struct mem_ref_stats_d *stats = gimple_mem_ref_stats (cfun);
2649
2650       /* Create .GLOBAL_VAR if there are no call-clobbered
2651          variables and the program contains a mixture of pure/const
2652          and regular function calls.  This is to avoid the problem
2653          described in PR 20115:
2654
2655               int X;
2656               int func_pure (void) { return X; }
2657               int func_non_pure (int a) { X += a; }
2658               int foo ()
2659               {
2660                 int a = func_pure ();
2661                 func_non_pure (a);
2662                 a = func_pure ();
2663                 return a;
2664               }
2665
2666          Since foo() has no call-clobbered variables, there is
2667          no relationship between the calls to func_pure and
2668          func_non_pure.  Since func_pure has no side-effects, value
2669          numbering optimizations elide the second call to func_pure.
2670          So, if we have some pure/const and some regular calls in the
2671          program we create .GLOBAL_VAR to avoid missing these
2672          relations.  */
2673       if (bitmap_count_bits (gimple_call_clobbered_vars (cfun)) == 0
2674           && stats->num_call_sites > 0
2675           && stats->num_pure_const_call_sites > 0
2676           && stats->num_call_sites > stats->num_pure_const_call_sites)
2677         create_global_var ();
2678     }
2679 }
2680
2681
2682 /* Return TRUE if pointer PTR may point to variable VAR.
2683    
2684    MEM_ALIAS_SET is the alias set for the memory location pointed-to by PTR
2685         This is needed because when checking for type conflicts we are
2686         interested in the alias set of the memory location pointed-to by
2687         PTR.  The alias set of PTR itself is irrelevant.
2688    
2689    VAR_ALIAS_SET is the alias set for VAR.  */
2690
2691 static bool
2692 may_alias_p (tree ptr, alias_set_type mem_alias_set,
2693              tree var, alias_set_type var_alias_set,
2694              bool alias_set_only)
2695 {
2696   tree mem;
2697
2698   alias_stats.alias_queries++;
2699   alias_stats.simple_queries++;
2700
2701   /* By convention, a variable cannot alias itself.  */
2702   mem = symbol_mem_tag (ptr);
2703   if (mem == var)
2704     {
2705       alias_stats.alias_noalias++;
2706       alias_stats.simple_resolved++;
2707       return false;
2708     }
2709
2710   /* If -fargument-noalias-global is > 2, pointer arguments may
2711      not point to anything else.  */
2712   if (flag_argument_noalias > 2 && TREE_CODE (ptr) == PARM_DECL)
2713     {
2714       alias_stats.alias_noalias++;
2715       alias_stats.simple_resolved++;
2716       return false;
2717     }
2718
2719   /* If -fargument-noalias-global is > 1, pointer arguments may
2720      not point to global variables.  */
2721   if (flag_argument_noalias > 1 && is_global_var (var)
2722       && TREE_CODE (ptr) == PARM_DECL)
2723     {
2724       alias_stats.alias_noalias++;
2725       alias_stats.simple_resolved++;
2726       return false;
2727     }
2728
2729   /* If either MEM or VAR is a read-only global and the other one
2730      isn't, then PTR cannot point to VAR.  */
2731   if ((unmodifiable_var_p (mem) && !unmodifiable_var_p (var))
2732       || (unmodifiable_var_p (var) && !unmodifiable_var_p (mem)))
2733     {
2734       alias_stats.alias_noalias++;
2735       alias_stats.simple_resolved++;
2736       return false;
2737     }
2738
2739   gcc_assert (TREE_CODE (mem) == SYMBOL_MEMORY_TAG);
2740
2741   if (!DECL_NO_TBAA_P (ptr))
2742     {
2743       alias_stats.tbaa_queries++;
2744
2745       /* If the alias sets don't conflict then MEM cannot alias VAR.  */
2746       if (!alias_sets_conflict_p (mem_alias_set, var_alias_set))
2747         {
2748           alias_stats.alias_noalias++;
2749           alias_stats.tbaa_resolved++;
2750           return false;
2751         }
2752
2753       /* If VAR is a record or union type, PTR cannot point into VAR
2754          unless there is some explicit address operation in the
2755          program that can reference a field of the type pointed-to by
2756          PTR.  This also assumes that the types of both VAR and PTR
2757          are contained within the compilation unit, and that there is
2758          no fancy addressing arithmetic associated with any of the
2759          types involved.  */
2760       if (mem_alias_set != 0 && var_alias_set != 0)
2761         {
2762           tree ptr_type = TREE_TYPE (ptr);
2763           tree var_type = TREE_TYPE (var);
2764       
2765           /* The star count is -1 if the type at the end of the
2766              pointer_to chain is not a record or union type. */ 
2767           if ((!alias_set_only) && 
2768               ipa_type_escape_star_count_of_interesting_type (var_type) >= 0)
2769             {
2770               int ptr_star_count = 0;
2771           
2772               /* ipa_type_escape_star_count_of_interesting_type is a
2773                  little too restrictive for the pointer type, need to
2774                  allow pointers to primitive types as long as those
2775                  types cannot be pointers to everything.  */
2776               while (POINTER_TYPE_P (ptr_type))
2777                 {
2778                   /* Strip the *s off.  */ 
2779                   ptr_type = TREE_TYPE (ptr_type);
2780                   ptr_star_count++;
2781                 }
2782           
2783               /* There does not appear to be a better test to see if
2784                  the pointer type was one of the pointer to everything
2785                  types.  */
2786               if (ptr_star_count > 0)
2787                 {
2788                   alias_stats.structnoaddress_queries++;
2789                   if (ipa_type_escape_field_does_not_clobber_p (var_type, 
2790                                                                 TREE_TYPE (ptr)))
2791                     {
2792                       alias_stats.structnoaddress_resolved++;
2793                       alias_stats.alias_noalias++;
2794                       return false;
2795                     }
2796                 }
2797               else if (ptr_star_count == 0)
2798                 {
2799                   /* If PTR_TYPE was not really a pointer to type, it cannot 
2800                      alias.  */ 
2801                   alias_stats.structnoaddress_queries++;
2802                   alias_stats.structnoaddress_resolved++;
2803                   alias_stats.alias_noalias++;
2804                   return false;
2805                 }
2806             }
2807         }
2808     }
2809
2810   alias_stats.alias_mayalias++;
2811   return true;
2812 }
2813
2814
2815 /* Add ALIAS to the set of variables that may alias VAR.  */
2816
2817 static void
2818 add_may_alias (tree var, tree alias)
2819 {
2820   /* Don't allow self-referential aliases.  */
2821   gcc_assert (var != alias);
2822
2823   /* ALIAS must be addressable if it's being added to an alias set.  */
2824 #if 1
2825   TREE_ADDRESSABLE (alias) = 1;
2826 #else
2827   gcc_assert (may_be_aliased (alias));
2828 #endif
2829
2830   /* VAR must be a symbol or a name tag.  */
2831   gcc_assert (TREE_CODE (var) == SYMBOL_MEMORY_TAG
2832               || TREE_CODE (var) == NAME_MEMORY_TAG);
2833
2834   if (MTAG_ALIASES (var) == NULL)
2835     MTAG_ALIASES (var) = BITMAP_ALLOC (&alias_bitmap_obstack);
2836   
2837   bitmap_set_bit (MTAG_ALIASES (var), DECL_UID (alias));
2838 }
2839
2840
2841 /* Mark pointer PTR as pointing to an arbitrary memory location.  */
2842
2843 static void
2844 set_pt_anything (tree ptr)
2845 {
2846   struct ptr_info_def *pi = get_ptr_info (ptr);
2847
2848   pi->pt_anything = 1;
2849   pi->pt_vars = NULL;
2850
2851   /* The pointer used to have a name tag, but we now found it pointing
2852      to an arbitrary location.  The name tag needs to be renamed and
2853      disassociated from PTR.  */
2854   if (pi->name_mem_tag)
2855     {
2856       mark_sym_for_renaming (pi->name_mem_tag);
2857       pi->name_mem_tag = NULL_TREE;
2858     }
2859 }
2860
2861
2862 /* Return true if STMT is an "escape" site from the current function.  Escape
2863    sites those statements which might expose the address of a variable
2864    outside the current function.  STMT is an escape site iff:
2865
2866         1- STMT is a function call, or
2867         2- STMT is an __asm__ expression, or
2868         3- STMT is an assignment to a non-local variable, or
2869         4- STMT is a return statement.
2870
2871    Return the type of escape site found, if we found one, or NO_ESCAPE
2872    if none.  */
2873
2874 enum escape_type
2875 is_escape_site (tree stmt)
2876 {
2877   tree call = get_call_expr_in (stmt);
2878   if (call != NULL_TREE)
2879     {
2880       if (!TREE_SIDE_EFFECTS (call))
2881         return ESCAPE_TO_PURE_CONST;
2882
2883       return ESCAPE_TO_CALL;
2884     }
2885   else if (TREE_CODE (stmt) == ASM_EXPR)
2886     return ESCAPE_TO_ASM;
2887   else if (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT)
2888     {
2889       tree lhs = GIMPLE_STMT_OPERAND (stmt, 0);
2890
2891       /* Get to the base of _REF nodes.  */
2892       if (TREE_CODE (lhs) != SSA_NAME)
2893         lhs = get_base_address (lhs);
2894
2895       /* If we couldn't recognize the LHS of the assignment, assume that it
2896          is a non-local store.  */
2897       if (lhs == NULL_TREE)
2898         return ESCAPE_UNKNOWN;
2899
2900       if (TREE_CODE (GIMPLE_STMT_OPERAND (stmt, 1)) == NOP_EXPR
2901           || TREE_CODE (GIMPLE_STMT_OPERAND (stmt, 1)) == CONVERT_EXPR
2902           || TREE_CODE (GIMPLE_STMT_OPERAND (stmt, 1)) == VIEW_CONVERT_EXPR)
2903         {
2904           tree from
2905             = TREE_TYPE (TREE_OPERAND (GIMPLE_STMT_OPERAND (stmt, 1), 0));
2906           tree to = TREE_TYPE (GIMPLE_STMT_OPERAND (stmt, 1));
2907
2908           /* If the RHS is a conversion between a pointer and an integer, the
2909              pointer escapes since we can't track the integer.  */
2910           if (POINTER_TYPE_P (from) && !POINTER_TYPE_P (to))
2911             return ESCAPE_BAD_CAST;
2912
2913           /* Same if the RHS is a conversion between a regular pointer and a
2914              ref-all pointer since we can't track the SMT of the former.  */
2915           if (POINTER_TYPE_P (from) && !TYPE_REF_CAN_ALIAS_ALL (from)
2916               && POINTER_TYPE_P (to) && TYPE_REF_CAN_ALIAS_ALL (to))
2917             return ESCAPE_BAD_CAST;
2918         }
2919
2920       /* If the LHS is an SSA name, it can't possibly represent a non-local
2921          memory store.  */
2922       if (TREE_CODE (lhs) == SSA_NAME)
2923         return NO_ESCAPE;
2924
2925       /* FIXME: LHS is not an SSA_NAME.  Even if it's an assignment to a
2926          local variables we cannot be sure if it will escape, because we
2927          don't have information about objects not in SSA form.  Need to
2928          implement something along the lines of
2929
2930          J.-D. Choi, M. Gupta, M. J. Serrano, V. C. Sreedhar, and S. P.
2931          Midkiff, ``Escape analysis for java,'' in Proceedings of the
2932          Conference on Object-Oriented Programming Systems, Languages, and
2933          Applications (OOPSLA), pp. 1-19, 1999.  */
2934       return ESCAPE_STORED_IN_GLOBAL;
2935     }
2936   else if (TREE_CODE (stmt) == RETURN_EXPR)
2937     return ESCAPE_TO_RETURN;
2938
2939   return NO_ESCAPE;
2940 }
2941
2942 /* Create a new memory tag of type TYPE.
2943    Does NOT push it into the current binding.  */
2944
2945 tree
2946 create_tag_raw (enum tree_code code, tree type, const char *prefix)
2947 {
2948   tree tmp_var;
2949
2950   tmp_var = build_decl (code, create_tmp_var_name (prefix), type);
2951
2952   /* Make the variable writable.  */
2953   TREE_READONLY (tmp_var) = 0;
2954
2955   /* It doesn't start out global.  */
2956   MTAG_GLOBAL (tmp_var) = 0;
2957   TREE_STATIC (tmp_var) = 0;
2958   TREE_USED (tmp_var) = 1;
2959
2960   return tmp_var;
2961 }
2962
2963 /* Create a new memory tag of type TYPE.  If IS_TYPE_TAG is true, the tag
2964    is considered to represent all the pointers whose pointed-to types are
2965    in the same alias set class.  Otherwise, the tag represents a single
2966    SSA_NAME pointer variable.  */
2967
2968 static tree
2969 create_memory_tag (tree type, bool is_type_tag)
2970 {
2971   tree tag = create_tag_raw (is_type_tag ? SYMBOL_MEMORY_TAG : NAME_MEMORY_TAG,
2972                              type, (is_type_tag) ? "SMT" : "NMT");
2973
2974   /* By default, memory tags are local variables.  Alias analysis will
2975      determine whether they should be considered globals.  */
2976   DECL_CONTEXT (tag) = current_function_decl;
2977
2978   /* Memory tags are by definition addressable.  */
2979   TREE_ADDRESSABLE (tag) = 1;
2980
2981   set_symbol_mem_tag (tag, NULL_TREE);
2982
2983   /* Add the tag to the symbol table.  */
2984   add_referenced_var (tag);
2985
2986   return tag;
2987 }
2988
2989
2990 /* Create a name memory tag to represent a specific SSA_NAME pointer P_i.
2991    This is used if P_i has been found to point to a specific set of
2992    variables or to a non-aliased memory location like the address returned
2993    by malloc functions.  */
2994
2995 static tree
2996 get_nmt_for (tree ptr)
2997 {
2998   struct ptr_info_def *pi = get_ptr_info (ptr);
2999   tree tag = pi->name_mem_tag;
3000
3001   if (tag == NULL_TREE)
3002     tag = create_memory_tag (TREE_TYPE (TREE_TYPE (ptr)), false);
3003   return tag;
3004 }
3005
3006
3007 /* Return the symbol memory tag associated to pointer PTR.  A memory
3008    tag is an artificial variable that represents the memory location
3009    pointed-to by PTR.  It is used to model the effects of pointer
3010    de-references on addressable variables.
3011    
3012    AI points to the data gathered during alias analysis.  This
3013    function populates the array AI->POINTERS.  */
3014
3015 static tree
3016 get_smt_for (tree ptr, struct alias_info *ai)
3017 {
3018   size_t i;
3019   tree tag;
3020   tree tag_type = TREE_TYPE (TREE_TYPE (ptr));
3021   alias_set_type tag_set = get_alias_set (tag_type);
3022
3023   /* We use a unique memory tag for all the ref-all pointers.  */
3024   if (PTR_IS_REF_ALL (ptr))
3025     {
3026       if (!ai->ref_all_symbol_mem_tag)
3027         ai->ref_all_symbol_mem_tag = create_memory_tag (void_type_node, true);
3028       return ai->ref_all_symbol_mem_tag;
3029     }
3030
3031   /* To avoid creating unnecessary memory tags, only create one memory tag
3032      per alias set class.  Note that it may be tempting to group
3033      memory tags based on conflicting alias sets instead of
3034      equivalence.  That would be wrong because alias sets are not
3035      necessarily transitive (as demonstrated by the libstdc++ test
3036      23_containers/vector/cons/4.cc).  Given three alias sets A, B, C
3037      such that conflicts (A, B) == true and conflicts (A, C) == true,
3038      it does not necessarily follow that conflicts (B, C) == true.  */
3039   for (i = 0, tag = NULL_TREE; i < ai->num_pointers; i++)
3040     {
3041       struct alias_map_d *curr = ai->pointers[i];
3042       tree curr_tag = symbol_mem_tag (curr->var);
3043       if (tag_set == curr->set)
3044         {
3045           tag = curr_tag;
3046           break;
3047         }
3048     }
3049
3050   /* If VAR cannot alias with any of the existing memory tags, create a new
3051      tag for PTR and add it to the POINTERS array.  */
3052   if (tag == NULL_TREE)
3053     {
3054       struct alias_map_d *alias_map;
3055
3056       /* If PTR did not have a symbol tag already, create a new SMT.*
3057          artificial variable representing the memory location
3058          pointed-to by PTR.  */
3059       tag = symbol_mem_tag (ptr);
3060       if (tag == NULL_TREE)
3061         tag = create_memory_tag (tag_type, true);
3062
3063       /* Add PTR to the POINTERS array.  Note that we are not interested in
3064          PTR's alias set.  Instead, we cache the alias set for the memory that
3065          PTR points to.  */
3066       alias_map = XCNEW (struct alias_map_d);
3067       alias_map->var = ptr;
3068       alias_map->set = tag_set;
3069       ai->pointers[ai->num_pointers++] = alias_map;
3070     }
3071
3072   /* If the pointed-to type is volatile, so is the tag.  */
3073   TREE_THIS_VOLATILE (tag) |= TREE_THIS_VOLATILE (tag_type);
3074
3075   /* Make sure that the symbol tag has the same alias set as the
3076      pointed-to type.  */
3077   gcc_assert (tag_set == get_alias_set (tag));
3078
3079   return tag;
3080 }
3081
3082
3083 /* Create GLOBAL_VAR, an artificial global variable to act as a
3084    representative of all the variables that may be clobbered by function
3085    calls.  */
3086
3087 static void
3088 create_global_var (void)
3089 {
3090   tree global_var = build_decl (VAR_DECL, get_identifier (".GLOBAL_VAR"),
3091                                 void_type_node);
3092   DECL_ARTIFICIAL (global_var) = 1;
3093   TREE_READONLY (global_var) = 0;
3094   DECL_EXTERNAL (global_var) = 1;
3095   TREE_STATIC (global_var) = 1;
3096   TREE_USED (global_var) = 1;
3097   DECL_CONTEXT (global_var) = NULL_TREE;
3098   TREE_THIS_VOLATILE (global_var) = 0;
3099   TREE_ADDRESSABLE (global_var) = 0;
3100
3101   create_var_ann (global_var);
3102   mark_call_clobbered (global_var, ESCAPE_UNKNOWN);
3103   add_referenced_var (global_var);
3104   mark_sym_for_renaming (global_var);
3105   cfun->gimple_df->global_var = global_var;
3106 }
3107
3108
3109 /* Dump alias statistics on FILE.  */
3110
3111 static void 
3112 dump_alias_stats (FILE *file)
3113 {
3114   const char *funcname
3115     = lang_hooks.decl_printable_name (current_function_decl, 2);
3116   fprintf (file, "\nAlias statistics for %s\n\n", funcname);
3117   fprintf (file, "Total alias queries:\t%u\n", alias_stats.alias_queries);
3118   fprintf (file, "Total alias mayalias results:\t%u\n", 
3119            alias_stats.alias_mayalias);
3120   fprintf (file, "Total alias noalias results:\t%u\n",
3121            alias_stats.alias_noalias);
3122   fprintf (file, "Total simple queries:\t%u\n",
3123            alias_stats.simple_queries);
3124   fprintf (file, "Total simple resolved:\t%u\n",
3125            alias_stats.simple_resolved);
3126   fprintf (file, "Total TBAA queries:\t%u\n",
3127            alias_stats.tbaa_queries);
3128   fprintf (file, "Total TBAA resolved:\t%u\n",
3129            alias_stats.tbaa_resolved);
3130   fprintf (file, "Total non-addressable structure type queries:\t%u\n",
3131            alias_stats.structnoaddress_queries);
3132   fprintf (file, "Total non-addressable structure type resolved:\t%u\n",
3133            alias_stats.structnoaddress_resolved);
3134 }
3135   
3136
3137 /* Dump alias information on FILE.  */
3138
3139 void
3140 dump_alias_info (FILE *file)
3141 {
3142   size_t i;
3143   const char *funcname
3144     = lang_hooks.decl_printable_name (current_function_decl, 2);
3145   referenced_var_iterator rvi;
3146   tree var;
3147
3148   fprintf (file, "\nAlias information for %s\n\n", funcname);
3149
3150   dump_memory_partitions (file);
3151
3152   fprintf (file, "\nFlow-insensitive alias information for %s\n\n", funcname);
3153
3154   fprintf (file, "Aliased symbols\n\n");
3155   
3156   FOR_EACH_REFERENCED_VAR (var, rvi)
3157     {
3158       if (may_be_aliased (var))
3159         dump_variable (file, var);
3160     }
3161
3162   fprintf (file, "\nDereferenced pointers\n\n");
3163
3164   FOR_EACH_REFERENCED_VAR (var, rvi)
3165     if (symbol_mem_tag (var))
3166       dump_variable (file, var);
3167
3168   fprintf (file, "\nSymbol memory tags\n\n");
3169   
3170   FOR_EACH_REFERENCED_VAR (var, rvi)
3171     {
3172       if (TREE_CODE (var) == SYMBOL_MEMORY_TAG)
3173         dump_variable (file, var);
3174     }
3175
3176   fprintf (file, "\n\nFlow-sensitive alias information for %s\n\n", funcname);
3177
3178   fprintf (file, "SSA_NAME pointers\n\n");
3179   for (i = 1; i < num_ssa_names; i++)
3180     {
3181       tree ptr = ssa_name (i);
3182       struct ptr_info_def *pi;
3183       
3184       if (ptr == NULL_TREE)
3185         continue;
3186
3187       pi = SSA_NAME_PTR_INFO (ptr);
3188       if (!SSA_NAME_IN_FREE_LIST (ptr)
3189           && pi
3190           && pi->name_mem_tag)
3191         dump_points_to_info_for (file, ptr);
3192     }
3193
3194   fprintf (file, "\nName memory tags\n\n");
3195   
3196   FOR_EACH_REFERENCED_VAR (var, rvi)
3197     {
3198       if (TREE_CODE (var) == NAME_MEMORY_TAG)
3199         dump_variable (file, var);
3200     }
3201
3202   fprintf (file, "\n");
3203 }
3204
3205
3206 /* Dump alias information on stderr.  */
3207
3208 void
3209 debug_alias_info (void)
3210 {
3211   dump_alias_info (stderr);
3212 }
3213
3214
3215 /* Return the alias information associated with pointer T.  It creates a
3216    new instance if none existed.  */
3217
3218 struct ptr_info_def *
3219 get_ptr_info (tree t)
3220 {
3221   struct ptr_info_def *pi;
3222
3223   gcc_assert (POINTER_TYPE_P (TREE_TYPE (t)));
3224
3225   pi = SSA_NAME_PTR_INFO (t);
3226   if (pi == NULL)
3227     {
3228       pi = GGC_CNEW (struct ptr_info_def);
3229       SSA_NAME_PTR_INFO (t) = pi;
3230     }
3231
3232   return pi;
3233 }
3234
3235
3236 /* Dump points-to information for SSA_NAME PTR into FILE.  */
3237
3238 void
3239 dump_points_to_info_for (FILE *file, tree ptr)
3240 {
3241   struct ptr_info_def *pi = SSA_NAME_PTR_INFO (ptr);
3242
3243   print_generic_expr (file, ptr, dump_flags);
3244
3245   if (pi)
3246     {
3247       if (pi->name_mem_tag)
3248         {
3249           fprintf (file, ", name memory tag: ");
3250           print_generic_expr (file, pi->name_mem_tag, dump_flags);
3251         }
3252
3253       if (pi->is_dereferenced)
3254         fprintf (file, ", is dereferenced");
3255
3256       if (pi->value_escapes_p)
3257         fprintf (file, ", its value escapes");
3258
3259       if (pi->pt_anything)
3260         fprintf (file, ", points-to anything");
3261
3262       if (pi->pt_null)
3263         fprintf (file, ", points-to NULL");
3264
3265       if (pi->pt_vars)
3266         {
3267           fprintf (file, ", points-to vars: ");
3268           dump_decl_set (file, pi->pt_vars);
3269         }
3270     }
3271
3272   fprintf (file, "\n");
3273 }
3274
3275
3276 /* Dump points-to information for VAR into stderr.  */
3277
3278 void
3279 debug_points_to_info_for (tree var)
3280 {
3281   dump_points_to_info_for (stderr, var);
3282 }
3283
3284
3285 /* Dump points-to information into FILE.  NOTE: This function is slow, as
3286    it needs to traverse the whole CFG looking for pointer SSA_NAMEs.  */
3287
3288 void
3289 dump_points_to_info (FILE *file)
3290 {
3291   basic_block bb;
3292   block_stmt_iterator si;
3293   ssa_op_iter iter;
3294   const char *fname =
3295     lang_hooks.decl_printable_name (current_function_decl, 2);
3296   referenced_var_iterator rvi;
3297   tree var;
3298
3299   fprintf (file, "\n\nPointed-to sets for pointers in %s\n\n", fname);
3300
3301   /* First dump points-to information for the default definitions of
3302      pointer variables.  This is necessary because default definitions are
3303      not part of the code.  */
3304   FOR_EACH_REFERENCED_VAR (var, rvi)
3305     {
3306       if (POINTER_TYPE_P (TREE_TYPE (var)))
3307         {
3308           tree def = gimple_default_def (cfun, var);
3309           if (def)
3310             dump_points_to_info_for (file, def);
3311         }
3312     }
3313
3314   /* Dump points-to information for every pointer defined in the program.  */
3315   FOR_EACH_BB (bb)
3316     {
3317       tree phi;
3318
3319       for (phi = phi_nodes (bb); phi; phi = PHI_CHAIN (phi))
3320         {
3321           tree ptr = PHI_RESULT (phi);
3322           if (POINTER_TYPE_P (TREE_TYPE (ptr)))
3323             dump_points_to_info_for (file, ptr);
3324         }
3325
3326         for (si = bsi_start (bb); !bsi_end_p (si); bsi_next (&si))
3327           {
3328             tree stmt = bsi_stmt (si);
3329             tree def;
3330             FOR_EACH_SSA_TREE_OPERAND (def, stmt, iter, SSA_OP_DEF)
3331               if (TREE_CODE (def) == SSA_NAME
3332                   && POINTER_TYPE_P (TREE_TYPE (def)))
3333                 dump_points_to_info_for (file, def);
3334           }
3335     }
3336
3337   fprintf (file, "\n");
3338 }
3339
3340
3341 /* Dump points-to info pointed to by PTO into STDERR.  */
3342
3343 void
3344 debug_points_to_info (void)
3345 {
3346   dump_points_to_info (stderr);
3347 }
3348
3349 /* Dump to FILE the list of variables that may be aliasing VAR.  */
3350
3351 void
3352 dump_may_aliases_for (FILE *file, tree var)
3353 {
3354   bitmap aliases;
3355   
3356   aliases = MTAG_ALIASES (var);
3357   if (aliases)
3358     {
3359       bitmap_iterator bi;
3360       unsigned int i;
3361       tree al;
3362
3363       fprintf (file, "{ ");
3364       EXECUTE_IF_SET_IN_BITMAP (aliases, 0, i, bi)
3365         {
3366           al = referenced_var (i);
3367           print_generic_expr (file, al, dump_flags);
3368           fprintf (file, " ");
3369         }
3370       fprintf (file, "}");
3371     }
3372 }
3373
3374
3375 /* Dump to stderr the list of variables that may be aliasing VAR.  */
3376
3377 void
3378 debug_may_aliases_for (tree var)
3379 {
3380   dump_may_aliases_for (stderr, var);
3381 }
3382
3383
3384 /* Return true if VAR may be aliased.  */
3385
3386 bool
3387 may_be_aliased (tree var)
3388 {
3389   /* Obviously.  */
3390   if (TREE_ADDRESSABLE (var))
3391     return true;
3392
3393   /* Globally visible variables can have their addresses taken by other
3394      translation units.  */
3395   if (MTAG_P (var)
3396       && (MTAG_GLOBAL (var) || TREE_PUBLIC (var)))
3397     return true;
3398   else if (!MTAG_P (var)
3399            && (DECL_EXTERNAL (var) || TREE_PUBLIC (var)))
3400     return true;
3401
3402   /* Automatic variables can't have their addresses escape any other
3403      way.  This must be after the check for global variables, as
3404      extern declarations do not have TREE_STATIC set.  */
3405   if (!TREE_STATIC (var))
3406     return false;
3407
3408   /* If we're in unit-at-a-time mode, then we must have seen all
3409      occurrences of address-of operators, and so we can trust
3410      TREE_ADDRESSABLE.  Otherwise we can only be sure the variable
3411      isn't addressable if it's local to the current function.  */
3412   if (flag_unit_at_a_time)
3413     return false;
3414
3415   if (decl_function_context (var) == current_function_decl)
3416     return false;
3417
3418   return true;
3419 }
3420
3421 /* The following is based on code in add_stmt_operand to ensure that the
3422    same defs/uses/vdefs/vuses will be found after replacing a reference
3423    to var (or ARRAY_REF to var) with an INDIRECT_REF to ptr whose value
3424    is the address of var.  Return a memtag for the ptr, after adding the 
3425    proper may_aliases to it (which are the aliases of var, if it has any,
3426    or var itself).  */
3427
3428 static tree
3429 add_may_alias_for_new_tag (tree tag, tree var)
3430 {
3431   bitmap aliases = NULL;
3432   
3433   if (MTAG_P (var))
3434     aliases = may_aliases (var);
3435
3436   /* Case 1: |aliases| == 1  */
3437   if (aliases && bitmap_count_bits (aliases) == 1)
3438     {
3439       tree ali = referenced_var (bitmap_first_set_bit (aliases));
3440       if (TREE_CODE (ali) == SYMBOL_MEMORY_TAG)
3441         return ali;
3442     }
3443
3444   /* Case 2: |aliases| == 0  */
3445   if (aliases == NULL)
3446     add_may_alias (tag, var);
3447   else
3448     {
3449       /* Case 3: |aliases| > 1  */
3450       union_alias_set_into (tag, aliases);
3451     }
3452   return tag;
3453 }
3454
3455 /* Create a new symbol tag for PTR.  Construct the may-alias list of this type
3456    tag so that it has the aliasing of VAR, or of the relevant subvars of VAR
3457    according to the location accessed by EXPR.
3458
3459    Note, the set of aliases represented by the new symbol tag are not marked
3460    for renaming.  */
3461
3462 void
3463 new_type_alias (tree ptr, tree var, tree expr)
3464 {
3465   tree tag_type = TREE_TYPE (TREE_TYPE (ptr));
3466   tree tag;
3467   subvar_t svars;
3468   tree ali = NULL_TREE;
3469   HOST_WIDE_INT offset, size, maxsize;
3470   tree ref;
3471   VEC (tree, heap) *overlaps = NULL;
3472   subvar_t sv;
3473   unsigned int len;
3474
3475   gcc_assert (symbol_mem_tag (ptr) == NULL_TREE);
3476   gcc_assert (!MTAG_P (var));
3477
3478   ref = get_ref_base_and_extent (expr, &offset, &size, &maxsize);
3479   gcc_assert (ref);
3480
3481   tag = create_memory_tag (tag_type, true);
3482   set_symbol_mem_tag (ptr, tag);
3483
3484   /* Add VAR to the may-alias set of PTR's new symbol tag.  If VAR has
3485      subvars, add the subvars to the tag instead of the actual var.  */
3486   if (var_can_have_subvars (ref)
3487       && (svars = get_subvars_for_var (ref)))
3488     {
3489       for (sv = svars; sv; sv = sv->next)
3490         {
3491           bool exact;
3492
3493           if (overlap_subvar (offset, maxsize, sv->var, &exact))
3494             VEC_safe_push (tree, heap, overlaps, sv->var);
3495         }
3496       gcc_assert (overlaps != NULL);
3497     }
3498   else if (var_can_have_subvars (var)
3499            && (svars = get_subvars_for_var (var)))
3500     {
3501       /* If the REF is not a direct access to VAR (e.g., it is a dereference
3502          of a pointer), we should scan the virtual operands of REF the same
3503          way as tree-ssa-operands do.  At the moment, this is somewhat
3504          difficult, so we just give up and add all the subvars of VAR.
3505          On mem-ssa branch, the scanning for virtual operands have been
3506          split from the rest of tree-ssa-operands, so it should be much
3507          easier to fix this problem correctly once mem-ssa is merged.  */
3508       for (sv = svars; sv; sv = sv->next)
3509         VEC_safe_push (tree, heap, overlaps, sv->var);
3510
3511       gcc_assert (overlaps != NULL);
3512     }
3513   else
3514     ali = add_may_alias_for_new_tag (tag, var);
3515
3516   len = VEC_length (tree, overlaps);
3517   if (len > 0)
3518     {
3519       if (dump_file && (dump_flags & TDF_DETAILS))
3520         fprintf (dump_file, "\nnumber of overlapping subvars = %u\n", len);
3521
3522       if (len == 1)
3523         ali = add_may_alias_for_new_tag (tag, VEC_index (tree, overlaps, 0));
3524       else if (len > 1)
3525         {
3526           unsigned int k;
3527           tree sv_var;
3528
3529           for (k = 0; VEC_iterate (tree, overlaps, k, sv_var); k++)
3530             {
3531               ali = add_may_alias_for_new_tag (tag, sv_var);
3532
3533               if (ali != tag)
3534                 {
3535                   /* Can happen only if 'Case 1' of add_may_alias_for_new_tag
3536                      took place.  Since more than one svar was found, we add 
3537                      'ali' as one of the may_aliases of the new tag.  */ 
3538                   add_may_alias (tag, ali);
3539                   ali = tag;
3540                 }
3541             }
3542         }
3543       VEC_free (tree, heap, overlaps);
3544     }
3545
3546   set_symbol_mem_tag (ptr, ali);
3547   TREE_READONLY (tag) = TREE_READONLY (var);
3548   MTAG_GLOBAL (tag) = is_global_var (var);
3549 }
3550
3551 /* This represents the used range of a variable.  */
3552
3553 typedef struct used_part
3554 {
3555   HOST_WIDE_INT minused;
3556   HOST_WIDE_INT maxused;
3557   /* True if we have an explicit use/def of some portion of this variable,
3558      even if it is all of it. i.e. a.b = 5 or temp = a.b.  */
3559   bool explicit_uses;
3560   /* True if we have an implicit use/def of some portion of this
3561      variable.  Implicit uses occur when we can't tell what part we
3562      are referencing, and have to make conservative assumptions.  */
3563   bool implicit_uses;
3564   /* True if the structure is only written to or taken its address.  */
3565   bool write_only;
3566 } *used_part_t;
3567
3568 /* An array of used_part structures, indexed by variable uid.  */
3569
3570 static htab_t used_portions;
3571
3572 struct used_part_map
3573 {
3574   unsigned int uid;
3575   used_part_t to;
3576 };
3577
3578 /* Return true if the uid in the two used part maps are equal.  */
3579
3580 static int
3581 used_part_map_eq (const void *va, const void *vb)
3582 {
3583   const struct used_part_map *a = (const struct used_part_map *) va;
3584   const struct used_part_map *b = (const struct used_part_map *) vb;
3585   return (a->uid == b->uid);
3586 }
3587
3588 /* Hash a from uid in a used_part_map.  */
3589
3590 static unsigned int
3591 used_part_map_hash (const void *item)
3592 {
3593   return ((const struct used_part_map *)item)->uid;
3594 }
3595
3596 /* Free a used part map element.  */
3597
3598 static void 
3599 free_used_part_map (void *item)
3600 {
3601   free (((struct used_part_map *)item)->to);
3602   free (item);
3603 }
3604
3605 /* Lookup a used_part structure for a UID.  */
3606
3607 static used_part_t
3608 up_lookup (unsigned int uid)
3609 {
3610   struct used_part_map *h, in;
3611   in.uid = uid;
3612   h = (struct used_part_map *) htab_find_with_hash (used_portions, &in, uid);
3613   if (!h)
3614     return NULL;
3615   return h->to;
3616 }
3617
3618 /* Insert the pair UID, TO into the used part hashtable.  */
3619  
3620 static void 
3621 up_insert (unsigned int uid, used_part_t to)
3622
3623   struct used_part_map *h;
3624   void **loc;
3625
3626   h = XNEW (struct used_part_map);
3627   h->uid = uid;
3628   h->to = to;
3629   loc = htab_find_slot_with_hash (used_portions, h,
3630                                   uid, INSERT);
3631   if (*loc != NULL)
3632     free (*loc);
3633   *(struct used_part_map **)  loc = h;
3634 }
3635
3636
3637 /* Given a variable uid, UID, get or create the entry in the used portions
3638    table for the variable.  */
3639
3640 static used_part_t
3641 get_or_create_used_part_for (size_t uid)
3642 {
3643   used_part_t up;
3644   if ((up = up_lookup (uid)) == NULL)
3645     {
3646       up = XCNEW (struct used_part);
3647       up->minused = INT_MAX;
3648       up->maxused = 0;
3649       up->explicit_uses = false;
3650       up->implicit_uses = false;
3651       up->write_only = true;
3652     }
3653
3654   return up;
3655 }
3656
3657
3658 /* Create and return a structure sub-variable for field type FIELD at
3659    offset OFFSET, with size SIZE, of variable VAR.  If ALIAS_SET not
3660    -1 this field is non-addressable and we should use this alias set
3661    with this field.  */
3662
3663 static tree
3664 create_sft (tree var, tree field, unsigned HOST_WIDE_INT offset,
3665             unsigned HOST_WIDE_INT size, alias_set_type alias_set)
3666 {
3667   tree subvar = create_tag_raw (STRUCT_FIELD_TAG, field, "SFT");
3668
3669   /* We need to copy the various flags from VAR to SUBVAR, so that
3670      they are is_global_var iff the original variable was.  */
3671   DECL_CONTEXT (subvar) = DECL_CONTEXT (var);
3672   MTAG_GLOBAL (subvar) = DECL_EXTERNAL (var);
3673   TREE_PUBLIC  (subvar) = TREE_PUBLIC (var);
3674   TREE_STATIC (subvar) = TREE_STATIC (var);
3675   TREE_READONLY (subvar) = TREE_READONLY (var);
3676   TREE_ADDRESSABLE (subvar) = TREE_ADDRESSABLE (var);
3677
3678   /* Add the new variable to REFERENCED_VARS.  */
3679   set_symbol_mem_tag (subvar, NULL);
3680   add_referenced_var (subvar);
3681   SFT_PARENT_VAR (subvar) = var;
3682   SFT_OFFSET (subvar) = offset;
3683   SFT_SIZE (subvar) = size;
3684   SFT_ALIAS_SET (subvar) = alias_set;
3685   return subvar;
3686 }
3687
3688
3689 /* Given an aggregate VAR, create the subvariables that represent its
3690    fields.  */
3691
3692 static void
3693 create_overlap_variables_for (tree var)
3694 {
3695   VEC(fieldoff_s,heap) *fieldstack = NULL;
3696   used_part_t up;
3697   size_t uid = DECL_UID (var);
3698
3699   up = up_lookup (uid);
3700   if (!up
3701       || up->write_only)
3702     return;
3703
3704   push_fields_onto_fieldstack (TREE_TYPE (var), &fieldstack, 0, NULL,
3705                                TREE_TYPE (var));
3706   if (VEC_length (fieldoff_s, fieldstack) != 0)
3707     {
3708       subvar_t *subvars;
3709       fieldoff_s *fo;
3710       bool notokay = false;
3711       int fieldcount = 0;
3712       int i;
3713       HOST_WIDE_INT lastfooffset = -1;
3714       HOST_WIDE_INT lastfosize = -1;
3715       tree lastfotype = NULL_TREE;
3716
3717       /* Not all fields have DECL_SIZE set, and those that don't, we don't
3718          know their size, and thus, can't handle.
3719          The same is true of fields with DECL_SIZE that is not an integer
3720          constant (such as variable sized fields).
3721          Fields with offsets which are not constant will have an offset < 0 
3722          We *could* handle fields that are constant sized arrays, but
3723          currently don't.  Doing so would require some extra changes to
3724          tree-ssa-operands.c.  */
3725
3726       for (i = 0; VEC_iterate (fieldoff_s, fieldstack, i, fo); i++)
3727         {
3728           if (!fo->size
3729               || TREE_CODE (fo->size) != INTEGER_CST
3730               || fo->offset < 0)
3731             {
3732               notokay = true;
3733               break;
3734             }
3735           fieldcount++;
3736         }
3737
3738       /* The current heuristic we use is as follows:
3739          If the variable has no used portions in this function, no
3740          structure vars are created for it.
3741          Otherwise,
3742          If the variable has less than SALIAS_MAX_IMPLICIT_FIELDS,
3743          we always create structure vars for them.
3744          If the variable has more than SALIAS_MAX_IMPLICIT_FIELDS, and
3745          some explicit uses, we create structure vars for them.
3746          If the variable has more than SALIAS_MAX_IMPLICIT_FIELDS, and
3747          no explicit uses, we do not create structure vars for them.
3748       */
3749       
3750       if (fieldcount >= SALIAS_MAX_IMPLICIT_FIELDS
3751           && !up->explicit_uses)
3752         {
3753           if (dump_file && (dump_flags & TDF_DETAILS))
3754             {
3755               fprintf (dump_file, "Variable ");
3756               print_generic_expr (dump_file, var, 0);
3757               fprintf (dump_file, " has no explicit uses in this function, and is > SALIAS_MAX_IMPLICIT_FIELDS, so skipping\n");
3758             }
3759           notokay = true;
3760         }
3761       
3762       /* Bail out, if we can't create overlap variables.  */
3763       if (notokay)
3764         {
3765           VEC_free (fieldoff_s, heap, fieldstack);
3766           return;
3767         }
3768       
3769       /* Otherwise, create the variables.  */
3770       subvars = lookup_subvars_for_var (var);
3771       
3772       sort_fieldstack (fieldstack);
3773
3774       for (i = VEC_length (fieldoff_s, fieldstack);
3775            VEC_iterate (fieldoff_s, fieldstack, --i, fo);)
3776         {
3777           subvar_t sv;
3778           HOST_WIDE_INT fosize;
3779           tree currfotype;
3780
3781           fosize = TREE_INT_CST_LOW (fo->size);
3782           currfotype = fo->type;
3783
3784           /* If this field isn't in the used portion,
3785              or it has the exact same offset and size as the last
3786              field, skip it.  */
3787
3788           if (((fo->offset <= up->minused
3789                 && fo->offset + fosize <= up->minused)
3790                || fo->offset >= up->maxused)
3791               || (fo->offset == lastfooffset
3792                   && fosize == lastfosize
3793                   && currfotype == lastfotype))
3794             continue;
3795           sv = GGC_NEW (struct subvar);
3796           sv->next = *subvars;
3797           sv->var =
3798             create_sft (var, fo->type, fo->offset, fosize, fo->alias_set);
3799
3800           if (dump_file)
3801             {
3802               fprintf (dump_file, "structure field tag %s created for var %s",
3803                        get_name (sv->var), get_name (var));
3804               fprintf (dump_file, " offset " HOST_WIDE_INT_PRINT_DEC,
3805                        SFT_OFFSET (sv->var));
3806               fprintf (dump_file, " size " HOST_WIDE_INT_PRINT_DEC,
3807                        SFT_SIZE (sv->var));
3808               fprintf (dump_file, "\n");
3809             }
3810           
3811           lastfotype = currfotype;
3812           lastfooffset = fo->offset;
3813           lastfosize = fosize;
3814           *subvars = sv;
3815         }
3816
3817       /* Once we have created subvars, the original is no longer call
3818          clobbered on its own.  Its call clobbered status depends
3819          completely on the call clobbered status of the subvars.
3820
3821          add_referenced_var in the above loop will take care of
3822          marking subvars of global variables as call clobbered for us
3823          to start, since they are global as well.  */
3824       clear_call_clobbered (var);
3825     }
3826
3827   VEC_free (fieldoff_s, heap, fieldstack);
3828 }
3829
3830
3831 /* Find the conservative answer to the question of what portions of what 
3832    structures are used by this statement.  We assume that if we have a
3833    component ref with a known size + offset, that we only need that part
3834    of the structure.  For unknown cases, or cases where we do something
3835    to the whole structure, we assume we need to create fields for the 
3836    entire structure.  */
3837
3838 static tree
3839 find_used_portions (tree *tp, int *walk_subtrees, void *lhs_p)
3840 {
3841   switch (TREE_CODE (*tp))
3842     {
3843     case GIMPLE_MODIFY_STMT:
3844       /* Recurse manually here to track whether the use is in the
3845          LHS of an assignment.  */
3846       find_used_portions (&GIMPLE_STMT_OPERAND (*tp, 0), walk_subtrees, tp);
3847       return find_used_portions (&GIMPLE_STMT_OPERAND (*tp, 1),
3848                                  walk_subtrees, NULL);
3849     case REALPART_EXPR:
3850     case IMAGPART_EXPR:
3851     case COMPONENT_REF:
3852     case ARRAY_REF:
3853       {
3854         HOST_WIDE_INT bitsize;
3855         HOST_WIDE_INT bitmaxsize;
3856         HOST_WIDE_INT bitpos;
3857         tree ref;
3858         ref = get_ref_base_and_extent (*tp, &bitpos, &bitsize, &bitmaxsize);
3859         if (DECL_P (ref)
3860             && var_can_have_subvars (ref)
3861             && bitmaxsize != -1)
3862           {
3863             size_t uid = DECL_UID (ref);
3864             used_part_t up;
3865
3866             up = get_or_create_used_part_for (uid);         
3867
3868             if (bitpos <= up->minused)
3869               up->minused = bitpos;
3870             if ((bitpos + bitmaxsize >= up->maxused))
3871               up->maxused = bitpos + bitmaxsize;
3872
3873             if (bitsize == bitmaxsize)
3874               up->explicit_uses = true;
3875             else
3876               up->implicit_uses = true;
3877             if (!lhs_p)
3878               up->write_only = false;
3879             up_insert (uid, up);
3880
3881             *walk_subtrees = 0;
3882             return NULL_TREE;
3883           }
3884       }
3885       break;
3886       /* This is here to make sure we mark the entire base variable as used
3887          when you take its address.  Because our used portion analysis is
3888          simple, we aren't looking at casts or pointer arithmetic to see what
3889          happens when you take the address.  */
3890     case ADDR_EXPR:
3891       {
3892         tree var = get_base_address (TREE_OPERAND (*tp, 0));
3893
3894         if (var 
3895             && DECL_P (var)
3896             && DECL_SIZE (var)
3897             && var_can_have_subvars (var)
3898             && TREE_CODE (DECL_SIZE (var)) == INTEGER_CST)
3899           {
3900             used_part_t up;
3901             size_t uid = DECL_UID (var);
3902             
3903             up = get_or_create_used_part_for (uid);
3904  
3905             up->minused = 0;
3906             up->maxused = TREE_INT_CST_LOW (DECL_SIZE (var));
3907             up->implicit_uses = true;
3908             if (!lhs_p)
3909               up->write_only = false;
3910
3911             up_insert (uid, up);
3912             *walk_subtrees = 0;
3913             return NULL_TREE;
3914           }
3915       }
3916       break;
3917     case CALL_EXPR:
3918       {
3919         int i;
3920         int nargs = call_expr_nargs (*tp);
3921         for (i = 0; i < nargs; i++)
3922           {
3923             tree *arg = &CALL_EXPR_ARG (*tp, i);
3924             if (TREE_CODE (*arg) != ADDR_EXPR)
3925               find_used_portions (arg, walk_subtrees, NULL);
3926           }
3927         *walk_subtrees = 0;
3928         return NULL_TREE;
3929       }
3930     case VAR_DECL:
3931     case PARM_DECL:
3932     case RESULT_DECL:
3933       {
3934         tree var = *tp;
3935         if (DECL_SIZE (var)
3936             && var_can_have_subvars (var)
3937             && TREE_CODE (DECL_SIZE (var)) == INTEGER_CST)
3938           {
3939             used_part_t up;
3940             size_t uid = DECL_UID (var);
3941             
3942             up = get_or_create_used_part_for (uid);
3943  
3944             up->minused = 0;
3945             up->maxused = TREE_INT_CST_LOW (DECL_SIZE (var));
3946             up->implicit_uses = true;
3947
3948             up_insert (uid, up);
3949             *walk_subtrees = 0;
3950             return NULL_TREE;
3951           }
3952       }
3953       break;
3954       
3955     default:
3956       break;
3957       
3958     }
3959   return NULL_TREE;
3960 }
3961
3962 /* Create structure field variables for structures used in this function.  */
3963
3964 static unsigned int
3965 create_structure_vars (void)
3966 {
3967   basic_block bb;
3968   safe_referenced_var_iterator rvi;
3969   VEC (tree, heap) *varvec = NULL;
3970   tree var;
3971
3972   used_portions = htab_create (10, used_part_map_hash, used_part_map_eq, 
3973                                free_used_part_map);
3974   
3975   FOR_EACH_BB (bb)
3976     {
3977       block_stmt_iterator bsi;
3978       for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
3979         {
3980           walk_tree_without_duplicates (bsi_stmt_ptr (bsi), 
3981                                         find_used_portions,
3982                                         NULL);
3983         }
3984     }
3985   FOR_EACH_REFERENCED_VAR_SAFE (var, varvec, rvi)
3986     {
3987       /* The C++ FE creates vars without DECL_SIZE set, for some reason.  */
3988       if (var     
3989           && DECL_SIZE (var)
3990           && var_can_have_subvars (var)
3991           && !MTAG_P (var)
3992           && TREE_CODE (DECL_SIZE (var)) == INTEGER_CST)
3993         create_overlap_variables_for (var);
3994     }
3995   htab_delete (used_portions);
3996   VEC_free (tree, heap, varvec);
3997
3998   /* Update SSA operands of statements mentioning variables we split.  */
3999   if (gimple_in_ssa_p (cfun))
4000     FOR_EACH_BB (bb)
4001       {
4002         block_stmt_iterator bsi;
4003         for (bsi = bsi_start (bb); !bsi_end_p (bsi); bsi_next (&bsi))
4004           {
4005             tree stmt = bsi_stmt (bsi);
4006             bool update = false;
4007             unsigned int i;
4008             bitmap_iterator bi;
4009
4010             if (STORED_SYMS (stmt))
4011                EXECUTE_IF_SET_IN_BITMAP (STORED_SYMS (stmt), 0, i, bi)
4012                 {
4013                   tree sym = referenced_var_lookup (i);
4014                   if (get_subvars_for_var (sym))
4015                     {
4016                       update=true;
4017                       break;
4018                     }
4019                 }
4020
4021             if (LOADED_SYMS (stmt) && !update)
4022                EXECUTE_IF_SET_IN_BITMAP (LOADED_SYMS (stmt), 0, i, bi)
4023                 {
4024                   tree sym = referenced_var_lookup (i);
4025                   if (get_subvars_for_var (sym))
4026                     {
4027                       update=true;
4028                       break;
4029                     }
4030                 }
4031
4032             if (stmt_ann (stmt)->addresses_taken && !update)
4033                EXECUTE_IF_SET_IN_BITMAP (stmt_ann (stmt)->addresses_taken,
4034                                          0, i, bi)
4035                 {
4036                   tree sym = referenced_var_lookup (i);
4037                   if (get_subvars_for_var (sym))
4038                     {
4039                       update=true;
4040                       break;
4041                     }
4042                 }
4043
4044             if (update)
4045               update_stmt (stmt);
4046           }
4047       }
4048
4049   return TODO_rebuild_alias;
4050 }
4051
4052 static bool
4053 gate_structure_vars (void)
4054 {
4055   return flag_tree_salias != 0;
4056 }
4057
4058 struct tree_opt_pass pass_create_structure_vars = 
4059 {
4060   "salias",              /* name */
4061   gate_structure_vars,   /* gate */
4062   create_structure_vars, /* execute */
4063   NULL,                  /* sub */
4064   NULL,                  /* next */
4065   0,                     /* static_pass_number */
4066   0,                     /* tv_id */
4067   PROP_cfg,              /* properties_required */
4068   0,                     /* properties_provided */
4069   0,                     /* properties_destroyed */
4070   0,                     /* todo_flags_start */
4071   TODO_dump_func,        /* todo_flags_finish */
4072   0                      /* letter */
4073 };
4074
4075 /* Reset the call_clobbered flags on our referenced vars.  In
4076    theory, this only needs to be done for globals.  */
4077
4078 static unsigned int
4079 reset_cc_flags (void)
4080 {
4081   tree var;
4082   referenced_var_iterator rvi;
4083
4084   FOR_EACH_REFERENCED_VAR (var, rvi)
4085     var_ann (var)->call_clobbered = false;
4086   return 0;
4087 }
4088
4089 struct tree_opt_pass pass_reset_cc_flags =
4090 {
4091   NULL,          /* name */
4092   NULL,          /* gate */
4093   reset_cc_flags, /* execute */
4094   NULL,                  /* sub */
4095   NULL,                  /* next */
4096   0,                     /* static_pass_number */
4097   0,                     /* tv_id */
4098   PROP_referenced_vars |PROP_cfg, /* properties_required */
4099   0,                     /* properties_provided */
4100   0,                     /* properties_destroyed */
4101   0,                     /* todo_flags_start */
4102   0,                     /* todo_flags_finish */
4103   0                      /* letter */
4104 };