OSDN Git Service

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