OSDN Git Service

2006-03-03 Daniel Berlin <dberlin@dberlin.org>
[pf3gnuchains/gcc-fork.git] / gcc / tree-sra.c
1 /* Scalar Replacement of Aggregates (SRA) converts some structure
2    references into scalar references, exposing them to the scalar
3    optimizers.
4    Copyright (C) 2003, 2004, 2005, 2006 Free Software Foundation, Inc.
5    Contributed by Diego Novillo <dnovillo@redhat.com>
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option) any
12 later version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT
15 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING.  If not, write to the Free
21 Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
22 02110-1301, USA.  */
23
24 #include "config.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "tm.h"
28 #include "ggc.h"
29 #include "tree.h"
30
31 /* These RTL headers are needed for basic-block.h.  */
32 #include "rtl.h"
33 #include "tm_p.h"
34 #include "hard-reg-set.h"
35 #include "basic-block.h"
36 #include "diagnostic.h"
37 #include "langhooks.h"
38 #include "tree-inline.h"
39 #include "tree-flow.h"
40 #include "tree-gimple.h"
41 #include "tree-dump.h"
42 #include "tree-pass.h"
43 #include "timevar.h"
44 #include "flags.h"
45 #include "bitmap.h"
46 #include "obstack.h"
47 #include "target.h"
48 /* expr.h is needed for MOVE_RATIO.  */
49 #include "expr.h"
50 #include "params.h"
51
52
53 /* This object of this pass is to replace a non-addressable aggregate with a
54    set of independent variables.  Most of the time, all of these variables
55    will be scalars.  But a secondary objective is to break up larger
56    aggregates into smaller aggregates.  In the process we may find that some
57    bits of the larger aggregate can be deleted as unreferenced.
58
59    This substitution is done globally.  More localized substitutions would
60    be the purvey of a load-store motion pass.
61
62    The optimization proceeds in phases:
63
64      (1) Identify variables that have types that are candidates for
65          decomposition.
66
67      (2) Scan the function looking for the ways these variables are used.
68          In particular we're interested in the number of times a variable
69          (or member) is needed as a complete unit, and the number of times
70          a variable (or member) is copied.
71
72      (3) Based on the usage profile, instantiate substitution variables.
73
74      (4) Scan the function making replacements.
75 */
76
77
78 /* The set of todo flags to return from tree_sra.  */
79 static unsigned int todoflags;
80
81 /* The set of aggregate variables that are candidates for scalarization.  */
82 static bitmap sra_candidates;
83
84 /* Set of scalarizable PARM_DECLs that need copy-in operations at the
85    beginning of the function.  */
86 static bitmap needs_copy_in;
87
88 /* Sets of bit pairs that cache type decomposition and instantiation.  */
89 static bitmap sra_type_decomp_cache;
90 static bitmap sra_type_inst_cache;
91
92 /* One of these structures is created for each candidate aggregate
93    and each (accessed) member of such an aggregate.  */
94 struct sra_elt
95 {
96   /* A tree of the elements.  Used when we want to traverse everything.  */
97   struct sra_elt *parent;
98   struct sra_elt *children;
99   struct sra_elt *sibling;
100
101   /* If this element is a root, then this is the VAR_DECL.  If this is
102      a sub-element, this is some token used to identify the reference.
103      In the case of COMPONENT_REF, this is the FIELD_DECL.  In the case
104      of an ARRAY_REF, this is the (constant) index.  In the case of a
105      complex number, this is a zero or one.  */
106   tree element;
107
108   /* The type of the element.  */
109   tree type;
110
111   /* A VAR_DECL, for any sub-element we've decided to replace.  */
112   tree replacement;
113
114   /* The number of times the element is referenced as a whole.  I.e.
115      given "a.b.c", this would be incremented for C, but not for A or B.  */
116   unsigned int n_uses;
117
118   /* The number of times the element is copied to or from another
119      scalarizable element.  */
120   unsigned int n_copies;
121
122   /* True if TYPE is scalar.  */
123   bool is_scalar;
124
125   /* True if we saw something about this element that prevents scalarization,
126      such as non-constant indexing.  */
127   bool cannot_scalarize;
128
129   /* True if we've decided that structure-to-structure assignment
130      should happen via memcpy and not per-element.  */
131   bool use_block_copy;
132
133   /* True if everything under this element has been marked TREE_NO_WARNING.  */
134   bool all_no_warning;
135
136   /* A flag for use with/after random access traversals.  */
137   bool visited;
138 };
139
140 /* Random access to the child of a parent is performed by hashing.
141    This prevents quadratic behavior, and allows SRA to function
142    reasonably on larger records.  */
143 static htab_t sra_map;
144
145 /* All structures are allocated out of the following obstack.  */
146 static struct obstack sra_obstack;
147
148 /* Debugging functions.  */
149 static void dump_sra_elt_name (FILE *, struct sra_elt *);
150 extern void debug_sra_elt_name (struct sra_elt *);
151
152 /* Forward declarations.  */
153 static tree generate_element_ref (struct sra_elt *);
154 \f
155 /* Return true if DECL is an SRA candidate.  */
156
157 static bool
158 is_sra_candidate_decl (tree decl)
159 {
160   return DECL_P (decl) && bitmap_bit_p (sra_candidates, DECL_UID (decl));
161 }
162
163 /* Return true if TYPE is a scalar type.  */
164
165 static bool
166 is_sra_scalar_type (tree type)
167 {
168   enum tree_code code = TREE_CODE (type);
169   return (code == INTEGER_TYPE || code == REAL_TYPE || code == VECTOR_TYPE
170           || code == ENUMERAL_TYPE || code == BOOLEAN_TYPE
171           || code == POINTER_TYPE || code == OFFSET_TYPE
172           || code == REFERENCE_TYPE);
173 }
174
175 /* Return true if TYPE can be decomposed into a set of independent variables.
176
177    Note that this doesn't imply that all elements of TYPE can be
178    instantiated, just that if we decide to break up the type into
179    separate pieces that it can be done.  */
180
181 bool
182 sra_type_can_be_decomposed_p (tree type)
183 {
184   unsigned int cache = TYPE_UID (TYPE_MAIN_VARIANT (type)) * 2;
185   tree t;
186
187   /* Avoid searching the same type twice.  */
188   if (bitmap_bit_p (sra_type_decomp_cache, cache+0))
189     return true;
190   if (bitmap_bit_p (sra_type_decomp_cache, cache+1))
191     return false;
192
193   /* The type must have a definite nonzero size.  */
194   if (TYPE_SIZE (type) == NULL || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST
195       || integer_zerop (TYPE_SIZE (type)))
196     goto fail;
197
198   /* The type must be a non-union aggregate.  */
199   switch (TREE_CODE (type))
200     {
201     case RECORD_TYPE:
202       {
203         bool saw_one_field = false;
204
205         for (t = TYPE_FIELDS (type); t ; t = TREE_CHAIN (t))
206           if (TREE_CODE (t) == FIELD_DECL)
207             {
208               /* Reject incorrectly represented bit fields.  */
209               if (DECL_BIT_FIELD (t)
210                   && (tree_low_cst (DECL_SIZE (t), 1)
211                       != TYPE_PRECISION (TREE_TYPE (t))))
212                 goto fail;
213
214               saw_one_field = true;
215             }
216
217         /* Record types must have at least one field.  */
218         if (!saw_one_field)
219           goto fail;
220       }
221       break;
222
223     case ARRAY_TYPE:
224       /* Array types must have a fixed lower and upper bound.  */
225       t = TYPE_DOMAIN (type);
226       if (t == NULL)
227         goto fail;
228       if (TYPE_MIN_VALUE (t) == NULL || !TREE_CONSTANT (TYPE_MIN_VALUE (t)))
229         goto fail;
230       if (TYPE_MAX_VALUE (t) == NULL || !TREE_CONSTANT (TYPE_MAX_VALUE (t)))
231         goto fail;
232       break;
233
234     case COMPLEX_TYPE:
235       break;
236
237     default:
238       goto fail;
239     }
240
241   bitmap_set_bit (sra_type_decomp_cache, cache+0);
242   return true;
243
244  fail:
245   bitmap_set_bit (sra_type_decomp_cache, cache+1);
246   return false;
247 }
248
249 /* Return true if DECL can be decomposed into a set of independent
250    (though not necessarily scalar) variables.  */
251
252 static bool
253 decl_can_be_decomposed_p (tree var)
254 {
255   /* Early out for scalars.  */
256   if (is_sra_scalar_type (TREE_TYPE (var)))
257     return false;
258
259   /* The variable must not be aliased.  */
260   if (!is_gimple_non_addressable (var))
261     {
262       if (dump_file && (dump_flags & TDF_DETAILS))
263         {
264           fprintf (dump_file, "Cannot scalarize variable ");
265           print_generic_expr (dump_file, var, dump_flags);
266           fprintf (dump_file, " because it must live in memory\n");
267         }
268       return false;
269     }
270
271   /* The variable must not be volatile.  */
272   if (TREE_THIS_VOLATILE (var))
273     {
274       if (dump_file && (dump_flags & TDF_DETAILS))
275         {
276           fprintf (dump_file, "Cannot scalarize variable ");
277           print_generic_expr (dump_file, var, dump_flags);
278           fprintf (dump_file, " because it is declared volatile\n");
279         }
280       return false;
281     }
282
283   /* We must be able to decompose the variable's type.  */
284   if (!sra_type_can_be_decomposed_p (TREE_TYPE (var)))
285     {
286       if (dump_file && (dump_flags & TDF_DETAILS))
287         {
288           fprintf (dump_file, "Cannot scalarize variable ");
289           print_generic_expr (dump_file, var, dump_flags);
290           fprintf (dump_file, " because its type cannot be decomposed\n");
291         }
292       return false;
293     }
294
295   return true;
296 }
297
298 /* Return true if TYPE can be *completely* decomposed into scalars.  */
299
300 static bool
301 type_can_instantiate_all_elements (tree type)
302 {
303   if (is_sra_scalar_type (type))
304     return true;
305   if (!sra_type_can_be_decomposed_p (type))
306     return false;
307
308   switch (TREE_CODE (type))
309     {
310     case RECORD_TYPE:
311       {
312         unsigned int cache = TYPE_UID (TYPE_MAIN_VARIANT (type)) * 2;
313         tree f;
314
315         if (bitmap_bit_p (sra_type_inst_cache, cache+0))
316           return true;
317         if (bitmap_bit_p (sra_type_inst_cache, cache+1))
318           return false;
319
320         for (f = TYPE_FIELDS (type); f ; f = TREE_CHAIN (f))
321           if (TREE_CODE (f) == FIELD_DECL)
322             {
323               if (!type_can_instantiate_all_elements (TREE_TYPE (f)))
324                 {
325                   bitmap_set_bit (sra_type_inst_cache, cache+1);
326                   return false;
327                 }
328             }
329
330         bitmap_set_bit (sra_type_inst_cache, cache+0);
331         return true;
332       }
333
334     case ARRAY_TYPE:
335       return type_can_instantiate_all_elements (TREE_TYPE (type));
336
337     case COMPLEX_TYPE:
338       return true;
339
340     default:
341       gcc_unreachable ();
342     }
343 }
344
345 /* Test whether ELT or some sub-element cannot be scalarized.  */
346
347 static bool
348 can_completely_scalarize_p (struct sra_elt *elt)
349 {
350   struct sra_elt *c;
351
352   if (elt->cannot_scalarize)
353     return false;
354
355   for (c = elt->children; c ; c = c->sibling)
356     if (!can_completely_scalarize_p (c))
357       return false;
358
359   return true;
360 }
361
362 \f
363 /* A simplified tree hashing algorithm that only handles the types of
364    trees we expect to find in sra_elt->element.  */
365
366 static hashval_t
367 sra_hash_tree (tree t)
368 {
369   hashval_t h;
370
371   switch (TREE_CODE (t))
372     {
373     case VAR_DECL:
374     case PARM_DECL:
375     case RESULT_DECL:
376       h = DECL_UID (t);
377       break;
378
379     case INTEGER_CST:
380       h = TREE_INT_CST_LOW (t) ^ TREE_INT_CST_HIGH (t);
381       break;
382
383     case FIELD_DECL:
384       /* We can have types that are compatible, but have different member
385          lists, so we can't hash fields by ID.  Use offsets instead.  */
386       h = iterative_hash_expr (DECL_FIELD_OFFSET (t), 0);
387       h = iterative_hash_expr (DECL_FIELD_BIT_OFFSET (t), h);
388       break;
389
390     default:
391       gcc_unreachable ();
392     }
393
394   return h;
395 }
396
397 /* Hash function for type SRA_PAIR.  */
398
399 static hashval_t
400 sra_elt_hash (const void *x)
401 {
402   const struct sra_elt *e = x;
403   const struct sra_elt *p;
404   hashval_t h;
405
406   h = sra_hash_tree (e->element);
407
408   /* Take into account everything back up the chain.  Given that chain
409      lengths are rarely very long, this should be acceptable.  If we
410      truly identify this as a performance problem, it should work to
411      hash the pointer value "e->parent".  */
412   for (p = e->parent; p ; p = p->parent)
413     h = (h * 65521) ^ sra_hash_tree (p->element);
414
415   return h;
416 }
417
418 /* Equality function for type SRA_PAIR.  */
419
420 static int
421 sra_elt_eq (const void *x, const void *y)
422 {
423   const struct sra_elt *a = x;
424   const struct sra_elt *b = y;
425   tree ae, be;
426
427   if (a->parent != b->parent)
428     return false;
429
430   ae = a->element;
431   be = b->element;
432
433   if (ae == be)
434     return true;
435   if (TREE_CODE (ae) != TREE_CODE (be))
436     return false;
437
438   switch (TREE_CODE (ae))
439     {
440     case VAR_DECL:
441     case PARM_DECL:
442     case RESULT_DECL:
443       /* These are all pointer unique.  */
444       return false;
445
446     case INTEGER_CST:
447       /* Integers are not pointer unique, so compare their values.  */
448       return tree_int_cst_equal (ae, be);
449
450     case FIELD_DECL:
451       /* Fields are unique within a record, but not between
452          compatible records.  */
453       if (DECL_FIELD_CONTEXT (ae) == DECL_FIELD_CONTEXT (be))
454         return false;
455       return fields_compatible_p (ae, be);
456
457     default:
458       gcc_unreachable ();
459     }
460 }
461
462 /* Create or return the SRA_ELT structure for CHILD in PARENT.  PARENT
463    may be null, in which case CHILD must be a DECL.  */
464
465 static struct sra_elt *
466 lookup_element (struct sra_elt *parent, tree child, tree type,
467                 enum insert_option insert)
468 {
469   struct sra_elt dummy;
470   struct sra_elt **slot;
471   struct sra_elt *elt;
472
473   dummy.parent = parent;
474   dummy.element = child;
475
476   slot = (struct sra_elt **) htab_find_slot (sra_map, &dummy, insert);
477   if (!slot && insert == NO_INSERT)
478     return NULL;
479
480   elt = *slot;
481   if (!elt && insert == INSERT)
482     {
483       *slot = elt = obstack_alloc (&sra_obstack, sizeof (*elt));
484       memset (elt, 0, sizeof (*elt));
485
486       elt->parent = parent;
487       elt->element = child;
488       elt->type = type;
489       elt->is_scalar = is_sra_scalar_type (type);
490
491       if (parent)
492         {
493           elt->sibling = parent->children;
494           parent->children = elt;
495         }
496
497       /* If this is a parameter, then if we want to scalarize, we have
498          one copy from the true function parameter.  Count it now.  */
499       if (TREE_CODE (child) == PARM_DECL)
500         {
501           elt->n_copies = 1;
502           bitmap_set_bit (needs_copy_in, DECL_UID (child));
503         }
504     }
505
506   return elt;
507 }
508
509 /* Return true if the ARRAY_REF in EXPR is a constant, in bounds access.  */
510
511 static bool
512 is_valid_const_index (tree expr)
513 {
514   tree dom, t, index = TREE_OPERAND (expr, 1);
515
516   if (TREE_CODE (index) != INTEGER_CST)
517     return false;
518
519   /* Watch out for stupid user tricks, indexing outside the array.
520
521      Careful, we're not called only on scalarizable types, so do not
522      assume constant array bounds.  We needn't do anything with such
523      cases, since they'll be referring to objects that we should have
524      already rejected for scalarization, so returning false is fine.  */
525
526   dom = TYPE_DOMAIN (TREE_TYPE (TREE_OPERAND (expr, 0)));
527   if (dom == NULL)
528     return false;
529
530   t = TYPE_MIN_VALUE (dom);
531   if (!t || TREE_CODE (t) != INTEGER_CST)
532     return false;
533   if (tree_int_cst_lt (index, t))
534     return false;
535
536   t = TYPE_MAX_VALUE (dom);
537   if (!t || TREE_CODE (t) != INTEGER_CST)
538     return false;
539   if (tree_int_cst_lt (t, index))
540     return false;
541
542   return true;
543 }
544
545 /* Create or return the SRA_ELT structure for EXPR if the expression
546    refers to a scalarizable variable.  */
547
548 static struct sra_elt *
549 maybe_lookup_element_for_expr (tree expr)
550 {
551   struct sra_elt *elt;
552   tree child;
553
554   switch (TREE_CODE (expr))
555     {
556     case VAR_DECL:
557     case PARM_DECL:
558     case RESULT_DECL:
559       if (is_sra_candidate_decl (expr))
560         return lookup_element (NULL, expr, TREE_TYPE (expr), INSERT);
561       return NULL;
562
563     case ARRAY_REF:
564       /* We can't scalarize variable array indicies.  */
565       if (is_valid_const_index (expr))
566         child = TREE_OPERAND (expr, 1);
567       else
568         return NULL;
569       break;
570
571     case COMPONENT_REF:
572       /* Don't look through unions.  */
573       if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) != RECORD_TYPE)
574         return NULL;
575       child = TREE_OPERAND (expr, 1);
576       break;
577
578     case REALPART_EXPR:
579       child = integer_zero_node;
580       break;
581     case IMAGPART_EXPR:
582       child = integer_one_node;
583       break;
584
585     default:
586       return NULL;
587     }
588
589   elt = maybe_lookup_element_for_expr (TREE_OPERAND (expr, 0));
590   if (elt)
591     return lookup_element (elt, child, TREE_TYPE (expr), INSERT);
592   return NULL;
593 }
594
595 \f
596 /* Functions to walk just enough of the tree to see all scalarizable
597    references, and categorize them.  */
598
599 /* A set of callbacks for phases 2 and 4.  They'll be invoked for the
600    various kinds of references seen.  In all cases, *BSI is an iterator
601    pointing to the statement being processed.  */
602 struct sra_walk_fns
603 {
604   /* Invoked when ELT is required as a unit.  Note that ELT might refer to
605      a leaf node, in which case this is a simple scalar reference.  *EXPR_P
606      points to the location of the expression.  IS_OUTPUT is true if this
607      is a left-hand-side reference.  USE_ALL is true if we saw something we
608      couldn't quite identify and had to force the use of the entire object.  */
609   void (*use) (struct sra_elt *elt, tree *expr_p,
610                block_stmt_iterator *bsi, bool is_output, bool use_all);
611
612   /* Invoked when we have a copy between two scalarizable references.  */
613   void (*copy) (struct sra_elt *lhs_elt, struct sra_elt *rhs_elt,
614                 block_stmt_iterator *bsi);
615
616   /* Invoked when ELT is initialized from a constant.  VALUE may be NULL,
617      in which case it should be treated as an empty CONSTRUCTOR.  */
618   void (*init) (struct sra_elt *elt, tree value, block_stmt_iterator *bsi);
619
620   /* Invoked when we have a copy between one scalarizable reference ELT
621      and one non-scalarizable reference OTHER.  IS_OUTPUT is true if ELT
622      is on the left-hand side.  */
623   void (*ldst) (struct sra_elt *elt, tree other,
624                 block_stmt_iterator *bsi, bool is_output);
625
626   /* True during phase 2, false during phase 4.  */
627   /* ??? This is a hack.  */
628   bool initial_scan;
629 };
630
631 #ifdef ENABLE_CHECKING
632 /* Invoked via walk_tree, if *TP contains a candidate decl, return it.  */
633
634 static tree
635 sra_find_candidate_decl (tree *tp, int *walk_subtrees,
636                          void *data ATTRIBUTE_UNUSED)
637 {
638   tree t = *tp;
639   enum tree_code code = TREE_CODE (t);
640
641   if (code == VAR_DECL || code == PARM_DECL || code == RESULT_DECL)
642     {
643       *walk_subtrees = 0;
644       if (is_sra_candidate_decl (t))
645         return t;
646     }
647   else if (TYPE_P (t))
648     *walk_subtrees = 0;
649
650   return NULL;
651 }
652 #endif
653
654 /* Walk most expressions looking for a scalarizable aggregate.
655    If we find one, invoke FNS->USE.  */
656
657 static void
658 sra_walk_expr (tree *expr_p, block_stmt_iterator *bsi, bool is_output,
659                const struct sra_walk_fns *fns)
660 {
661   tree expr = *expr_p;
662   tree inner = expr;
663   bool disable_scalarization = false;
664   bool use_all_p = false;
665
666   /* We're looking to collect a reference expression between EXPR and INNER,
667      such that INNER is a scalarizable decl and all other nodes through EXPR
668      are references that we can scalarize.  If we come across something that
669      we can't scalarize, we reset EXPR.  This has the effect of making it
670      appear that we're referring to the larger expression as a whole.  */
671
672   while (1)
673     switch (TREE_CODE (inner))
674       {
675       case VAR_DECL:
676       case PARM_DECL:
677       case RESULT_DECL:
678         /* If there is a scalarizable decl at the bottom, then process it.  */
679         if (is_sra_candidate_decl (inner))
680           {
681             struct sra_elt *elt = maybe_lookup_element_for_expr (expr);
682             if (disable_scalarization)
683               elt->cannot_scalarize = true;
684             else
685               fns->use (elt, expr_p, bsi, is_output, use_all_p);
686           }
687         return;
688
689       case ARRAY_REF:
690         /* Non-constant index means any member may be accessed.  Prevent the
691            expression from being scalarized.  If we were to treat this as a
692            reference to the whole array, we can wind up with a single dynamic
693            index reference inside a loop being overridden by several constant
694            index references during loop setup.  It's possible that this could
695            be avoided by using dynamic usage counts based on BB trip counts
696            (based on loop analysis or profiling), but that hardly seems worth
697            the effort.  */
698         /* ??? Hack.  Figure out how to push this into the scan routines
699            without duplicating too much code.  */
700         if (!is_valid_const_index (inner))
701           {
702             disable_scalarization = true;
703             goto use_all;
704           }
705         /* ??? Are we assured that non-constant bounds and stride will have
706            the same value everywhere?  I don't think Fortran will...  */
707         if (TREE_OPERAND (inner, 2) || TREE_OPERAND (inner, 3))
708           goto use_all;
709         inner = TREE_OPERAND (inner, 0);
710         break;
711
712       case COMPONENT_REF:
713         /* A reference to a union member constitutes a reference to the
714            entire union.  */
715         if (TREE_CODE (TREE_TYPE (TREE_OPERAND (inner, 0))) != RECORD_TYPE)
716           goto use_all;
717         /* ??? See above re non-constant stride.  */
718         if (TREE_OPERAND (inner, 2))
719           goto use_all;
720         inner = TREE_OPERAND (inner, 0);
721         break;
722
723       case REALPART_EXPR:
724       case IMAGPART_EXPR:
725         inner = TREE_OPERAND (inner, 0);
726         break;
727
728       case BIT_FIELD_REF:
729         /* A bit field reference (access to *multiple* fields simultaneously)
730            is not currently scalarized.  Consider this an access to the
731            complete outer element, to which walk_tree will bring us next.  */
732         goto use_all;
733
734       case ARRAY_RANGE_REF:
735         /* Similarly, a subrange reference is used to modify indexing.  Which
736            means that the canonical element names that we have won't work.  */
737         goto use_all;
738
739       case VIEW_CONVERT_EXPR:
740       case NOP_EXPR:
741         /* Similarly, a view/nop explicitly wants to look at an object in a
742            type other than the one we've scalarized.  */
743         goto use_all;
744
745       case WITH_SIZE_EXPR:
746         /* This is a transparent wrapper.  The entire inner expression really
747            is being used.  */
748         goto use_all;
749
750       use_all:
751         expr_p = &TREE_OPERAND (inner, 0);
752         inner = expr = *expr_p;
753         use_all_p = true;
754         break;
755
756       default:
757 #ifdef ENABLE_CHECKING
758         /* Validate that we're not missing any references.  */
759         gcc_assert (!walk_tree (&inner, sra_find_candidate_decl, NULL, NULL));
760 #endif
761         return;
762       }
763 }
764
765 /* Walk a TREE_LIST of values looking for scalarizable aggregates.
766    If we find one, invoke FNS->USE.  */
767
768 static void
769 sra_walk_tree_list (tree list, block_stmt_iterator *bsi, bool is_output,
770                     const struct sra_walk_fns *fns)
771 {
772   tree op;
773   for (op = list; op ; op = TREE_CHAIN (op))
774     sra_walk_expr (&TREE_VALUE (op), bsi, is_output, fns);
775 }
776
777 /* Walk the arguments of a CALL_EXPR looking for scalarizable aggregates.
778    If we find one, invoke FNS->USE.  */
779
780 static void
781 sra_walk_call_expr (tree expr, block_stmt_iterator *bsi,
782                     const struct sra_walk_fns *fns)
783 {
784   sra_walk_tree_list (TREE_OPERAND (expr, 1), bsi, false, fns);
785 }
786
787 /* Walk the inputs and outputs of an ASM_EXPR looking for scalarizable
788    aggregates.  If we find one, invoke FNS->USE.  */
789
790 static void
791 sra_walk_asm_expr (tree expr, block_stmt_iterator *bsi,
792                    const struct sra_walk_fns *fns)
793 {
794   sra_walk_tree_list (ASM_INPUTS (expr), bsi, false, fns);
795   sra_walk_tree_list (ASM_OUTPUTS (expr), bsi, true, fns);
796 }
797
798 /* Walk a MODIFY_EXPR and categorize the assignment appropriately.  */
799
800 static void
801 sra_walk_modify_expr (tree expr, block_stmt_iterator *bsi,
802                       const struct sra_walk_fns *fns)
803 {
804   struct sra_elt *lhs_elt, *rhs_elt;
805   tree lhs, rhs;
806
807   lhs = TREE_OPERAND (expr, 0);
808   rhs = TREE_OPERAND (expr, 1);
809   lhs_elt = maybe_lookup_element_for_expr (lhs);
810   rhs_elt = maybe_lookup_element_for_expr (rhs);
811
812   /* If both sides are scalarizable, this is a COPY operation.  */
813   if (lhs_elt && rhs_elt)
814     {
815       fns->copy (lhs_elt, rhs_elt, bsi);
816       return;
817     }
818
819   /* If the RHS is scalarizable, handle it.  There are only two cases.  */
820   if (rhs_elt)
821     {
822       if (!rhs_elt->is_scalar)
823         fns->ldst (rhs_elt, lhs, bsi, false);
824       else
825         fns->use (rhs_elt, &TREE_OPERAND (expr, 1), bsi, false, false);
826     }
827
828   /* If it isn't scalarizable, there may be scalarizable variables within, so
829      check for a call or else walk the RHS to see if we need to do any
830      copy-in operations.  We need to do it before the LHS is scalarized so
831      that the statements get inserted in the proper place, before any
832      copy-out operations.  */
833   else
834     {
835       tree call = get_call_expr_in (rhs);
836       if (call)
837         sra_walk_call_expr (call, bsi, fns);
838       else
839         sra_walk_expr (&TREE_OPERAND (expr, 1), bsi, false, fns);
840     }
841
842   /* Likewise, handle the LHS being scalarizable.  We have cases similar
843      to those above, but also want to handle RHS being constant.  */
844   if (lhs_elt)
845     {
846       /* If this is an assignment from a constant, or constructor, then
847          we have access to all of the elements individually.  Invoke INIT.  */
848       if (TREE_CODE (rhs) == COMPLEX_EXPR
849           || TREE_CODE (rhs) == COMPLEX_CST
850           || TREE_CODE (rhs) == CONSTRUCTOR)
851         fns->init (lhs_elt, rhs, bsi);
852
853       /* If this is an assignment from read-only memory, treat this as if
854          we'd been passed the constructor directly.  Invoke INIT.  */
855       else if (TREE_CODE (rhs) == VAR_DECL
856                && TREE_STATIC (rhs)
857                && TREE_READONLY (rhs)
858                && targetm.binds_local_p (rhs))
859         fns->init (lhs_elt, DECL_INITIAL (rhs), bsi);
860
861       /* If this is a copy from a non-scalarizable lvalue, invoke LDST.
862          The lvalue requirement prevents us from trying to directly scalarize
863          the result of a function call.  Which would result in trying to call
864          the function multiple times, and other evil things.  */
865       else if (!lhs_elt->is_scalar && is_gimple_addressable (rhs))
866         fns->ldst (lhs_elt, rhs, bsi, true);
867
868       /* Otherwise we're being used in some context that requires the
869          aggregate to be seen as a whole.  Invoke USE.  */
870       else
871         fns->use (lhs_elt, &TREE_OPERAND (expr, 0), bsi, true, false);
872     }
873
874   /* Similarly to above, LHS_ELT being null only means that the LHS as a
875      whole is not a scalarizable reference.  There may be occurrences of
876      scalarizable variables within, which implies a USE.  */
877   else
878     sra_walk_expr (&TREE_OPERAND (expr, 0), bsi, true, fns);
879 }
880
881 /* Entry point to the walk functions.  Search the entire function,
882    invoking the callbacks in FNS on each of the references to
883    scalarizable variables.  */
884
885 static void
886 sra_walk_function (const struct sra_walk_fns *fns)
887 {
888   basic_block bb;
889   block_stmt_iterator si, ni;
890
891   /* ??? Phase 4 could derive some benefit to walking the function in
892      dominator tree order.  */
893
894   FOR_EACH_BB (bb)
895     for (si = bsi_start (bb); !bsi_end_p (si); si = ni)
896       {
897         tree stmt, t;
898         stmt_ann_t ann;
899
900         stmt = bsi_stmt (si);
901         ann = stmt_ann (stmt);
902
903         ni = si;
904         bsi_next (&ni);
905
906         /* If the statement has no virtual operands, then it doesn't
907            make any structure references that we care about.  */
908         if (ZERO_SSA_OPERANDS (stmt, (SSA_OP_VIRTUAL_DEFS | SSA_OP_VUSE)))
909           continue;
910
911         switch (TREE_CODE (stmt))
912           {
913           case RETURN_EXPR:
914             /* If we have "return <retval>" then the return value is
915                already exposed for our pleasure.  Walk it as a USE to
916                force all the components back in place for the return.
917
918                If we have an embedded assignment, then <retval> is of
919                a type that gets returned in registers in this ABI, and
920                we do not wish to extend their lifetimes.  Treat this
921                as a USE of the variable on the RHS of this assignment.  */
922
923             t = TREE_OPERAND (stmt, 0);
924             if (TREE_CODE (t) == MODIFY_EXPR)
925               sra_walk_expr (&TREE_OPERAND (t, 1), &si, false, fns);
926             else
927               sra_walk_expr (&TREE_OPERAND (stmt, 0), &si, false, fns);
928             break;
929
930           case MODIFY_EXPR:
931             sra_walk_modify_expr (stmt, &si, fns);
932             break;
933           case CALL_EXPR:
934             sra_walk_call_expr (stmt, &si, fns);
935             break;
936           case ASM_EXPR:
937             sra_walk_asm_expr (stmt, &si, fns);
938             break;
939
940           default:
941             break;
942           }
943       }
944 }
945 \f
946 /* Phase One: Scan all referenced variables in the program looking for
947    structures that could be decomposed.  */
948
949 static bool
950 find_candidates_for_sra (void)
951 {
952   bool any_set = false;
953   tree var;
954   referenced_var_iterator rvi;
955
956   FOR_EACH_REFERENCED_VAR (var, rvi)
957     {
958       if (decl_can_be_decomposed_p (var))
959         {
960           bitmap_set_bit (sra_candidates, DECL_UID (var));
961           any_set = true;
962         }
963     }
964
965   return any_set;
966 }
967
968 \f
969 /* Phase Two: Scan all references to scalarizable variables.  Count the
970    number of times they are used or copied respectively.  */
971
972 /* Callbacks to fill in SRA_WALK_FNS.  Everything but USE is
973    considered a copy, because we can decompose the reference such that
974    the sub-elements needn't be contiguous.  */
975
976 static void
977 scan_use (struct sra_elt *elt, tree *expr_p ATTRIBUTE_UNUSED,
978           block_stmt_iterator *bsi ATTRIBUTE_UNUSED,
979           bool is_output ATTRIBUTE_UNUSED, bool use_all ATTRIBUTE_UNUSED)
980 {
981   elt->n_uses += 1;
982 }
983
984 static void
985 scan_copy (struct sra_elt *lhs_elt, struct sra_elt *rhs_elt,
986            block_stmt_iterator *bsi ATTRIBUTE_UNUSED)
987 {
988   lhs_elt->n_copies += 1;
989   rhs_elt->n_copies += 1;
990 }
991
992 static void
993 scan_init (struct sra_elt *lhs_elt, tree rhs ATTRIBUTE_UNUSED,
994            block_stmt_iterator *bsi ATTRIBUTE_UNUSED)
995 {
996   lhs_elt->n_copies += 1;
997 }
998
999 static void
1000 scan_ldst (struct sra_elt *elt, tree other ATTRIBUTE_UNUSED,
1001            block_stmt_iterator *bsi ATTRIBUTE_UNUSED,
1002            bool is_output ATTRIBUTE_UNUSED)
1003 {
1004   elt->n_copies += 1;
1005 }
1006
1007 /* Dump the values we collected during the scanning phase.  */
1008
1009 static void
1010 scan_dump (struct sra_elt *elt)
1011 {
1012   struct sra_elt *c;
1013
1014   dump_sra_elt_name (dump_file, elt);
1015   fprintf (dump_file, ": n_uses=%u n_copies=%u\n", elt->n_uses, elt->n_copies);
1016
1017   for (c = elt->children; c ; c = c->sibling)
1018     scan_dump (c);
1019 }
1020
1021 /* Entry point to phase 2.  Scan the entire function, building up
1022    scalarization data structures, recording copies and uses.  */
1023
1024 static void
1025 scan_function (void)
1026 {
1027   static const struct sra_walk_fns fns = {
1028     scan_use, scan_copy, scan_init, scan_ldst, true
1029   };
1030   bitmap_iterator bi;
1031
1032   sra_walk_function (&fns);
1033
1034   if (dump_file && (dump_flags & TDF_DETAILS))
1035     {
1036       unsigned i;
1037
1038       fputs ("\nScan results:\n", dump_file);
1039       EXECUTE_IF_SET_IN_BITMAP (sra_candidates, 0, i, bi)
1040         {
1041           tree var = referenced_var (i);
1042           struct sra_elt *elt = lookup_element (NULL, var, NULL, NO_INSERT);
1043           if (elt)
1044             scan_dump (elt);
1045         }
1046       fputc ('\n', dump_file);
1047     }
1048 }
1049 \f
1050 /* Phase Three: Make decisions about which variables to scalarize, if any.
1051    All elements to be scalarized have replacement variables made for them.  */
1052
1053 /* A subroutine of build_element_name.  Recursively build the element
1054    name on the obstack.  */
1055
1056 static void
1057 build_element_name_1 (struct sra_elt *elt)
1058 {
1059   tree t;
1060   char buffer[32];
1061
1062   if (elt->parent)
1063     {
1064       build_element_name_1 (elt->parent);
1065       obstack_1grow (&sra_obstack, '$');
1066
1067       if (TREE_CODE (elt->parent->type) == COMPLEX_TYPE)
1068         {
1069           if (elt->element == integer_zero_node)
1070             obstack_grow (&sra_obstack, "real", 4);
1071           else
1072             obstack_grow (&sra_obstack, "imag", 4);
1073           return;
1074         }
1075     }
1076
1077   t = elt->element;
1078   if (TREE_CODE (t) == INTEGER_CST)
1079     {
1080       /* ??? Eh.  Don't bother doing double-wide printing.  */
1081       sprintf (buffer, HOST_WIDE_INT_PRINT_DEC, TREE_INT_CST_LOW (t));
1082       obstack_grow (&sra_obstack, buffer, strlen (buffer));
1083     }
1084   else
1085     {
1086       tree name = DECL_NAME (t);
1087       if (name)
1088         obstack_grow (&sra_obstack, IDENTIFIER_POINTER (name),
1089                       IDENTIFIER_LENGTH (name));
1090       else
1091         {
1092           sprintf (buffer, "D%u", DECL_UID (t));
1093           obstack_grow (&sra_obstack, buffer, strlen (buffer));
1094         }
1095     }
1096 }
1097
1098 /* Construct a pretty variable name for an element's replacement variable.
1099    The name is built on the obstack.  */
1100
1101 static char *
1102 build_element_name (struct sra_elt *elt)
1103 {
1104   build_element_name_1 (elt);
1105   obstack_1grow (&sra_obstack, '\0');
1106   return XOBFINISH (&sra_obstack, char *);
1107 }
1108
1109 /* Instantiate an element as an independent variable.  */
1110
1111 static void
1112 instantiate_element (struct sra_elt *elt)
1113 {
1114   struct sra_elt *base_elt;
1115   tree var, base;
1116
1117   for (base_elt = elt; base_elt->parent; base_elt = base_elt->parent)
1118     continue;
1119   base = base_elt->element;
1120
1121   elt->replacement = var = make_rename_temp (elt->type, "SR");
1122   DECL_SOURCE_LOCATION (var) = DECL_SOURCE_LOCATION (base);
1123   DECL_ARTIFICIAL (var) = 1;
1124
1125   if (TREE_THIS_VOLATILE (elt->type))
1126     {
1127       TREE_THIS_VOLATILE (var) = 1;
1128       TREE_SIDE_EFFECTS (var) = 1;
1129     }
1130
1131   if (DECL_NAME (base) && !DECL_IGNORED_P (base))
1132     {
1133       char *pretty_name = build_element_name (elt);
1134       DECL_NAME (var) = get_identifier (pretty_name);
1135       obstack_free (&sra_obstack, pretty_name);
1136
1137       SET_DECL_DEBUG_EXPR (var, generate_element_ref (elt));
1138       DECL_DEBUG_EXPR_IS_FROM (var) = 1;
1139       
1140       DECL_IGNORED_P (var) = 0;
1141       TREE_NO_WARNING (var) = TREE_NO_WARNING (base);
1142     }
1143   else
1144     {
1145       DECL_IGNORED_P (var) = 1;
1146       /* ??? We can't generate any warning that would be meaningful.  */
1147       TREE_NO_WARNING (var) = 1;
1148     }
1149
1150   if (dump_file)
1151     {
1152       fputs ("  ", dump_file);
1153       dump_sra_elt_name (dump_file, elt);
1154       fputs (" -> ", dump_file);
1155       print_generic_expr (dump_file, var, dump_flags);
1156       fputc ('\n', dump_file);
1157     }
1158 }
1159
1160 /* Make one pass across an element tree deciding whether or not it's
1161    profitable to instantiate individual leaf scalars.
1162
1163    PARENT_USES and PARENT_COPIES are the sum of the N_USES and N_COPIES
1164    fields all the way up the tree.  */
1165
1166 static void
1167 decide_instantiation_1 (struct sra_elt *elt, unsigned int parent_uses,
1168                         unsigned int parent_copies)
1169 {
1170   if (dump_file && !elt->parent)
1171     {
1172       fputs ("Initial instantiation for ", dump_file);
1173       dump_sra_elt_name (dump_file, elt);
1174       fputc ('\n', dump_file);
1175     }
1176
1177   if (elt->cannot_scalarize)
1178     return;
1179
1180   if (elt->is_scalar)
1181     {
1182       /* The decision is simple: instantiate if we're used more frequently
1183          than the parent needs to be seen as a complete unit.  */
1184       if (elt->n_uses + elt->n_copies + parent_copies > parent_uses)
1185         instantiate_element (elt);
1186     }
1187   else
1188     {
1189       struct sra_elt *c;
1190       unsigned int this_uses = elt->n_uses + parent_uses;
1191       unsigned int this_copies = elt->n_copies + parent_copies;
1192
1193       for (c = elt->children; c ; c = c->sibling)
1194         decide_instantiation_1 (c, this_uses, this_copies);
1195     }
1196 }
1197
1198 /* Compute the size and number of all instantiated elements below ELT.
1199    We will only care about this if the size of the complete structure
1200    fits in a HOST_WIDE_INT, so we don't have to worry about overflow.  */
1201
1202 static unsigned int
1203 sum_instantiated_sizes (struct sra_elt *elt, unsigned HOST_WIDE_INT *sizep)
1204 {
1205   if (elt->replacement)
1206     {
1207       *sizep += TREE_INT_CST_LOW (TYPE_SIZE_UNIT (elt->type));
1208       return 1;
1209     }
1210   else
1211     {
1212       struct sra_elt *c;
1213       unsigned int count = 0;
1214
1215       for (c = elt->children; c ; c = c->sibling)
1216         count += sum_instantiated_sizes (c, sizep);
1217
1218       return count;
1219     }
1220 }
1221
1222 /* Instantiate fields in ELT->TYPE that are not currently present as
1223    children of ELT.  */
1224
1225 static void instantiate_missing_elements (struct sra_elt *elt);
1226
1227 static void
1228 instantiate_missing_elements_1 (struct sra_elt *elt, tree child, tree type)
1229 {
1230   struct sra_elt *sub = lookup_element (elt, child, type, INSERT);
1231   if (sub->is_scalar)
1232     {
1233       if (sub->replacement == NULL)
1234         instantiate_element (sub);
1235     }
1236   else
1237     instantiate_missing_elements (sub);
1238 }
1239
1240 static void
1241 instantiate_missing_elements (struct sra_elt *elt)
1242 {
1243   tree type = elt->type;
1244
1245   switch (TREE_CODE (type))
1246     {
1247     case RECORD_TYPE:
1248       {
1249         tree f;
1250         for (f = TYPE_FIELDS (type); f ; f = TREE_CHAIN (f))
1251           if (TREE_CODE (f) == FIELD_DECL)
1252             instantiate_missing_elements_1 (elt, f, TREE_TYPE (f));
1253         break;
1254       }
1255
1256     case ARRAY_TYPE:
1257       {
1258         tree i, max, subtype;
1259
1260         i = TYPE_MIN_VALUE (TYPE_DOMAIN (type));
1261         max = TYPE_MAX_VALUE (TYPE_DOMAIN (type));
1262         subtype = TREE_TYPE (type);
1263
1264         while (1)
1265           {
1266             instantiate_missing_elements_1 (elt, i, subtype);
1267             if (tree_int_cst_equal (i, max))
1268               break;
1269             i = int_const_binop (PLUS_EXPR, i, integer_one_node, true);
1270           }
1271
1272         break;
1273       }
1274
1275     case COMPLEX_TYPE:
1276       type = TREE_TYPE (type);
1277       instantiate_missing_elements_1 (elt, integer_zero_node, type);
1278       instantiate_missing_elements_1 (elt, integer_one_node, type);
1279       break;
1280
1281     default:
1282       gcc_unreachable ();
1283     }
1284 }
1285
1286 /* Make one pass across an element tree deciding whether to perform block
1287    or element copies.  If we decide on element copies, instantiate all
1288    elements.  Return true if there are any instantiated sub-elements.  */
1289
1290 static bool
1291 decide_block_copy (struct sra_elt *elt)
1292 {
1293   struct sra_elt *c;
1294   bool any_inst;
1295
1296   /* If scalarization is disabled, respect it.  */
1297   if (elt->cannot_scalarize)
1298     {
1299       elt->use_block_copy = 1;
1300
1301       if (dump_file)
1302         {
1303           fputs ("Scalarization disabled for ", dump_file);
1304           dump_sra_elt_name (dump_file, elt);
1305           fputc ('\n', dump_file);
1306         }
1307
1308       /* Disable scalarization of sub-elements */
1309       for (c = elt->children; c; c = c->sibling)
1310         {
1311           c->cannot_scalarize = 1;
1312           decide_block_copy (c);
1313         }
1314       return false;
1315     }
1316
1317   /* Don't decide if we've no uses.  */
1318   if (elt->n_uses == 0 && elt->n_copies == 0)
1319     ;
1320
1321   else if (!elt->is_scalar)
1322     {
1323       tree size_tree = TYPE_SIZE_UNIT (elt->type);
1324       bool use_block_copy = true;
1325
1326       /* Tradeoffs for COMPLEX types pretty much always make it better
1327          to go ahead and split the components.  */
1328       if (TREE_CODE (elt->type) == COMPLEX_TYPE)
1329         use_block_copy = false;
1330
1331       /* Don't bother trying to figure out the rest if the structure is
1332          so large we can't do easy arithmetic.  This also forces block
1333          copies for variable sized structures.  */
1334       else if (host_integerp (size_tree, 1))
1335         {
1336           unsigned HOST_WIDE_INT full_size, inst_size = 0;
1337           unsigned int max_size, max_count, inst_count, full_count;
1338
1339           /* If the sra-max-structure-size parameter is 0, then the
1340              user has not overridden the parameter and we can choose a
1341              sensible default.  */
1342           max_size = SRA_MAX_STRUCTURE_SIZE
1343             ? SRA_MAX_STRUCTURE_SIZE
1344             : MOVE_RATIO * UNITS_PER_WORD;
1345           max_count = SRA_MAX_STRUCTURE_COUNT
1346             ? SRA_MAX_STRUCTURE_COUNT
1347             : MOVE_RATIO;
1348
1349           full_size = tree_low_cst (size_tree, 1);
1350           full_count = count_type_elements (elt->type, false);
1351           inst_count = sum_instantiated_sizes (elt, &inst_size);
1352
1353           /* ??? What to do here.  If there are two fields, and we've only
1354              instantiated one, then instantiating the other is clearly a win.
1355              If there are a large number of fields then the size of the copy
1356              is much more of a factor.  */
1357
1358           /* If the structure is small, and we've made copies, go ahead
1359              and instantiate, hoping that the copies will go away.  */
1360           if (full_size <= max_size
1361               && (full_count - inst_count) <= max_count
1362               && elt->n_copies > elt->n_uses)
1363             use_block_copy = false;
1364           else if (inst_count * 100 >= full_count * SRA_FIELD_STRUCTURE_RATIO
1365                    && inst_size * 100 >= full_size * SRA_FIELD_STRUCTURE_RATIO)
1366             use_block_copy = false;
1367
1368           /* In order to avoid block copy, we have to be able to instantiate
1369              all elements of the type.  See if this is possible.  */
1370           if (!use_block_copy
1371               && (!can_completely_scalarize_p (elt)
1372                   || !type_can_instantiate_all_elements (elt->type)))
1373             use_block_copy = true;
1374         }
1375       elt->use_block_copy = use_block_copy;
1376
1377       if (dump_file)
1378         {
1379           fprintf (dump_file, "Using %s for ",
1380                    use_block_copy ? "block-copy" : "element-copy");
1381           dump_sra_elt_name (dump_file, elt);
1382           fputc ('\n', dump_file);
1383         }
1384
1385       if (!use_block_copy)
1386         {
1387           instantiate_missing_elements (elt);
1388           return true;
1389         }
1390     }
1391
1392   any_inst = elt->replacement != NULL;
1393
1394   for (c = elt->children; c ; c = c->sibling)
1395     any_inst |= decide_block_copy (c);
1396
1397   return any_inst;
1398 }
1399
1400 /* Entry point to phase 3.  Instantiate scalar replacement variables.  */
1401
1402 static void
1403 decide_instantiations (void)
1404 {
1405   unsigned int i;
1406   bool cleared_any;
1407   bitmap_head done_head;
1408   bitmap_iterator bi;
1409
1410   /* We cannot clear bits from a bitmap we're iterating over,
1411      so save up all the bits to clear until the end.  */
1412   bitmap_initialize (&done_head, &bitmap_default_obstack);
1413   cleared_any = false;
1414
1415   EXECUTE_IF_SET_IN_BITMAP (sra_candidates, 0, i, bi)
1416     {
1417       tree var = referenced_var (i);
1418       struct sra_elt *elt = lookup_element (NULL, var, NULL, NO_INSERT);
1419       if (elt)
1420         {
1421           decide_instantiation_1 (elt, 0, 0);
1422           if (!decide_block_copy (elt))
1423             elt = NULL;
1424         }
1425       if (!elt)
1426         {
1427           bitmap_set_bit (&done_head, i);
1428           cleared_any = true;
1429         }
1430     }
1431
1432   if (cleared_any)
1433     {
1434       bitmap_and_compl_into (sra_candidates, &done_head);
1435       bitmap_and_compl_into (needs_copy_in, &done_head);
1436     }
1437   bitmap_clear (&done_head);
1438   
1439   if (!bitmap_empty_p (sra_candidates))
1440     todoflags |= TODO_update_smt_usage;
1441
1442   mark_set_for_renaming (sra_candidates);
1443
1444   if (dump_file)
1445     fputc ('\n', dump_file);
1446 }
1447
1448 \f
1449 /* Phase Four: Update the function to match the replacements created.  */
1450
1451 /* Mark all the variables in V_MAY_DEF or V_MUST_DEF operands for STMT for
1452    renaming. This becomes necessary when we modify all of a non-scalar.  */
1453
1454 static void
1455 mark_all_v_defs_1 (tree stmt)
1456 {
1457   tree sym;
1458   ssa_op_iter iter;
1459
1460   update_stmt_if_modified (stmt);
1461
1462   FOR_EACH_SSA_TREE_OPERAND (sym, stmt, iter, SSA_OP_ALL_VIRTUALS)
1463     {
1464       if (TREE_CODE (sym) == SSA_NAME)
1465         sym = SSA_NAME_VAR (sym);
1466       mark_sym_for_renaming (sym);
1467     }
1468 }
1469
1470
1471 /* Mark all the variables in virtual operands in all the statements in
1472    LIST for renaming.  */
1473
1474 static void
1475 mark_all_v_defs (tree list)
1476 {
1477   if (TREE_CODE (list) != STATEMENT_LIST)
1478     mark_all_v_defs_1 (list);
1479   else
1480     {
1481       tree_stmt_iterator i;
1482       for (i = tsi_start (list); !tsi_end_p (i); tsi_next (&i))
1483         mark_all_v_defs_1 (tsi_stmt (i));
1484     }
1485 }
1486
1487 /* Mark every replacement under ELT with TREE_NO_WARNING.  */
1488
1489 static void
1490 mark_no_warning (struct sra_elt *elt)
1491 {
1492   if (!elt->all_no_warning)
1493     {
1494       if (elt->replacement)
1495         TREE_NO_WARNING (elt->replacement) = 1;
1496       else
1497         {
1498           struct sra_elt *c;
1499           for (c = elt->children; c ; c = c->sibling)
1500             mark_no_warning (c);
1501         }
1502     }
1503 }
1504
1505 /* Build a single level component reference to ELT rooted at BASE.  */
1506
1507 static tree
1508 generate_one_element_ref (struct sra_elt *elt, tree base)
1509 {
1510   switch (TREE_CODE (TREE_TYPE (base)))
1511     {
1512     case RECORD_TYPE:
1513       {
1514         tree field = elt->element;
1515
1516         /* Watch out for compatible records with differing field lists.  */
1517         if (DECL_FIELD_CONTEXT (field) != TYPE_MAIN_VARIANT (TREE_TYPE (base)))
1518           field = find_compatible_field (TREE_TYPE (base), field);
1519
1520         return build3 (COMPONENT_REF, elt->type, base, field, NULL);
1521       }
1522
1523     case ARRAY_TYPE:
1524       todoflags |= TODO_update_smt_usage;
1525       return build4 (ARRAY_REF, elt->type, base, elt->element, NULL, NULL);
1526
1527     case COMPLEX_TYPE:
1528       if (elt->element == integer_zero_node)
1529         return build1 (REALPART_EXPR, elt->type, base);
1530       else
1531         return build1 (IMAGPART_EXPR, elt->type, base);
1532
1533     default:
1534       gcc_unreachable ();
1535     }
1536 }
1537
1538 /* Build a full component reference to ELT rooted at its native variable.  */
1539
1540 static tree
1541 generate_element_ref (struct sra_elt *elt)
1542 {
1543   if (elt->parent)
1544     return generate_one_element_ref (elt, generate_element_ref (elt->parent));
1545   else
1546     return elt->element;
1547 }
1548
1549 /* Generate a set of assignment statements in *LIST_P to copy all
1550    instantiated elements under ELT to or from the equivalent structure
1551    rooted at EXPR.  COPY_OUT controls the direction of the copy, with
1552    true meaning to copy out of EXPR into ELT.  */
1553
1554 static void
1555 generate_copy_inout (struct sra_elt *elt, bool copy_out, tree expr,
1556                      tree *list_p)
1557 {
1558   struct sra_elt *c;
1559   tree t;
1560
1561   if (!copy_out && TREE_CODE (expr) == SSA_NAME
1562       && TREE_CODE (TREE_TYPE (expr)) == COMPLEX_TYPE)
1563     {
1564       tree r, i;
1565
1566       c = lookup_element (elt, integer_zero_node, NULL, NO_INSERT);
1567       r = c->replacement;
1568       c = lookup_element (elt, integer_one_node, NULL, NO_INSERT);
1569       i = c->replacement;
1570
1571       t = build2 (COMPLEX_EXPR, elt->type, r, i);
1572       t = build2 (MODIFY_EXPR, void_type_node, expr, t);
1573       SSA_NAME_DEF_STMT (expr) = t;
1574       append_to_statement_list (t, list_p);
1575     }
1576   else if (elt->replacement)
1577     {
1578       if (copy_out)
1579         t = build2 (MODIFY_EXPR, void_type_node, elt->replacement, expr);
1580       else
1581         t = build2 (MODIFY_EXPR, void_type_node, expr, elt->replacement);
1582       append_to_statement_list (t, list_p);
1583     }
1584   else
1585     {
1586       for (c = elt->children; c ; c = c->sibling)
1587         {
1588           t = generate_one_element_ref (c, unshare_expr (expr));
1589           generate_copy_inout (c, copy_out, t, list_p);
1590         }
1591     }
1592 }
1593
1594 /* Generate a set of assignment statements in *LIST_P to copy all instantiated
1595    elements under SRC to their counterparts under DST.  There must be a 1-1
1596    correspondence of instantiated elements.  */
1597
1598 static void
1599 generate_element_copy (struct sra_elt *dst, struct sra_elt *src, tree *list_p)
1600 {
1601   struct sra_elt *dc, *sc;
1602
1603   for (dc = dst->children; dc ; dc = dc->sibling)
1604     {
1605       sc = lookup_element (src, dc->element, NULL, NO_INSERT);
1606       gcc_assert (sc);
1607       generate_element_copy (dc, sc, list_p);
1608     }
1609
1610   if (dst->replacement)
1611     {
1612       tree t;
1613
1614       gcc_assert (src->replacement);
1615
1616       t = build2 (MODIFY_EXPR, void_type_node, dst->replacement,
1617                   src->replacement);
1618       append_to_statement_list (t, list_p);
1619     }
1620 }
1621
1622 /* Generate a set of assignment statements in *LIST_P to zero all instantiated
1623    elements under ELT.  In addition, do not assign to elements that have been
1624    marked VISITED but do reset the visited flag; this allows easy coordination
1625    with generate_element_init.  */
1626
1627 static void
1628 generate_element_zero (struct sra_elt *elt, tree *list_p)
1629 {
1630   struct sra_elt *c;
1631
1632   if (elt->visited)
1633     {
1634       elt->visited = false;
1635       return;
1636     }
1637
1638   for (c = elt->children; c ; c = c->sibling)
1639     generate_element_zero (c, list_p);
1640
1641   if (elt->replacement)
1642     {
1643       tree t;
1644
1645       gcc_assert (elt->is_scalar);
1646       t = fold_convert (elt->type, integer_zero_node);
1647
1648       t = build2 (MODIFY_EXPR, void_type_node, elt->replacement, t);
1649       append_to_statement_list (t, list_p);
1650     }
1651 }
1652
1653 /* Generate an assignment VAR = INIT, where INIT may need gimplification.
1654    Add the result to *LIST_P.  */
1655
1656 static void
1657 generate_one_element_init (tree var, tree init, tree *list_p)
1658 {
1659   /* The replacement can be almost arbitrarily complex.  Gimplify.  */
1660   tree stmt = build2 (MODIFY_EXPR, void_type_node, var, init);
1661   gimplify_and_add (stmt, list_p);
1662 }
1663
1664 /* Generate a set of assignment statements in *LIST_P to set all instantiated
1665    elements under ELT with the contents of the initializer INIT.  In addition,
1666    mark all assigned elements VISITED; this allows easy coordination with
1667    generate_element_zero.  Return false if we found a case we couldn't
1668    handle.  */
1669
1670 static bool
1671 generate_element_init_1 (struct sra_elt *elt, tree init, tree *list_p)
1672 {
1673   bool result = true;
1674   enum tree_code init_code;
1675   struct sra_elt *sub;
1676   tree t;
1677   unsigned HOST_WIDE_INT idx;
1678   tree value, purpose;
1679
1680   /* We can be passed DECL_INITIAL of a static variable.  It might have a
1681      conversion, which we strip off here.  */
1682   STRIP_USELESS_TYPE_CONVERSION (init);
1683   init_code = TREE_CODE (init);
1684
1685   if (elt->is_scalar)
1686     {
1687       if (elt->replacement)
1688         {
1689           generate_one_element_init (elt->replacement, init, list_p);
1690           elt->visited = true;
1691         }
1692       return result;
1693     }
1694
1695   switch (init_code)
1696     {
1697     case COMPLEX_CST:
1698     case COMPLEX_EXPR:
1699       for (sub = elt->children; sub ; sub = sub->sibling)
1700         {
1701           if (sub->element == integer_zero_node)
1702             t = (init_code == COMPLEX_EXPR
1703                  ? TREE_OPERAND (init, 0) : TREE_REALPART (init));
1704           else
1705             t = (init_code == COMPLEX_EXPR
1706                  ? TREE_OPERAND (init, 1) : TREE_IMAGPART (init));
1707           result &= generate_element_init_1 (sub, t, list_p);
1708         }
1709       break;
1710
1711     case CONSTRUCTOR:
1712       FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (init), idx, purpose, value)
1713         {
1714           if (TREE_CODE (purpose) == RANGE_EXPR)
1715             {
1716               tree lower = TREE_OPERAND (purpose, 0);
1717               tree upper = TREE_OPERAND (purpose, 1);
1718
1719               while (1)
1720                 {
1721                   sub = lookup_element (elt, lower, NULL, NO_INSERT);
1722                   if (sub != NULL)
1723                     result &= generate_element_init_1 (sub, value, list_p);
1724                   if (tree_int_cst_equal (lower, upper))
1725                     break;
1726                   lower = int_const_binop (PLUS_EXPR, lower,
1727                                            integer_one_node, true);
1728                 }
1729             }
1730           else
1731             {
1732               sub = lookup_element (elt, purpose, NULL, NO_INSERT);
1733               if (sub != NULL)
1734                 result &= generate_element_init_1 (sub, value, list_p);
1735             }
1736         }
1737       break;
1738
1739     default:
1740       elt->visited = true;
1741       result = false;
1742     }
1743
1744   return result;
1745 }
1746
1747 /* A wrapper function for generate_element_init_1 that handles cleanup after
1748    gimplification.  */
1749
1750 static bool
1751 generate_element_init (struct sra_elt *elt, tree init, tree *list_p)
1752 {
1753   bool ret;
1754
1755   push_gimplify_context ();
1756   ret = generate_element_init_1 (elt, init, list_p);
1757   pop_gimplify_context (NULL);
1758
1759   /* The replacement can expose previously unreferenced variables.  */
1760   if (ret && *list_p)
1761     {
1762       tree_stmt_iterator i;
1763
1764       for (i = tsi_start (*list_p); !tsi_end_p (i); tsi_next (&i))
1765         find_new_referenced_vars (tsi_stmt_ptr (i));
1766     }
1767
1768   return ret;
1769 }
1770
1771 /* Insert STMT on all the outgoing edges out of BB.  Note that if BB
1772    has more than one edge, STMT will be replicated for each edge.  Also,
1773    abnormal edges will be ignored.  */
1774
1775 void
1776 insert_edge_copies (tree stmt, basic_block bb)
1777 {
1778   edge e;
1779   edge_iterator ei;
1780   bool first_copy;
1781
1782   first_copy = true;
1783   FOR_EACH_EDGE (e, ei, bb->succs)
1784     {
1785       /* We don't need to insert copies on abnormal edges.  The
1786          value of the scalar replacement is not guaranteed to
1787          be valid through an abnormal edge.  */
1788       if (!(e->flags & EDGE_ABNORMAL))
1789         {
1790           if (first_copy)
1791             {
1792               bsi_insert_on_edge (e, stmt);
1793               first_copy = false;
1794             }
1795           else
1796             bsi_insert_on_edge (e, unsave_expr_now (stmt));
1797         }
1798     }
1799 }
1800
1801 /* Helper function to insert LIST before BSI, and set up line number info.  */
1802
1803 void
1804 sra_insert_before (block_stmt_iterator *bsi, tree list)
1805 {
1806   tree stmt = bsi_stmt (*bsi);
1807
1808   if (EXPR_HAS_LOCATION (stmt))
1809     annotate_all_with_locus (&list, EXPR_LOCATION (stmt));
1810   bsi_insert_before (bsi, list, BSI_SAME_STMT);
1811 }
1812
1813 /* Similarly, but insert after BSI.  Handles insertion onto edges as well.  */
1814
1815 void
1816 sra_insert_after (block_stmt_iterator *bsi, tree list)
1817 {
1818   tree stmt = bsi_stmt (*bsi);
1819
1820   if (EXPR_HAS_LOCATION (stmt))
1821     annotate_all_with_locus (&list, EXPR_LOCATION (stmt));
1822
1823   if (stmt_ends_bb_p (stmt))
1824     insert_edge_copies (list, bsi->bb);
1825   else
1826     bsi_insert_after (bsi, list, BSI_SAME_STMT);
1827 }
1828
1829 /* Similarly, but replace the statement at BSI.  */
1830
1831 static void
1832 sra_replace (block_stmt_iterator *bsi, tree list)
1833 {
1834   sra_insert_before (bsi, list);
1835   bsi_remove (bsi, false);
1836   if (bsi_end_p (*bsi))
1837     *bsi = bsi_last (bsi->bb);
1838   else
1839     bsi_prev (bsi);
1840 }
1841
1842 /* Scalarize a USE.  To recap, this is either a simple reference to ELT,
1843    if elt is scalar, or some occurrence of ELT that requires a complete
1844    aggregate.  IS_OUTPUT is true if ELT is being modified.  */
1845
1846 static void
1847 scalarize_use (struct sra_elt *elt, tree *expr_p, block_stmt_iterator *bsi,
1848                bool is_output, bool use_all)
1849 {
1850   tree list = NULL, stmt = bsi_stmt (*bsi);
1851
1852   if (elt->replacement)
1853     {
1854       /* If we have a replacement, then updating the reference is as
1855          simple as modifying the existing statement in place.  */
1856       if (is_output)
1857         mark_all_v_defs (stmt);
1858       *expr_p = elt->replacement;
1859       update_stmt (stmt);
1860     }
1861   else
1862     {
1863       /* Otherwise we need some copies.  If ELT is being read, then we want
1864          to store all (modified) sub-elements back into the structure before
1865          the reference takes place.  If ELT is being written, then we want to
1866          load the changed values back into our shadow variables.  */
1867       /* ??? We don't check modified for reads, we just always write all of
1868          the values.  We should be able to record the SSA number of the VOP
1869          for which the values were last read.  If that number matches the
1870          SSA number of the VOP in the current statement, then we needn't
1871          emit an assignment.  This would also eliminate double writes when
1872          a structure is passed as more than one argument to a function call.
1873          This optimization would be most effective if sra_walk_function
1874          processed the blocks in dominator order.  */
1875
1876       generate_copy_inout (elt, is_output, generate_element_ref (elt), &list);
1877       if (list == NULL)
1878         return;
1879       mark_all_v_defs (list);
1880       if (is_output)
1881         sra_insert_after (bsi, list);
1882       else
1883         {
1884           sra_insert_before (bsi, list);
1885           if (use_all)
1886             mark_no_warning (elt);
1887         }
1888     }
1889 }
1890
1891 /* Scalarize a COPY.  To recap, this is an assignment statement between
1892    two scalarizable references, LHS_ELT and RHS_ELT.  */
1893
1894 static void
1895 scalarize_copy (struct sra_elt *lhs_elt, struct sra_elt *rhs_elt,
1896                 block_stmt_iterator *bsi)
1897 {
1898   tree list, stmt;
1899
1900   if (lhs_elt->replacement && rhs_elt->replacement)
1901     {
1902       /* If we have two scalar operands, modify the existing statement.  */
1903       stmt = bsi_stmt (*bsi);
1904
1905       /* See the commentary in sra_walk_function concerning
1906          RETURN_EXPR, and why we should never see one here.  */
1907       gcc_assert (TREE_CODE (stmt) == MODIFY_EXPR);
1908
1909       TREE_OPERAND (stmt, 0) = lhs_elt->replacement;
1910       TREE_OPERAND (stmt, 1) = rhs_elt->replacement;
1911       update_stmt (stmt);
1912     }
1913   else if (lhs_elt->use_block_copy || rhs_elt->use_block_copy)
1914     {
1915       /* If either side requires a block copy, then sync the RHS back
1916          to the original structure, leave the original assignment
1917          statement (which will perform the block copy), then load the
1918          LHS values out of its now-updated original structure.  */
1919       /* ??? Could perform a modified pair-wise element copy.  That
1920          would at least allow those elements that are instantiated in
1921          both structures to be optimized well.  */
1922
1923       list = NULL;
1924       generate_copy_inout (rhs_elt, false,
1925                            generate_element_ref (rhs_elt), &list);
1926       if (list)
1927         {
1928           mark_all_v_defs (list);
1929           sra_insert_before (bsi, list);
1930         }
1931
1932       list = NULL;
1933       generate_copy_inout (lhs_elt, true,
1934                            generate_element_ref (lhs_elt), &list);
1935       if (list)
1936         {
1937           mark_all_v_defs (list);
1938           sra_insert_after (bsi, list);
1939         }
1940     }
1941   else
1942     {
1943       /* Otherwise both sides must be fully instantiated.  In which
1944          case perform pair-wise element assignments and replace the
1945          original block copy statement.  */
1946
1947       stmt = bsi_stmt (*bsi);
1948       mark_all_v_defs (stmt);
1949
1950       list = NULL;
1951       generate_element_copy (lhs_elt, rhs_elt, &list);
1952       gcc_assert (list);
1953       mark_all_v_defs (list);
1954       sra_replace (bsi, list);
1955     }
1956 }
1957
1958 /* Scalarize an INIT.  To recap, this is an assignment to a scalarizable
1959    reference from some form of constructor: CONSTRUCTOR, COMPLEX_CST or
1960    COMPLEX_EXPR.  If RHS is NULL, it should be treated as an empty
1961    CONSTRUCTOR.  */
1962
1963 static void
1964 scalarize_init (struct sra_elt *lhs_elt, tree rhs, block_stmt_iterator *bsi)
1965 {
1966   bool result = true;
1967   tree list = NULL;
1968
1969   /* Generate initialization statements for all members extant in the RHS.  */
1970   if (rhs)
1971     {
1972       /* Unshare the expression just in case this is from a decl's initial.  */
1973       rhs = unshare_expr (rhs);
1974       result = generate_element_init (lhs_elt, rhs, &list);
1975     }
1976
1977   /* CONSTRUCTOR is defined such that any member not mentioned is assigned
1978      a zero value.  Initialize the rest of the instantiated elements.  */
1979   generate_element_zero (lhs_elt, &list);
1980
1981   if (!result)
1982     {
1983       /* If we failed to convert the entire initializer, then we must
1984          leave the structure assignment in place and must load values
1985          from the structure into the slots for which we did not find
1986          constants.  The easiest way to do this is to generate a complete
1987          copy-out, and then follow that with the constant assignments
1988          that we were able to build.  DCE will clean things up.  */
1989       tree list0 = NULL;
1990       generate_copy_inout (lhs_elt, true, generate_element_ref (lhs_elt),
1991                            &list0);
1992       append_to_statement_list (list, &list0);
1993       list = list0;
1994     }
1995
1996   if (lhs_elt->use_block_copy || !result)
1997     {
1998       /* Since LHS is not fully instantiated, we must leave the structure
1999          assignment in place.  Treating this case differently from a USE
2000          exposes constants to later optimizations.  */
2001       if (list)
2002         {
2003           mark_all_v_defs (list);
2004           sra_insert_after (bsi, list);
2005         }
2006     }
2007   else
2008     {
2009       /* The LHS is fully instantiated.  The list of initializations
2010          replaces the original structure assignment.  */
2011       gcc_assert (list);
2012       mark_all_v_defs (bsi_stmt (*bsi));
2013       mark_all_v_defs (list);
2014       sra_replace (bsi, list);
2015     }
2016 }
2017
2018 /* A subroutine of scalarize_ldst called via walk_tree.  Set TREE_NO_TRAP
2019    on all INDIRECT_REFs.  */
2020
2021 static tree
2022 mark_notrap (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
2023 {
2024   tree t = *tp;
2025
2026   if (TREE_CODE (t) == INDIRECT_REF)
2027     {
2028       TREE_THIS_NOTRAP (t) = 1;
2029       *walk_subtrees = 0;
2030     }
2031   else if (IS_TYPE_OR_DECL_P (t))
2032     *walk_subtrees = 0;
2033
2034   return NULL;
2035 }
2036
2037 /* Scalarize a LDST.  To recap, this is an assignment between one scalarizable
2038    reference ELT and one non-scalarizable reference OTHER.  IS_OUTPUT is true
2039    if ELT is on the left-hand side.  */
2040
2041 static void
2042 scalarize_ldst (struct sra_elt *elt, tree other,
2043                 block_stmt_iterator *bsi, bool is_output)
2044 {
2045   /* Shouldn't have gotten called for a scalar.  */
2046   gcc_assert (!elt->replacement);
2047
2048   if (elt->use_block_copy)
2049     {
2050       /* Since ELT is not fully instantiated, we have to leave the
2051          block copy in place.  Treat this as a USE.  */
2052       scalarize_use (elt, NULL, bsi, is_output, false);
2053     }
2054   else
2055     {
2056       /* The interesting case is when ELT is fully instantiated.  In this
2057          case we can have each element stored/loaded directly to/from the
2058          corresponding slot in OTHER.  This avoids a block copy.  */
2059
2060       tree list = NULL, stmt = bsi_stmt (*bsi);
2061
2062       mark_all_v_defs (stmt);
2063       generate_copy_inout (elt, is_output, other, &list);
2064       mark_all_v_defs (list);
2065       gcc_assert (list);
2066
2067       /* Preserve EH semantics.  */
2068       if (stmt_ends_bb_p (stmt))
2069         {
2070           tree_stmt_iterator tsi;
2071           tree first;
2072
2073           /* Extract the first statement from LIST.  */
2074           tsi = tsi_start (list);
2075           first = tsi_stmt (tsi);
2076           tsi_delink (&tsi);
2077
2078           /* Replace the old statement with this new representative.  */
2079           bsi_replace (bsi, first, true);
2080
2081           if (!tsi_end_p (tsi))
2082             {
2083               /* If any reference would trap, then they all would.  And more
2084                  to the point, the first would.  Therefore none of the rest
2085                  will trap since the first didn't.  Indicate this by
2086                  iterating over the remaining statements and set
2087                  TREE_THIS_NOTRAP in all INDIRECT_REFs.  */
2088               do
2089                 {
2090                   walk_tree (tsi_stmt_ptr (tsi), mark_notrap, NULL, NULL);
2091                   tsi_next (&tsi);
2092                 }
2093               while (!tsi_end_p (tsi));
2094
2095               insert_edge_copies (list, bsi->bb);
2096             }
2097         }
2098       else
2099         sra_replace (bsi, list);
2100     }
2101 }
2102
2103 /* Generate initializations for all scalarizable parameters.  */
2104
2105 static void
2106 scalarize_parms (void)
2107 {
2108   tree list = NULL;
2109   unsigned i;
2110   bitmap_iterator bi;
2111
2112   EXECUTE_IF_SET_IN_BITMAP (needs_copy_in, 0, i, bi)
2113     {
2114       tree var = referenced_var (i);
2115       struct sra_elt *elt = lookup_element (NULL, var, NULL, NO_INSERT);
2116       generate_copy_inout (elt, true, var, &list);
2117     }
2118
2119   if (list)
2120     {
2121       insert_edge_copies (list, ENTRY_BLOCK_PTR);
2122       mark_all_v_defs (list);
2123     }
2124 }
2125
2126 /* Entry point to phase 4.  Update the function to match replacements.  */
2127
2128 static void
2129 scalarize_function (void)
2130 {
2131   static const struct sra_walk_fns fns = {
2132     scalarize_use, scalarize_copy, scalarize_init, scalarize_ldst, false
2133   };
2134
2135   sra_walk_function (&fns);
2136   scalarize_parms ();
2137   bsi_commit_edge_inserts ();
2138 }
2139
2140 \f
2141 /* Debug helper function.  Print ELT in a nice human-readable format.  */
2142
2143 static void
2144 dump_sra_elt_name (FILE *f, struct sra_elt *elt)
2145 {
2146   if (elt->parent && TREE_CODE (elt->parent->type) == COMPLEX_TYPE)
2147     {
2148       fputs (elt->element == integer_zero_node ? "__real__ " : "__imag__ ", f);
2149       dump_sra_elt_name (f, elt->parent);
2150     }
2151   else
2152     {
2153       if (elt->parent)
2154         dump_sra_elt_name (f, elt->parent);
2155       if (DECL_P (elt->element))
2156         {
2157           if (TREE_CODE (elt->element) == FIELD_DECL)
2158             fputc ('.', f);
2159           print_generic_expr (f, elt->element, dump_flags);
2160         }
2161       else
2162         fprintf (f, "[" HOST_WIDE_INT_PRINT_DEC "]",
2163                  TREE_INT_CST_LOW (elt->element));
2164     }
2165 }
2166
2167 /* Likewise, but callable from the debugger.  */
2168
2169 void
2170 debug_sra_elt_name (struct sra_elt *elt)
2171 {
2172   dump_sra_elt_name (stderr, elt);
2173   fputc ('\n', stderr);
2174 }
2175
2176 void 
2177 sra_init_cache (void)
2178 {
2179   if (sra_type_decomp_cache) 
2180     return;
2181
2182   sra_type_decomp_cache = BITMAP_ALLOC (NULL);
2183   sra_type_inst_cache = BITMAP_ALLOC (NULL);
2184 }
2185
2186 /* Main entry point.  */
2187
2188 static unsigned int
2189 tree_sra (void)
2190 {
2191   /* Initialize local variables.  */
2192   todoflags = 0;
2193   gcc_obstack_init (&sra_obstack);
2194   sra_candidates = BITMAP_ALLOC (NULL);
2195   needs_copy_in = BITMAP_ALLOC (NULL);
2196   sra_init_cache ();
2197   sra_map = htab_create (101, sra_elt_hash, sra_elt_eq, NULL);
2198
2199   /* Scan.  If we find anything, instantiate and scalarize.  */
2200   if (find_candidates_for_sra ())
2201     {
2202       scan_function ();
2203       decide_instantiations ();
2204       scalarize_function ();
2205     }
2206
2207   /* Free allocated memory.  */
2208   htab_delete (sra_map);
2209   sra_map = NULL;
2210   BITMAP_FREE (sra_candidates);
2211   BITMAP_FREE (needs_copy_in);
2212   BITMAP_FREE (sra_type_decomp_cache);
2213   BITMAP_FREE (sra_type_inst_cache);
2214   obstack_free (&sra_obstack, NULL);
2215   return todoflags;
2216 }
2217
2218 static bool
2219 gate_sra (void)
2220 {
2221   return flag_tree_sra != 0;
2222 }
2223
2224 struct tree_opt_pass pass_sra =
2225 {
2226   "sra",                                /* name */
2227   gate_sra,                             /* gate */
2228   tree_sra,                             /* execute */
2229   NULL,                                 /* sub */
2230   NULL,                                 /* next */
2231   0,                                    /* static_pass_number */
2232   TV_TREE_SRA,                          /* tv_id */
2233   PROP_cfg | PROP_ssa | PROP_alias,     /* properties_required */
2234   0,                                    /* properties_provided */
2235   PROP_smt_usage,                       /* properties_destroyed */
2236   0,                                    /* todo_flags_start */
2237   TODO_dump_func /* todo_flags_finish */
2238   | TODO_update_ssa
2239   | TODO_ggc_collect | TODO_verify_ssa,
2240   0                                     /* letter */
2241 };