OSDN Git Service

Daily bump.
[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, 2007, 2008
5      Free Software Foundation, Inc.
6    Contributed by Diego Novillo <dnovillo@redhat.com>
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify it
11 under the terms of the GNU General Public License as published by the
12 Free Software Foundation; either version 3, or (at your option) any
13 later version.
14
15 GCC is distributed in the hope that it will be useful, but WITHOUT
16 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
17 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
18 for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
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 /* True if this is the "early" pass, before inlining.  */
79 static bool early_sra;
80
81 /* The set of todo flags to return from tree_sra.  */
82 static unsigned int todoflags;
83
84 /* The set of aggregate variables that are candidates for scalarization.  */
85 static bitmap sra_candidates;
86
87 /* Set of scalarizable PARM_DECLs that need copy-in operations at the
88    beginning of the function.  */
89 static bitmap needs_copy_in;
90
91 /* Sets of bit pairs that cache type decomposition and instantiation.  */
92 static bitmap sra_type_decomp_cache;
93 static bitmap sra_type_inst_cache;
94
95 /* One of these structures is created for each candidate aggregate and
96    each (accessed) member or group of members of such an aggregate.  */
97 struct sra_elt
98 {
99   /* A tree of the elements.  Used when we want to traverse everything.  */
100   struct sra_elt *parent;
101   struct sra_elt *groups;
102   struct sra_elt *children;
103   struct sra_elt *sibling;
104
105   /* If this element is a root, then this is the VAR_DECL.  If this is
106      a sub-element, this is some token used to identify the reference.
107      In the case of COMPONENT_REF, this is the FIELD_DECL.  In the case
108      of an ARRAY_REF, this is the (constant) index.  In the case of an
109      ARRAY_RANGE_REF, this is the (constant) RANGE_EXPR.  In the case
110      of a complex number, this is a zero or one.  */
111   tree element;
112
113   /* The type of the element.  */
114   tree type;
115
116   /* A VAR_DECL, for any sub-element we've decided to replace.  */
117   tree replacement;
118
119   /* The number of times the element is referenced as a whole.  I.e.
120      given "a.b.c", this would be incremented for C, but not for A or B.  */
121   unsigned int n_uses;
122
123   /* The number of times the element is copied to or from another
124      scalarizable element.  */
125   unsigned int n_copies;
126
127   /* True if TYPE is scalar.  */
128   bool is_scalar;
129
130   /* True if this element is a group of members of its parent.  */
131   bool is_group;
132
133   /* True if we saw something about this element that prevents scalarization,
134      such as non-constant indexing.  */
135   bool cannot_scalarize;
136
137   /* True if we've decided that structure-to-structure assignment
138      should happen via memcpy and not per-element.  */
139   bool use_block_copy;
140
141   /* True if everything under this element has been marked TREE_NO_WARNING.  */
142   bool all_no_warning;
143
144   /* A flag for use with/after random access traversals.  */
145   bool visited;
146
147   /* True if there is BIT_FIELD_REF on the lhs with a vector. */
148   bool is_vector_lhs;
149
150   /* 1 if the element is a field that is part of a block, 2 if the field
151      is the block itself, 0 if it's neither.  */
152   char in_bitfld_block;
153 };
154
155 #define IS_ELEMENT_FOR_GROUP(ELEMENT) (TREE_CODE (ELEMENT) == RANGE_EXPR)
156
157 #define FOR_EACH_ACTUAL_CHILD(CHILD, ELT)                       \
158   for ((CHILD) = (ELT)->is_group                                \
159                  ? next_child_for_group (NULL, (ELT))           \
160                  : (ELT)->children;                             \
161        (CHILD);                                                 \
162        (CHILD) = (ELT)->is_group                                \
163                  ? next_child_for_group ((CHILD), (ELT))        \
164                  : (CHILD)->sibling)
165
166 /* Helper function for above macro.  Return next child in group.  */
167 static struct sra_elt *
168 next_child_for_group (struct sra_elt *child, struct sra_elt *group)
169 {
170   gcc_assert (group->is_group);
171
172   /* Find the next child in the parent.  */
173   if (child)
174     child = child->sibling;
175   else
176     child = group->parent->children;
177
178   /* Skip siblings that do not belong to the group.  */
179   while (child)
180     {
181       tree g_elt = group->element;
182       if (TREE_CODE (g_elt) == RANGE_EXPR)
183         {
184           if (!tree_int_cst_lt (child->element, TREE_OPERAND (g_elt, 0))
185               && !tree_int_cst_lt (TREE_OPERAND (g_elt, 1), child->element))
186             break;
187         }
188       else
189         gcc_unreachable ();
190
191       child = child->sibling;
192     }
193
194   return child;
195 }
196
197 /* Random access to the child of a parent is performed by hashing.
198    This prevents quadratic behavior, and allows SRA to function
199    reasonably on larger records.  */
200 static htab_t sra_map;
201
202 /* All structures are allocated out of the following obstack.  */
203 static struct obstack sra_obstack;
204
205 /* Debugging functions.  */
206 static void dump_sra_elt_name (FILE *, struct sra_elt *);
207 extern void debug_sra_elt_name (struct sra_elt *);
208
209 /* Forward declarations.  */
210 static tree generate_element_ref (struct sra_elt *);
211 static tree sra_build_assignment (tree dst, tree src);
212 static void mark_all_v_defs (tree list);
213
214 \f
215 /* Return true if DECL is an SRA candidate.  */
216
217 static bool
218 is_sra_candidate_decl (tree decl)
219 {
220   return DECL_P (decl) && bitmap_bit_p (sra_candidates, DECL_UID (decl));
221 }
222
223 /* Return true if TYPE is a scalar type.  */
224
225 static bool
226 is_sra_scalar_type (tree type)
227 {
228   enum tree_code code = TREE_CODE (type);
229   return (code == INTEGER_TYPE || code == REAL_TYPE || code == VECTOR_TYPE
230           || code == FIXED_POINT_TYPE
231           || code == ENUMERAL_TYPE || code == BOOLEAN_TYPE
232           || code == POINTER_TYPE || code == OFFSET_TYPE
233           || code == REFERENCE_TYPE);
234 }
235
236 /* Return true if TYPE can be decomposed into a set of independent variables.
237
238    Note that this doesn't imply that all elements of TYPE can be
239    instantiated, just that if we decide to break up the type into
240    separate pieces that it can be done.  */
241
242 bool
243 sra_type_can_be_decomposed_p (tree type)
244 {
245   unsigned int cache = TYPE_UID (TYPE_MAIN_VARIANT (type)) * 2;
246   tree t;
247
248   /* Avoid searching the same type twice.  */
249   if (bitmap_bit_p (sra_type_decomp_cache, cache+0))
250     return true;
251   if (bitmap_bit_p (sra_type_decomp_cache, cache+1))
252     return false;
253
254   /* The type must have a definite nonzero size.  */
255   if (TYPE_SIZE (type) == NULL || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST
256       || integer_zerop (TYPE_SIZE (type)))
257     goto fail;
258
259   /* The type must be a non-union aggregate.  */
260   switch (TREE_CODE (type))
261     {
262     case RECORD_TYPE:
263       {
264         bool saw_one_field = false;
265
266         for (t = TYPE_FIELDS (type); t ; t = TREE_CHAIN (t))
267           if (TREE_CODE (t) == FIELD_DECL)
268             {
269               /* Reject incorrectly represented bit fields.  */
270               if (DECL_BIT_FIELD (t)
271                   && INTEGRAL_TYPE_P (TREE_TYPE (t))
272                   && (tree_low_cst (DECL_SIZE (t), 1)
273                       != TYPE_PRECISION (TREE_TYPE (t))))
274                 goto fail;
275
276               saw_one_field = true;
277             }
278
279         /* Record types must have at least one field.  */
280         if (!saw_one_field)
281           goto fail;
282       }
283       break;
284
285     case ARRAY_TYPE:
286       /* Array types must have a fixed lower and upper bound.  */
287       t = TYPE_DOMAIN (type);
288       if (t == NULL)
289         goto fail;
290       if (TYPE_MIN_VALUE (t) == NULL || !TREE_CONSTANT (TYPE_MIN_VALUE (t)))
291         goto fail;
292       if (TYPE_MAX_VALUE (t) == NULL || !TREE_CONSTANT (TYPE_MAX_VALUE (t)))
293         goto fail;
294       break;
295
296     case COMPLEX_TYPE:
297       break;
298
299     default:
300       goto fail;
301     }
302
303   bitmap_set_bit (sra_type_decomp_cache, cache+0);
304   return true;
305
306  fail:
307   bitmap_set_bit (sra_type_decomp_cache, cache+1);
308   return false;
309 }
310
311 /* Return true if DECL can be decomposed into a set of independent
312    (though not necessarily scalar) variables.  */
313
314 static bool
315 decl_can_be_decomposed_p (tree var)
316 {
317   /* Early out for scalars.  */
318   if (is_sra_scalar_type (TREE_TYPE (var)))
319     return false;
320
321   /* The variable must not be aliased.  */
322   if (!is_gimple_non_addressable (var))
323     {
324       if (dump_file && (dump_flags & TDF_DETAILS))
325         {
326           fprintf (dump_file, "Cannot scalarize variable ");
327           print_generic_expr (dump_file, var, dump_flags);
328           fprintf (dump_file, " because it must live in memory\n");
329         }
330       return false;
331     }
332
333   /* The variable must not be volatile.  */
334   if (TREE_THIS_VOLATILE (var))
335     {
336       if (dump_file && (dump_flags & TDF_DETAILS))
337         {
338           fprintf (dump_file, "Cannot scalarize variable ");
339           print_generic_expr (dump_file, var, dump_flags);
340           fprintf (dump_file, " because it is declared volatile\n");
341         }
342       return false;
343     }
344
345   /* We must be able to decompose the variable's type.  */
346   if (!sra_type_can_be_decomposed_p (TREE_TYPE (var)))
347     {
348       if (dump_file && (dump_flags & TDF_DETAILS))
349         {
350           fprintf (dump_file, "Cannot scalarize variable ");
351           print_generic_expr (dump_file, var, dump_flags);
352           fprintf (dump_file, " because its type cannot be decomposed\n");
353         }
354       return false;
355     }
356
357   /* HACK: if we decompose a va_list_type_node before inlining, then we'll
358      confuse tree-stdarg.c, and we won't be able to figure out which and
359      how many arguments are accessed.  This really should be improved in
360      tree-stdarg.c, as the decomposition is truly a win.  This could also
361      be fixed if the stdarg pass ran early, but this can't be done until
362      we've aliasing information early too.  See PR 30791.  */
363   if (early_sra
364       && TYPE_MAIN_VARIANT (TREE_TYPE (var))
365          == TYPE_MAIN_VARIANT (va_list_type_node))
366     return false;
367
368   return true;
369 }
370
371 /* Return true if TYPE can be *completely* decomposed into scalars.  */
372
373 static bool
374 type_can_instantiate_all_elements (tree type)
375 {
376   if (is_sra_scalar_type (type))
377     return true;
378   if (!sra_type_can_be_decomposed_p (type))
379     return false;
380
381   switch (TREE_CODE (type))
382     {
383     case RECORD_TYPE:
384       {
385         unsigned int cache = TYPE_UID (TYPE_MAIN_VARIANT (type)) * 2;
386         tree f;
387
388         if (bitmap_bit_p (sra_type_inst_cache, cache+0))
389           return true;
390         if (bitmap_bit_p (sra_type_inst_cache, cache+1))
391           return false;
392
393         for (f = TYPE_FIELDS (type); f ; f = TREE_CHAIN (f))
394           if (TREE_CODE (f) == FIELD_DECL)
395             {
396               if (!type_can_instantiate_all_elements (TREE_TYPE (f)))
397                 {
398                   bitmap_set_bit (sra_type_inst_cache, cache+1);
399                   return false;
400                 }
401             }
402
403         bitmap_set_bit (sra_type_inst_cache, cache+0);
404         return true;
405       }
406
407     case ARRAY_TYPE:
408       return type_can_instantiate_all_elements (TREE_TYPE (type));
409
410     case COMPLEX_TYPE:
411       return true;
412
413     default:
414       gcc_unreachable ();
415     }
416 }
417
418 /* Test whether ELT or some sub-element cannot be scalarized.  */
419
420 static bool
421 can_completely_scalarize_p (struct sra_elt *elt)
422 {
423   struct sra_elt *c;
424
425   if (elt->cannot_scalarize)
426     return false;
427
428   for (c = elt->children; c; c = c->sibling)
429     if (!can_completely_scalarize_p (c))
430       return false;
431
432   for (c = elt->groups; c; c = c->sibling)
433     if (!can_completely_scalarize_p (c))
434       return false;
435
436   return true;
437 }
438
439 \f
440 /* A simplified tree hashing algorithm that only handles the types of
441    trees we expect to find in sra_elt->element.  */
442
443 static hashval_t
444 sra_hash_tree (tree t)
445 {
446   hashval_t h;
447
448   switch (TREE_CODE (t))
449     {
450     case VAR_DECL:
451     case PARM_DECL:
452     case RESULT_DECL:
453       h = DECL_UID (t);
454       break;
455
456     case INTEGER_CST:
457       h = TREE_INT_CST_LOW (t) ^ TREE_INT_CST_HIGH (t);
458       break;
459
460     case RANGE_EXPR:
461       h = iterative_hash_expr (TREE_OPERAND (t, 0), 0);
462       h = iterative_hash_expr (TREE_OPERAND (t, 1), h);
463       break;
464
465     case FIELD_DECL:
466       /* We can have types that are compatible, but have different member
467          lists, so we can't hash fields by ID.  Use offsets instead.  */
468       h = iterative_hash_expr (DECL_FIELD_OFFSET (t), 0);
469       h = iterative_hash_expr (DECL_FIELD_BIT_OFFSET (t), h);
470       break;
471
472     case BIT_FIELD_REF:
473       /* Don't take operand 0 into account, that's our parent.  */
474       h = iterative_hash_expr (TREE_OPERAND (t, 1), 0);
475       h = iterative_hash_expr (TREE_OPERAND (t, 2), h);
476       break;
477
478     default:
479       gcc_unreachable ();
480     }
481
482   return h;
483 }
484
485 /* Hash function for type SRA_PAIR.  */
486
487 static hashval_t
488 sra_elt_hash (const void *x)
489 {
490   const struct sra_elt *const e = (const struct sra_elt *) x;
491   const struct sra_elt *p;
492   hashval_t h;
493
494   h = sra_hash_tree (e->element);
495
496   /* Take into account everything except bitfield blocks back up the
497      chain.  Given that chain lengths are rarely very long, this
498      should be acceptable.  If we truly identify this as a performance
499      problem, it should work to hash the pointer value
500      "e->parent".  */
501   for (p = e->parent; p ; p = p->parent)
502     if (!p->in_bitfld_block)
503       h = (h * 65521) ^ sra_hash_tree (p->element);
504
505   return h;
506 }
507
508 /* Equality function for type SRA_PAIR.  */
509
510 static int
511 sra_elt_eq (const void *x, const void *y)
512 {
513   const struct sra_elt *const a = (const struct sra_elt *) x;
514   const struct sra_elt *const b = (const struct sra_elt *) y;
515   tree ae, be;
516   const struct sra_elt *ap = a->parent;
517   const struct sra_elt *bp = b->parent;
518
519   if (ap)
520     while (ap->in_bitfld_block)
521       ap = ap->parent;
522   if (bp)
523     while (bp->in_bitfld_block)
524       bp = bp->parent;
525
526   if (ap != bp)
527     return false;
528
529   ae = a->element;
530   be = b->element;
531
532   if (ae == be)
533     return true;
534   if (TREE_CODE (ae) != TREE_CODE (be))
535     return false;
536
537   switch (TREE_CODE (ae))
538     {
539     case VAR_DECL:
540     case PARM_DECL:
541     case RESULT_DECL:
542       /* These are all pointer unique.  */
543       return false;
544
545     case INTEGER_CST:
546       /* Integers are not pointer unique, so compare their values.  */
547       return tree_int_cst_equal (ae, be);
548
549     case RANGE_EXPR:
550       return
551         tree_int_cst_equal (TREE_OPERAND (ae, 0), TREE_OPERAND (be, 0))
552         && tree_int_cst_equal (TREE_OPERAND (ae, 1), TREE_OPERAND (be, 1));
553
554     case FIELD_DECL:
555       /* Fields are unique within a record, but not between
556          compatible records.  */
557       if (DECL_FIELD_CONTEXT (ae) == DECL_FIELD_CONTEXT (be))
558         return false;
559       return fields_compatible_p (ae, be);
560
561     case BIT_FIELD_REF:
562       return
563         tree_int_cst_equal (TREE_OPERAND (ae, 1), TREE_OPERAND (be, 1))
564         && tree_int_cst_equal (TREE_OPERAND (ae, 2), TREE_OPERAND (be, 2));
565
566     default:
567       gcc_unreachable ();
568     }
569 }
570
571 /* Create or return the SRA_ELT structure for CHILD in PARENT.  PARENT
572    may be null, in which case CHILD must be a DECL.  */
573
574 static struct sra_elt *
575 lookup_element (struct sra_elt *parent, tree child, tree type,
576                 enum insert_option insert)
577 {
578   struct sra_elt dummy;
579   struct sra_elt **slot;
580   struct sra_elt *elt;
581
582   if (parent)
583     dummy.parent = parent->is_group ? parent->parent : parent;
584   else
585     dummy.parent = NULL;
586   dummy.element = child;
587
588   slot = (struct sra_elt **) htab_find_slot (sra_map, &dummy, insert);
589   if (!slot && insert == NO_INSERT)
590     return NULL;
591
592   elt = *slot;
593   if (!elt && insert == INSERT)
594     {
595       *slot = elt = XOBNEW (&sra_obstack, struct sra_elt);
596       memset (elt, 0, sizeof (*elt));
597
598       elt->parent = parent;
599       elt->element = child;
600       elt->type = type;
601       elt->is_scalar = is_sra_scalar_type (type);
602
603       if (parent)
604         {
605           if (IS_ELEMENT_FOR_GROUP (elt->element))
606             {
607               elt->is_group = true;
608               elt->sibling = parent->groups;
609               parent->groups = elt;
610             }
611           else
612             {
613               elt->sibling = parent->children;
614               parent->children = elt;
615             }
616         }
617
618       /* If this is a parameter, then if we want to scalarize, we have
619          one copy from the true function parameter.  Count it now.  */
620       if (TREE_CODE (child) == PARM_DECL)
621         {
622           elt->n_copies = 1;
623           bitmap_set_bit (needs_copy_in, DECL_UID (child));
624         }
625     }
626
627   return elt;
628 }
629
630 /* Create or return the SRA_ELT structure for EXPR if the expression
631    refers to a scalarizable variable.  */
632
633 static struct sra_elt *
634 maybe_lookup_element_for_expr (tree expr)
635 {
636   struct sra_elt *elt;
637   tree child;
638
639   switch (TREE_CODE (expr))
640     {
641     case VAR_DECL:
642     case PARM_DECL:
643     case RESULT_DECL:
644       if (is_sra_candidate_decl (expr))
645         return lookup_element (NULL, expr, TREE_TYPE (expr), INSERT);
646       return NULL;
647
648     case ARRAY_REF:
649       /* We can't scalarize variable array indices.  */
650       if (in_array_bounds_p (expr))
651         child = TREE_OPERAND (expr, 1);
652       else
653         return NULL;
654       break;
655
656     case ARRAY_RANGE_REF:
657       /* We can't scalarize variable array indices.  */
658       if (range_in_array_bounds_p (expr))
659         {
660           tree domain = TYPE_DOMAIN (TREE_TYPE (expr));
661           child = build2 (RANGE_EXPR, integer_type_node,
662                           TYPE_MIN_VALUE (domain), TYPE_MAX_VALUE (domain));
663         }
664       else
665         return NULL;
666       break;
667
668     case COMPONENT_REF:
669       {
670         tree type = TREE_TYPE (TREE_OPERAND (expr, 0));
671         /* Don't look through unions.  */
672         if (TREE_CODE (type) != RECORD_TYPE)
673           return NULL;
674         /* Neither through variable-sized records.  */
675         if (TYPE_SIZE (type) == NULL_TREE
676             || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST)
677           return NULL;
678         child = TREE_OPERAND (expr, 1);
679       }
680       break;
681
682     case REALPART_EXPR:
683       child = integer_zero_node;
684       break;
685     case IMAGPART_EXPR:
686       child = integer_one_node;
687       break;
688
689     default:
690       return NULL;
691     }
692
693   elt = maybe_lookup_element_for_expr (TREE_OPERAND (expr, 0));
694   if (elt)
695     return lookup_element (elt, child, TREE_TYPE (expr), INSERT);
696   return NULL;
697 }
698
699 \f
700 /* Functions to walk just enough of the tree to see all scalarizable
701    references, and categorize them.  */
702
703 /* A set of callbacks for phases 2 and 4.  They'll be invoked for the
704    various kinds of references seen.  In all cases, *BSI is an iterator
705    pointing to the statement being processed.  */
706 struct sra_walk_fns
707 {
708   /* Invoked when ELT is required as a unit.  Note that ELT might refer to
709      a leaf node, in which case this is a simple scalar reference.  *EXPR_P
710      points to the location of the expression.  IS_OUTPUT is true if this
711      is a left-hand-side reference.  USE_ALL is true if we saw something we
712      couldn't quite identify and had to force the use of the entire object.  */
713   void (*use) (struct sra_elt *elt, tree *expr_p,
714                block_stmt_iterator *bsi, bool is_output, bool use_all);
715
716   /* Invoked when we have a copy between two scalarizable references.  */
717   void (*copy) (struct sra_elt *lhs_elt, struct sra_elt *rhs_elt,
718                 block_stmt_iterator *bsi);
719
720   /* Invoked when ELT is initialized from a constant.  VALUE may be NULL,
721      in which case it should be treated as an empty CONSTRUCTOR.  */
722   void (*init) (struct sra_elt *elt, tree value, block_stmt_iterator *bsi);
723
724   /* Invoked when we have a copy between one scalarizable reference ELT
725      and one non-scalarizable reference OTHER without side-effects. 
726      IS_OUTPUT is true if ELT is on the left-hand side.  */
727   void (*ldst) (struct sra_elt *elt, tree other,
728                 block_stmt_iterator *bsi, bool is_output);
729
730   /* True during phase 2, false during phase 4.  */
731   /* ??? This is a hack.  */
732   bool initial_scan;
733 };
734
735 #ifdef ENABLE_CHECKING
736 /* Invoked via walk_tree, if *TP contains a candidate decl, return it.  */
737
738 static tree
739 sra_find_candidate_decl (tree *tp, int *walk_subtrees,
740                          void *data ATTRIBUTE_UNUSED)
741 {
742   tree t = *tp;
743   enum tree_code code = TREE_CODE (t);
744
745   if (code == VAR_DECL || code == PARM_DECL || code == RESULT_DECL)
746     {
747       *walk_subtrees = 0;
748       if (is_sra_candidate_decl (t))
749         return t;
750     }
751   else if (TYPE_P (t))
752     *walk_subtrees = 0;
753
754   return NULL;
755 }
756 #endif
757
758 /* Walk most expressions looking for a scalarizable aggregate.
759    If we find one, invoke FNS->USE.  */
760
761 static void
762 sra_walk_expr (tree *expr_p, block_stmt_iterator *bsi, bool is_output,
763                const struct sra_walk_fns *fns)
764 {
765   tree expr = *expr_p;
766   tree inner = expr;
767   bool disable_scalarization = false;
768   bool use_all_p = false;
769
770   /* We're looking to collect a reference expression between EXPR and INNER,
771      such that INNER is a scalarizable decl and all other nodes through EXPR
772      are references that we can scalarize.  If we come across something that
773      we can't scalarize, we reset EXPR.  This has the effect of making it
774      appear that we're referring to the larger expression as a whole.  */
775
776   while (1)
777     switch (TREE_CODE (inner))
778       {
779       case VAR_DECL:
780       case PARM_DECL:
781       case RESULT_DECL:
782         /* If there is a scalarizable decl at the bottom, then process it.  */
783         if (is_sra_candidate_decl (inner))
784           {
785             struct sra_elt *elt = maybe_lookup_element_for_expr (expr);
786             if (disable_scalarization)
787               elt->cannot_scalarize = true;
788             else
789               fns->use (elt, expr_p, bsi, is_output, use_all_p);
790           }
791         return;
792
793       case ARRAY_REF:
794         /* Non-constant index means any member may be accessed.  Prevent the
795            expression from being scalarized.  If we were to treat this as a
796            reference to the whole array, we can wind up with a single dynamic
797            index reference inside a loop being overridden by several constant
798            index references during loop setup.  It's possible that this could
799            be avoided by using dynamic usage counts based on BB trip counts
800            (based on loop analysis or profiling), but that hardly seems worth
801            the effort.  */
802         /* ??? Hack.  Figure out how to push this into the scan routines
803            without duplicating too much code.  */
804         if (!in_array_bounds_p (inner))
805           {
806             disable_scalarization = true;
807             goto use_all;
808           }
809         /* ??? Are we assured that non-constant bounds and stride will have
810            the same value everywhere?  I don't think Fortran will...  */
811         if (TREE_OPERAND (inner, 2) || TREE_OPERAND (inner, 3))
812           goto use_all;
813         inner = TREE_OPERAND (inner, 0);
814         break;
815
816       case ARRAY_RANGE_REF:
817         if (!range_in_array_bounds_p (inner))
818           {
819             disable_scalarization = true;
820             goto use_all;
821           }
822         /* ??? See above non-constant bounds and stride .  */
823         if (TREE_OPERAND (inner, 2) || TREE_OPERAND (inner, 3))
824           goto use_all;
825         inner = TREE_OPERAND (inner, 0);
826         break;
827
828       case COMPONENT_REF:
829         {
830           tree type = TREE_TYPE (TREE_OPERAND (inner, 0));
831           /* Don't look through unions.  */
832           if (TREE_CODE (type) != RECORD_TYPE)
833             goto use_all;
834           /* Neither through variable-sized records.  */
835           if (TYPE_SIZE (type) == NULL_TREE
836               || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST)
837             goto use_all;
838           inner = TREE_OPERAND (inner, 0);
839         }
840         break;
841
842       case REALPART_EXPR:
843       case IMAGPART_EXPR:
844         inner = TREE_OPERAND (inner, 0);
845         break;
846
847       case BIT_FIELD_REF:
848         /* A bit field reference to a specific vector is scalarized but for
849            ones for inputs need to be marked as used on the left hand size so
850            when we scalarize it, we can mark that variable as non renamable.  */
851         if (is_output
852             && TREE_CODE (TREE_TYPE (TREE_OPERAND (inner, 0))) == VECTOR_TYPE)
853           {
854             struct sra_elt *elt
855               = maybe_lookup_element_for_expr (TREE_OPERAND (inner, 0));
856             if (elt)
857               elt->is_vector_lhs = true;
858           }
859
860         /* A bit field reference (access to *multiple* fields simultaneously)
861            is not currently scalarized.  Consider this an access to the full
862            outer element, to which walk_tree will bring us next.  */
863         goto use_all;
864
865       case NOP_EXPR:
866         /* Similarly, a nop explicitly wants to look at an object in a
867            type other than the one we've scalarized.  */
868         goto use_all;
869
870       case VIEW_CONVERT_EXPR:
871         /* Likewise for a view conversion, but with an additional twist:
872            it can be on the LHS and, in this case, an access to the full
873            outer element would mean a killing def.  So we need to punt
874            if we haven't already a full access to the current element,
875            because we cannot pretend to have a killing def if we only
876            have a partial access at some level.  */
877         if (is_output && !use_all_p && inner != expr)
878           disable_scalarization = true;
879         goto use_all;
880
881       case WITH_SIZE_EXPR:
882         /* This is a transparent wrapper.  The entire inner expression really
883            is being used.  */
884         goto use_all;
885
886       use_all:
887         expr_p = &TREE_OPERAND (inner, 0);
888         inner = expr = *expr_p;
889         use_all_p = true;
890         break;
891
892       default:
893 #ifdef ENABLE_CHECKING
894         /* Validate that we're not missing any references.  */
895         gcc_assert (!walk_tree (&inner, sra_find_candidate_decl, NULL, NULL));
896 #endif
897         return;
898       }
899 }
900
901 /* Walk a TREE_LIST of values looking for scalarizable aggregates.
902    If we find one, invoke FNS->USE.  */
903
904 static void
905 sra_walk_tree_list (tree list, block_stmt_iterator *bsi, bool is_output,
906                     const struct sra_walk_fns *fns)
907 {
908   tree op;
909   for (op = list; op ; op = TREE_CHAIN (op))
910     sra_walk_expr (&TREE_VALUE (op), bsi, is_output, fns);
911 }
912
913 /* Walk the arguments of a CALL_EXPR looking for scalarizable aggregates.
914    If we find one, invoke FNS->USE.  */
915
916 static void
917 sra_walk_call_expr (tree expr, block_stmt_iterator *bsi,
918                     const struct sra_walk_fns *fns)
919 {
920   int i;
921   int nargs = call_expr_nargs (expr);
922   for (i = 0; i < nargs; i++)
923     sra_walk_expr (&CALL_EXPR_ARG (expr, i), bsi, false, fns);
924 }
925
926 /* Walk the inputs and outputs of an ASM_EXPR looking for scalarizable
927    aggregates.  If we find one, invoke FNS->USE.  */
928
929 static void
930 sra_walk_asm_expr (tree expr, block_stmt_iterator *bsi,
931                    const struct sra_walk_fns *fns)
932 {
933   sra_walk_tree_list (ASM_INPUTS (expr), bsi, false, fns);
934   sra_walk_tree_list (ASM_OUTPUTS (expr), bsi, true, fns);
935 }
936
937 /* Walk a GIMPLE_MODIFY_STMT and categorize the assignment appropriately.  */
938
939 static void
940 sra_walk_gimple_modify_stmt (tree expr, block_stmt_iterator *bsi,
941                              const struct sra_walk_fns *fns)
942 {
943   struct sra_elt *lhs_elt, *rhs_elt;
944   tree lhs, rhs;
945
946   lhs = GIMPLE_STMT_OPERAND (expr, 0);
947   rhs = GIMPLE_STMT_OPERAND (expr, 1);
948   lhs_elt = maybe_lookup_element_for_expr (lhs);
949   rhs_elt = maybe_lookup_element_for_expr (rhs);
950
951   /* If both sides are scalarizable, this is a COPY operation.  */
952   if (lhs_elt && rhs_elt)
953     {
954       fns->copy (lhs_elt, rhs_elt, bsi);
955       return;
956     }
957
958   /* If the RHS is scalarizable, handle it.  There are only two cases.  */
959   if (rhs_elt)
960     {
961       if (!rhs_elt->is_scalar && !TREE_SIDE_EFFECTS (lhs))
962         fns->ldst (rhs_elt, lhs, bsi, false);
963       else
964         fns->use (rhs_elt, &GIMPLE_STMT_OPERAND (expr, 1), bsi, false, false);
965     }
966
967   /* If it isn't scalarizable, there may be scalarizable variables within, so
968      check for a call or else walk the RHS to see if we need to do any
969      copy-in operations.  We need to do it before the LHS is scalarized so
970      that the statements get inserted in the proper place, before any
971      copy-out operations.  */
972   else
973     {
974       tree call = get_call_expr_in (rhs);
975       if (call)
976         sra_walk_call_expr (call, bsi, fns);
977       else
978         sra_walk_expr (&GIMPLE_STMT_OPERAND (expr, 1), bsi, false, fns);
979     }
980
981   /* Likewise, handle the LHS being scalarizable.  We have cases similar
982      to those above, but also want to handle RHS being constant.  */
983   if (lhs_elt)
984     {
985       /* If this is an assignment from a constant, or constructor, then
986          we have access to all of the elements individually.  Invoke INIT.  */
987       if (TREE_CODE (rhs) == COMPLEX_EXPR
988           || TREE_CODE (rhs) == COMPLEX_CST
989           || TREE_CODE (rhs) == CONSTRUCTOR)
990         fns->init (lhs_elt, rhs, bsi);
991
992       /* If this is an assignment from read-only memory, treat this as if
993          we'd been passed the constructor directly.  Invoke INIT.  */
994       else if (TREE_CODE (rhs) == VAR_DECL
995                && TREE_STATIC (rhs)
996                && TREE_READONLY (rhs)
997                && targetm.binds_local_p (rhs))
998         fns->init (lhs_elt, DECL_INITIAL (rhs), bsi);
999
1000       /* If this is a copy from a non-scalarizable lvalue, invoke LDST.
1001          The lvalue requirement prevents us from trying to directly scalarize
1002          the result of a function call.  Which would result in trying to call
1003          the function multiple times, and other evil things.  */
1004       else if (!lhs_elt->is_scalar
1005                && !TREE_SIDE_EFFECTS (rhs) && is_gimple_addressable (rhs))
1006         fns->ldst (lhs_elt, rhs, bsi, true);
1007
1008       /* Otherwise we're being used in some context that requires the
1009          aggregate to be seen as a whole.  Invoke USE.  */
1010       else
1011         fns->use (lhs_elt, &GIMPLE_STMT_OPERAND (expr, 0), bsi, true, false);
1012     }
1013
1014   /* Similarly to above, LHS_ELT being null only means that the LHS as a
1015      whole is not a scalarizable reference.  There may be occurrences of
1016      scalarizable variables within, which implies a USE.  */
1017   else
1018     sra_walk_expr (&GIMPLE_STMT_OPERAND (expr, 0), bsi, true, fns);
1019 }
1020
1021 /* Entry point to the walk functions.  Search the entire function,
1022    invoking the callbacks in FNS on each of the references to
1023    scalarizable variables.  */
1024
1025 static void
1026 sra_walk_function (const struct sra_walk_fns *fns)
1027 {
1028   basic_block bb;
1029   block_stmt_iterator si, ni;
1030
1031   /* ??? Phase 4 could derive some benefit to walking the function in
1032      dominator tree order.  */
1033
1034   FOR_EACH_BB (bb)
1035     for (si = bsi_start (bb); !bsi_end_p (si); si = ni)
1036       {
1037         tree stmt, t;
1038         stmt_ann_t ann;
1039
1040         stmt = bsi_stmt (si);
1041         ann = stmt_ann (stmt);
1042
1043         ni = si;
1044         bsi_next (&ni);
1045
1046         /* If the statement has no virtual operands, then it doesn't
1047            make any structure references that we care about.  */
1048         if (gimple_aliases_computed_p (cfun)
1049             && ZERO_SSA_OPERANDS (stmt, (SSA_OP_VIRTUAL_DEFS | SSA_OP_VUSE)))
1050               continue;
1051
1052         switch (TREE_CODE (stmt))
1053           {
1054           case RETURN_EXPR:
1055             /* If we have "return <retval>" then the return value is
1056                already exposed for our pleasure.  Walk it as a USE to
1057                force all the components back in place for the return.
1058
1059                If we have an embedded assignment, then <retval> is of
1060                a type that gets returned in registers in this ABI, and
1061                we do not wish to extend their lifetimes.  Treat this
1062                as a USE of the variable on the RHS of this assignment.  */
1063
1064             t = TREE_OPERAND (stmt, 0);
1065             if (t == NULL_TREE)
1066               ;
1067             else if (TREE_CODE (t) == GIMPLE_MODIFY_STMT)
1068               sra_walk_expr (&GIMPLE_STMT_OPERAND (t, 1), &si, false, fns);
1069             else
1070               sra_walk_expr (&TREE_OPERAND (stmt, 0), &si, false, fns);
1071             break;
1072
1073           case GIMPLE_MODIFY_STMT:
1074             sra_walk_gimple_modify_stmt (stmt, &si, fns);
1075             break;
1076           case CALL_EXPR:
1077             sra_walk_call_expr (stmt, &si, fns);
1078             break;
1079           case ASM_EXPR:
1080             sra_walk_asm_expr (stmt, &si, fns);
1081             break;
1082
1083           default:
1084             break;
1085           }
1086       }
1087 }
1088 \f
1089 /* Phase One: Scan all referenced variables in the program looking for
1090    structures that could be decomposed.  */
1091
1092 static bool
1093 find_candidates_for_sra (void)
1094 {
1095   bool any_set = false;
1096   tree var;
1097   referenced_var_iterator rvi;
1098
1099   FOR_EACH_REFERENCED_VAR (var, rvi)
1100     {
1101       if (decl_can_be_decomposed_p (var))
1102         {
1103           bitmap_set_bit (sra_candidates, DECL_UID (var));
1104           any_set = true;
1105         }
1106     }
1107
1108   return any_set;
1109 }
1110
1111 \f
1112 /* Phase Two: Scan all references to scalarizable variables.  Count the
1113    number of times they are used or copied respectively.  */
1114
1115 /* Callbacks to fill in SRA_WALK_FNS.  Everything but USE is
1116    considered a copy, because we can decompose the reference such that
1117    the sub-elements needn't be contiguous.  */
1118
1119 static void
1120 scan_use (struct sra_elt *elt, tree *expr_p ATTRIBUTE_UNUSED,
1121           block_stmt_iterator *bsi ATTRIBUTE_UNUSED,
1122           bool is_output ATTRIBUTE_UNUSED, bool use_all ATTRIBUTE_UNUSED)
1123 {
1124   elt->n_uses += 1;
1125 }
1126
1127 static void
1128 scan_copy (struct sra_elt *lhs_elt, struct sra_elt *rhs_elt,
1129            block_stmt_iterator *bsi ATTRIBUTE_UNUSED)
1130 {
1131   lhs_elt->n_copies += 1;
1132   rhs_elt->n_copies += 1;
1133 }
1134
1135 static void
1136 scan_init (struct sra_elt *lhs_elt, tree rhs ATTRIBUTE_UNUSED,
1137            block_stmt_iterator *bsi ATTRIBUTE_UNUSED)
1138 {
1139   lhs_elt->n_copies += 1;
1140 }
1141
1142 static void
1143 scan_ldst (struct sra_elt *elt, tree other ATTRIBUTE_UNUSED,
1144            block_stmt_iterator *bsi ATTRIBUTE_UNUSED,
1145            bool is_output ATTRIBUTE_UNUSED)
1146 {
1147   elt->n_copies += 1;
1148 }
1149
1150 /* Dump the values we collected during the scanning phase.  */
1151
1152 static void
1153 scan_dump (struct sra_elt *elt)
1154 {
1155   struct sra_elt *c;
1156
1157   dump_sra_elt_name (dump_file, elt);
1158   fprintf (dump_file, ": n_uses=%u n_copies=%u\n", elt->n_uses, elt->n_copies);
1159
1160   for (c = elt->children; c ; c = c->sibling)
1161     scan_dump (c);
1162
1163   for (c = elt->groups; c ; c = c->sibling)
1164     scan_dump (c);
1165 }
1166
1167 /* Entry point to phase 2.  Scan the entire function, building up
1168    scalarization data structures, recording copies and uses.  */
1169
1170 static void
1171 scan_function (void)
1172 {
1173   static const struct sra_walk_fns fns = {
1174     scan_use, scan_copy, scan_init, scan_ldst, true
1175   };
1176   bitmap_iterator bi;
1177
1178   sra_walk_function (&fns);
1179
1180   if (dump_file && (dump_flags & TDF_DETAILS))
1181     {
1182       unsigned i;
1183
1184       fputs ("\nScan results:\n", dump_file);
1185       EXECUTE_IF_SET_IN_BITMAP (sra_candidates, 0, i, bi)
1186         {
1187           tree var = referenced_var (i);
1188           struct sra_elt *elt = lookup_element (NULL, var, NULL, NO_INSERT);
1189           if (elt)
1190             scan_dump (elt);
1191         }
1192       fputc ('\n', dump_file);
1193     }
1194 }
1195 \f
1196 /* Phase Three: Make decisions about which variables to scalarize, if any.
1197    All elements to be scalarized have replacement variables made for them.  */
1198
1199 /* A subroutine of build_element_name.  Recursively build the element
1200    name on the obstack.  */
1201
1202 static void
1203 build_element_name_1 (struct sra_elt *elt)
1204 {
1205   tree t;
1206   char buffer[32];
1207
1208   if (elt->parent)
1209     {
1210       build_element_name_1 (elt->parent);
1211       obstack_1grow (&sra_obstack, '$');
1212
1213       if (TREE_CODE (elt->parent->type) == COMPLEX_TYPE)
1214         {
1215           if (elt->element == integer_zero_node)
1216             obstack_grow (&sra_obstack, "real", 4);
1217           else
1218             obstack_grow (&sra_obstack, "imag", 4);
1219           return;
1220         }
1221     }
1222
1223   t = elt->element;
1224   if (TREE_CODE (t) == INTEGER_CST)
1225     {
1226       /* ??? Eh.  Don't bother doing double-wide printing.  */
1227       sprintf (buffer, HOST_WIDE_INT_PRINT_DEC, TREE_INT_CST_LOW (t));
1228       obstack_grow (&sra_obstack, buffer, strlen (buffer));
1229     }
1230   else if (TREE_CODE (t) == BIT_FIELD_REF)
1231     {
1232       sprintf (buffer, "B" HOST_WIDE_INT_PRINT_DEC,
1233                tree_low_cst (TREE_OPERAND (t, 2), 1));
1234       obstack_grow (&sra_obstack, buffer, strlen (buffer));
1235       sprintf (buffer, "F" HOST_WIDE_INT_PRINT_DEC,
1236                tree_low_cst (TREE_OPERAND (t, 1), 1));
1237       obstack_grow (&sra_obstack, buffer, strlen (buffer));
1238     }
1239   else
1240     {
1241       tree name = DECL_NAME (t);
1242       if (name)
1243         obstack_grow (&sra_obstack, IDENTIFIER_POINTER (name),
1244                       IDENTIFIER_LENGTH (name));
1245       else
1246         {
1247           sprintf (buffer, "D%u", DECL_UID (t));
1248           obstack_grow (&sra_obstack, buffer, strlen (buffer));
1249         }
1250     }
1251 }
1252
1253 /* Construct a pretty variable name for an element's replacement variable.
1254    The name is built on the obstack.  */
1255
1256 static char *
1257 build_element_name (struct sra_elt *elt)
1258 {
1259   build_element_name_1 (elt);
1260   obstack_1grow (&sra_obstack, '\0');
1261   return XOBFINISH (&sra_obstack, char *);
1262 }
1263
1264 /* Instantiate an element as an independent variable.  */
1265
1266 static void
1267 instantiate_element (struct sra_elt *elt)
1268 {
1269   struct sra_elt *base_elt;
1270   tree var, base;
1271   bool nowarn = TREE_NO_WARNING (elt->element);
1272
1273   for (base_elt = elt; base_elt->parent; base_elt = base_elt->parent)
1274     if (!nowarn)
1275       nowarn = TREE_NO_WARNING (base_elt->parent->element);
1276   base = base_elt->element;
1277
1278   elt->replacement = var = make_rename_temp (elt->type, "SR");
1279
1280   if (DECL_P (elt->element)
1281       && !tree_int_cst_equal (DECL_SIZE (var), DECL_SIZE (elt->element)))
1282     {
1283       DECL_SIZE (var) = DECL_SIZE (elt->element);
1284       DECL_SIZE_UNIT (var) = DECL_SIZE_UNIT (elt->element);
1285
1286       elt->in_bitfld_block = 1;
1287       elt->replacement = fold_build3 (BIT_FIELD_REF, elt->type, var,
1288                                       DECL_SIZE (var),
1289                                       BYTES_BIG_ENDIAN
1290                                       ? size_binop (MINUS_EXPR,
1291                                                     TYPE_SIZE (elt->type),
1292                                                     DECL_SIZE (var))
1293                                       : bitsize_int (0));
1294     }
1295
1296   /* For vectors, if used on the left hand side with BIT_FIELD_REF,
1297      they are not a gimple register.  */
1298   if (TREE_CODE (TREE_TYPE (var)) == VECTOR_TYPE && elt->is_vector_lhs)
1299     DECL_GIMPLE_REG_P (var) = 0;
1300
1301   DECL_SOURCE_LOCATION (var) = DECL_SOURCE_LOCATION (base);
1302   DECL_ARTIFICIAL (var) = 1;
1303
1304   if (TREE_THIS_VOLATILE (elt->type))
1305     {
1306       TREE_THIS_VOLATILE (var) = 1;
1307       TREE_SIDE_EFFECTS (var) = 1;
1308     }
1309
1310   if (DECL_NAME (base) && !DECL_IGNORED_P (base))
1311     {
1312       char *pretty_name = build_element_name (elt);
1313       DECL_NAME (var) = get_identifier (pretty_name);
1314       obstack_free (&sra_obstack, pretty_name);
1315
1316       SET_DECL_DEBUG_EXPR (var, generate_element_ref (elt));
1317       DECL_DEBUG_EXPR_IS_FROM (var) = 1;
1318       
1319       DECL_IGNORED_P (var) = 0;
1320       TREE_NO_WARNING (var) = nowarn;
1321     }
1322   else
1323     {
1324       DECL_IGNORED_P (var) = 1;
1325       /* ??? We can't generate any warning that would be meaningful.  */
1326       TREE_NO_WARNING (var) = 1;
1327     }
1328
1329   /* Zero-initialize bit-field scalarization variables, to avoid
1330      triggering undefined behavior.  */
1331   if (TREE_CODE (elt->element) == BIT_FIELD_REF
1332       || (var != elt->replacement
1333           && TREE_CODE (elt->replacement) == BIT_FIELD_REF))
1334     {
1335       tree init = sra_build_assignment (var, fold_convert (TREE_TYPE (var),
1336                                                            integer_zero_node));
1337       insert_edge_copies (init, ENTRY_BLOCK_PTR);
1338       mark_all_v_defs (init);
1339     }
1340
1341   if (dump_file)
1342     {
1343       fputs ("  ", dump_file);
1344       dump_sra_elt_name (dump_file, elt);
1345       fputs (" -> ", dump_file);
1346       print_generic_expr (dump_file, var, dump_flags);
1347       fputc ('\n', dump_file);
1348     }
1349 }
1350
1351 /* Make one pass across an element tree deciding whether or not it's
1352    profitable to instantiate individual leaf scalars.
1353
1354    PARENT_USES and PARENT_COPIES are the sum of the N_USES and N_COPIES
1355    fields all the way up the tree.  */
1356
1357 static void
1358 decide_instantiation_1 (struct sra_elt *elt, unsigned int parent_uses,
1359                         unsigned int parent_copies)
1360 {
1361   if (dump_file && !elt->parent)
1362     {
1363       fputs ("Initial instantiation for ", dump_file);
1364       dump_sra_elt_name (dump_file, elt);
1365       fputc ('\n', dump_file);
1366     }
1367
1368   if (elt->cannot_scalarize)
1369     return;
1370
1371   if (elt->is_scalar)
1372     {
1373       /* The decision is simple: instantiate if we're used more frequently
1374          than the parent needs to be seen as a complete unit.  */
1375       if (elt->n_uses + elt->n_copies + parent_copies > parent_uses)
1376         instantiate_element (elt);
1377     }
1378   else
1379     {
1380       struct sra_elt *c, *group;
1381       unsigned int this_uses = elt->n_uses + parent_uses;
1382       unsigned int this_copies = elt->n_copies + parent_copies;
1383
1384       /* Consider groups of sub-elements as weighing in favour of
1385          instantiation whatever their size.  */
1386       for (group = elt->groups; group ; group = group->sibling)
1387         FOR_EACH_ACTUAL_CHILD (c, group)
1388           {
1389             c->n_uses += group->n_uses;
1390             c->n_copies += group->n_copies;
1391           }
1392
1393       for (c = elt->children; c ; c = c->sibling)
1394         decide_instantiation_1 (c, this_uses, this_copies);
1395     }
1396 }
1397
1398 /* Compute the size and number of all instantiated elements below ELT.
1399    We will only care about this if the size of the complete structure
1400    fits in a HOST_WIDE_INT, so we don't have to worry about overflow.  */
1401
1402 static unsigned int
1403 sum_instantiated_sizes (struct sra_elt *elt, unsigned HOST_WIDE_INT *sizep)
1404 {
1405   if (elt->replacement)
1406     {
1407       *sizep += TREE_INT_CST_LOW (TYPE_SIZE_UNIT (elt->type));
1408       return 1;
1409     }
1410   else
1411     {
1412       struct sra_elt *c;
1413       unsigned int count = 0;
1414
1415       for (c = elt->children; c ; c = c->sibling)
1416         count += sum_instantiated_sizes (c, sizep);
1417
1418       return count;
1419     }
1420 }
1421
1422 /* Instantiate fields in ELT->TYPE that are not currently present as
1423    children of ELT.  */
1424
1425 static void instantiate_missing_elements (struct sra_elt *elt);
1426
1427 static struct sra_elt *
1428 instantiate_missing_elements_1 (struct sra_elt *elt, tree child, tree type)
1429 {
1430   struct sra_elt *sub = lookup_element (elt, child, type, INSERT);
1431   if (sub->is_scalar)
1432     {
1433       if (sub->replacement == NULL)
1434         instantiate_element (sub);
1435     }
1436   else
1437     instantiate_missing_elements (sub);
1438   return sub;
1439 }
1440
1441 /* Obtain the canonical type for field F of ELEMENT.  */
1442
1443 static tree
1444 canon_type_for_field (tree f, tree element)
1445 {
1446   tree field_type = TREE_TYPE (f);
1447
1448   /* canonicalize_component_ref() unwidens some bit-field types (not
1449      marked as DECL_BIT_FIELD in C++), so we must do the same, lest we
1450      may introduce type mismatches.  */
1451   if (INTEGRAL_TYPE_P (field_type)
1452       && DECL_MODE (f) != TYPE_MODE (field_type))
1453     field_type = TREE_TYPE (get_unwidened (build3 (COMPONENT_REF,
1454                                                    field_type,
1455                                                    element,
1456                                                    f, NULL_TREE),
1457                                            NULL_TREE));
1458
1459   return field_type;
1460 }
1461
1462 /* Look for adjacent fields of ELT starting at F that we'd like to
1463    scalarize as a single variable.  Return the last field of the
1464    group.  */
1465
1466 static tree
1467 try_instantiate_multiple_fields (struct sra_elt *elt, tree f)
1468 {
1469   int count;
1470   unsigned HOST_WIDE_INT align, bit, size, alchk;
1471   enum machine_mode mode;
1472   tree first = f, prev;
1473   tree type, var;
1474   struct sra_elt *block;
1475
1476   /* Point fields are typically best handled as standalone entities.  */
1477   if (POINTER_TYPE_P (TREE_TYPE (f)))
1478     return f;
1479     
1480   if (!is_sra_scalar_type (TREE_TYPE (f))
1481       || !host_integerp (DECL_FIELD_OFFSET (f), 1)
1482       || !host_integerp (DECL_FIELD_BIT_OFFSET (f), 1)
1483       || !host_integerp (DECL_SIZE (f), 1)
1484       || lookup_element (elt, f, NULL, NO_INSERT))
1485     return f;
1486
1487   block = elt;
1488
1489   /* For complex and array objects, there are going to be integer
1490      literals as child elements.  In this case, we can't just take the
1491      alignment and mode of the decl, so we instead rely on the element
1492      type.
1493
1494      ??? We could try to infer additional alignment from the full
1495      object declaration and the location of the sub-elements we're
1496      accessing.  */
1497   for (count = 0; !DECL_P (block->element); count++)
1498     block = block->parent;
1499
1500   align = DECL_ALIGN (block->element);
1501   alchk = GET_MODE_BITSIZE (DECL_MODE (block->element));
1502
1503   if (count)
1504     {
1505       type = TREE_TYPE (block->element);
1506       while (count--)
1507         type = TREE_TYPE (type);
1508
1509       align = TYPE_ALIGN (type);
1510       alchk = GET_MODE_BITSIZE (TYPE_MODE (type));
1511     }
1512
1513   if (align < alchk)
1514     align = alchk;
1515
1516   /* Coalescing wider fields is probably pointless and
1517      inefficient.  */
1518   if (align > BITS_PER_WORD)
1519     align = BITS_PER_WORD;
1520
1521   bit = tree_low_cst (DECL_FIELD_OFFSET (f), 1) * BITS_PER_UNIT
1522     + tree_low_cst (DECL_FIELD_BIT_OFFSET (f), 1);
1523   size = tree_low_cst (DECL_SIZE (f), 1);
1524
1525   alchk = align - 1;
1526   alchk = ~alchk;
1527
1528   if ((bit & alchk) != ((bit + size - 1) & alchk))
1529     return f;
1530
1531   /* Find adjacent fields in the same alignment word.  */
1532
1533   for (prev = f, f = TREE_CHAIN (f);
1534        f && TREE_CODE (f) == FIELD_DECL
1535          && is_sra_scalar_type (TREE_TYPE (f))
1536          && host_integerp (DECL_FIELD_OFFSET (f), 1)
1537          && host_integerp (DECL_FIELD_BIT_OFFSET (f), 1)
1538          && host_integerp (DECL_SIZE (f), 1)
1539          && !lookup_element (elt, f, NULL, NO_INSERT);
1540        prev = f, f = TREE_CHAIN (f))
1541     {
1542       unsigned HOST_WIDE_INT nbit, nsize;
1543
1544       nbit = tree_low_cst (DECL_FIELD_OFFSET (f), 1) * BITS_PER_UNIT
1545         + tree_low_cst (DECL_FIELD_BIT_OFFSET (f), 1);
1546       nsize = tree_low_cst (DECL_SIZE (f), 1);
1547
1548       if (bit + size == nbit)
1549         {
1550           if ((bit & alchk) != ((nbit + nsize - 1) & alchk))
1551             {
1552               /* If we're at an alignment boundary, don't bother
1553                  growing alignment such that we can include this next
1554                  field.  */
1555               if ((nbit & alchk)
1556                   || GET_MODE_BITSIZE (DECL_MODE (f)) <= align)
1557                 break;
1558
1559               align = GET_MODE_BITSIZE (DECL_MODE (f));
1560               alchk = align - 1;
1561               alchk = ~alchk;
1562
1563               if ((bit & alchk) != ((nbit + nsize - 1) & alchk))
1564                 break;
1565             }
1566           size += nsize;
1567         }
1568       else if (nbit + nsize == bit)
1569         {
1570           if ((nbit & alchk) != ((bit + size - 1) & alchk))
1571             {
1572               if ((bit & alchk)
1573                   || GET_MODE_BITSIZE (DECL_MODE (f)) <= align)
1574                 break;
1575
1576               align = GET_MODE_BITSIZE (DECL_MODE (f));
1577               alchk = align - 1;
1578               alchk = ~alchk;
1579
1580               if ((nbit & alchk) != ((bit + size - 1) & alchk))
1581                 break;
1582             }
1583           bit = nbit;
1584           size += nsize;
1585         }
1586       else
1587         break;
1588     }
1589
1590   f = prev;
1591
1592   if (f == first)
1593     return f;
1594
1595   gcc_assert ((bit & alchk) == ((bit + size - 1) & alchk));
1596
1597   /* Try to widen the bit range so as to cover padding bits as well.  */
1598
1599   if ((bit & ~alchk) || size != align)
1600     {
1601       unsigned HOST_WIDE_INT mbit = bit & alchk;
1602       unsigned HOST_WIDE_INT msize = align;
1603
1604       for (f = TYPE_FIELDS (elt->type);
1605            f; f = TREE_CHAIN (f))
1606         {
1607           unsigned HOST_WIDE_INT fbit, fsize;
1608
1609           /* Skip the fields from first to prev.  */
1610           if (f == first)
1611             {
1612               f = prev;
1613               continue;
1614             }
1615
1616           if (!(TREE_CODE (f) == FIELD_DECL
1617                 && host_integerp (DECL_FIELD_OFFSET (f), 1)
1618                 && host_integerp (DECL_FIELD_BIT_OFFSET (f), 1)))
1619             continue;
1620
1621           fbit = tree_low_cst (DECL_FIELD_OFFSET (f), 1) * BITS_PER_UNIT
1622             + tree_low_cst (DECL_FIELD_BIT_OFFSET (f), 1);
1623
1624           /* If we're past the selected word, we're fine.  */
1625           if ((bit & alchk) < (fbit & alchk))
1626             continue;
1627
1628           if (host_integerp (DECL_SIZE (f), 1))
1629             fsize = tree_low_cst (DECL_SIZE (f), 1);
1630           else
1631             /* Assume a variable-sized field takes up all space till
1632                the end of the word.  ??? Endianness issues?  */
1633             fsize = align - (fbit & alchk);
1634
1635           if ((fbit & alchk) < (bit & alchk))
1636             {
1637               /* A large field might start at a previous word and
1638                  extend into the selected word.  Exclude those
1639                  bits.  ??? Endianness issues? */
1640               HOST_WIDE_INT diff = fbit + fsize - mbit;
1641
1642               if (diff <= 0)
1643                 continue;
1644
1645               mbit += diff;
1646               msize -= diff;
1647             }
1648           else
1649             {
1650               /* Non-overlapping, great.  */
1651               if (fbit + fsize <= mbit
1652                   || mbit + msize <= fbit)
1653                 continue;
1654
1655               if (fbit <= mbit)
1656                 {
1657                   unsigned HOST_WIDE_INT diff = fbit + fsize - mbit;
1658                   mbit += diff;
1659                   msize -= diff;
1660                 }
1661               else if (fbit > mbit)
1662                 msize -= (mbit + msize - fbit);
1663               else
1664                 gcc_unreachable ();
1665             }
1666         }
1667
1668       bit = mbit;
1669       size = msize;
1670     }
1671
1672   /* Now we know the bit range we're interested in.  Find the smallest
1673      machine mode we can use to access it.  */
1674
1675   for (mode = smallest_mode_for_size (size, MODE_INT);
1676        ;
1677        mode = GET_MODE_WIDER_MODE (mode))
1678     {
1679       gcc_assert (mode != VOIDmode);
1680
1681       alchk = GET_MODE_PRECISION (mode) - 1;
1682       alchk = ~alchk;
1683
1684       if ((bit & alchk) == ((bit + size - 1) & alchk))
1685         break;
1686     }
1687
1688   gcc_assert (~alchk < align);
1689
1690   /* Create the field group as a single variable.  */
1691
1692   /* We used to create a type for the mode above, but size turns
1693      to be out not of mode-size.  As we need a matching type
1694      to build a BIT_FIELD_REF, use a nonstandard integer type as
1695      fallback.  */
1696   type = lang_hooks.types.type_for_size (size, 1);
1697   if (!type || TYPE_PRECISION (type) != size)
1698     type = build_nonstandard_integer_type (size, 1);
1699   gcc_assert (type);
1700   var = build3 (BIT_FIELD_REF, type, NULL_TREE,
1701                 bitsize_int (size), bitsize_int (bit));
1702
1703   block = instantiate_missing_elements_1 (elt, var, type);
1704   gcc_assert (block && block->is_scalar);
1705
1706   var = block->replacement;
1707
1708   if ((bit & ~alchk)
1709       || (HOST_WIDE_INT)size != tree_low_cst (DECL_SIZE (var), 1))
1710     {
1711       block->replacement = fold_build3 (BIT_FIELD_REF,
1712                                         TREE_TYPE (block->element), var,
1713                                         bitsize_int (size),
1714                                         bitsize_int (bit & ~alchk));
1715     }
1716
1717   block->in_bitfld_block = 2;
1718
1719   /* Add the member fields to the group, such that they access
1720      portions of the group variable.  */
1721
1722   for (f = first; f != TREE_CHAIN (prev); f = TREE_CHAIN (f))
1723     {
1724       tree field_type = canon_type_for_field (f, elt->element);
1725       struct sra_elt *fld = lookup_element (block, f, field_type, INSERT);
1726
1727       gcc_assert (fld && fld->is_scalar && !fld->replacement);
1728
1729       fld->replacement = fold_build3 (BIT_FIELD_REF, field_type, var,
1730                                       DECL_SIZE (f),
1731                                       bitsize_int
1732                                       ((TREE_INT_CST_LOW (DECL_FIELD_OFFSET (f))
1733                                         * BITS_PER_UNIT
1734                                         + (TREE_INT_CST_LOW
1735                                            (DECL_FIELD_BIT_OFFSET (f))))
1736                                        & ~alchk));
1737       fld->in_bitfld_block = 1;
1738     }
1739
1740   return prev;
1741 }
1742
1743 static void
1744 instantiate_missing_elements (struct sra_elt *elt)
1745 {
1746   tree type = elt->type;
1747
1748   switch (TREE_CODE (type))
1749     {
1750     case RECORD_TYPE:
1751       {
1752         tree f;
1753         for (f = TYPE_FIELDS (type); f ; f = TREE_CHAIN (f))
1754           if (TREE_CODE (f) == FIELD_DECL)
1755             {
1756               tree last = try_instantiate_multiple_fields (elt, f);
1757
1758               if (last != f)
1759                 {
1760                   f = last;
1761                   continue;
1762                 }
1763
1764               instantiate_missing_elements_1 (elt, f,
1765                                               canon_type_for_field
1766                                               (f, elt->element));
1767             }
1768         break;
1769       }
1770
1771     case ARRAY_TYPE:
1772       {
1773         tree i, max, subtype;
1774
1775         i = TYPE_MIN_VALUE (TYPE_DOMAIN (type));
1776         max = TYPE_MAX_VALUE (TYPE_DOMAIN (type));
1777         subtype = TREE_TYPE (type);
1778
1779         while (1)
1780           {
1781             instantiate_missing_elements_1 (elt, i, subtype);
1782             if (tree_int_cst_equal (i, max))
1783               break;
1784             i = int_const_binop (PLUS_EXPR, i, integer_one_node, true);
1785           }
1786
1787         break;
1788       }
1789
1790     case COMPLEX_TYPE:
1791       type = TREE_TYPE (type);
1792       instantiate_missing_elements_1 (elt, integer_zero_node, type);
1793       instantiate_missing_elements_1 (elt, integer_one_node, type);
1794       break;
1795
1796     default:
1797       gcc_unreachable ();
1798     }
1799 }
1800
1801 /* Return true if there is only one non aggregate field in the record, TYPE.
1802    Return false otherwise.  */
1803
1804 static bool
1805 single_scalar_field_in_record_p (tree type)
1806 {
1807    int num_fields = 0;
1808    tree field;
1809    if (TREE_CODE (type) != RECORD_TYPE)
1810      return false;
1811
1812    for (field = TYPE_FIELDS (type); field; field = TREE_CHAIN (field))
1813      if (TREE_CODE (field) == FIELD_DECL)
1814        {
1815          num_fields++;
1816
1817          if (num_fields == 2)
1818            return false;
1819          
1820          if (AGGREGATE_TYPE_P (TREE_TYPE (field)))
1821            return false;
1822        }
1823
1824    return true;
1825 }
1826
1827 /* Make one pass across an element tree deciding whether to perform block
1828    or element copies.  If we decide on element copies, instantiate all
1829    elements.  Return true if there are any instantiated sub-elements.  */
1830
1831 static bool
1832 decide_block_copy (struct sra_elt *elt)
1833 {
1834   struct sra_elt *c;
1835   bool any_inst;
1836
1837   /* We shouldn't be invoked on groups of sub-elements as they must
1838      behave like their parent as far as block copy is concerned.  */
1839   gcc_assert (!elt->is_group);
1840
1841   /* If scalarization is disabled, respect it.  */
1842   if (elt->cannot_scalarize)
1843     {
1844       elt->use_block_copy = 1;
1845
1846       if (dump_file)
1847         {
1848           fputs ("Scalarization disabled for ", dump_file);
1849           dump_sra_elt_name (dump_file, elt);
1850           fputc ('\n', dump_file);
1851         }
1852
1853       /* Disable scalarization of sub-elements */
1854       for (c = elt->children; c; c = c->sibling)
1855         {
1856           c->cannot_scalarize = 1;
1857           decide_block_copy (c);
1858         }
1859
1860       /* Groups behave like their parent.  */
1861       for (c = elt->groups; c; c = c->sibling)
1862         {
1863           c->cannot_scalarize = 1;
1864           c->use_block_copy = 1;
1865         }
1866
1867       return false;
1868     }
1869
1870   /* Don't decide if we've no uses and no groups.  */
1871   if (elt->n_uses == 0 && elt->n_copies == 0 && elt->groups == NULL)
1872     ;
1873
1874   else if (!elt->is_scalar)
1875     {
1876       tree size_tree = TYPE_SIZE_UNIT (elt->type);
1877       bool use_block_copy = true;
1878
1879       /* Tradeoffs for COMPLEX types pretty much always make it better
1880          to go ahead and split the components.  */
1881       if (TREE_CODE (elt->type) == COMPLEX_TYPE)
1882         use_block_copy = false;
1883
1884       /* Don't bother trying to figure out the rest if the structure is
1885          so large we can't do easy arithmetic.  This also forces block
1886          copies for variable sized structures.  */
1887       else if (host_integerp (size_tree, 1))
1888         {
1889           unsigned HOST_WIDE_INT full_size, inst_size = 0;
1890           unsigned int max_size, max_count, inst_count, full_count;
1891
1892           /* If the sra-max-structure-size parameter is 0, then the
1893              user has not overridden the parameter and we can choose a
1894              sensible default.  */
1895           max_size = SRA_MAX_STRUCTURE_SIZE
1896             ? SRA_MAX_STRUCTURE_SIZE
1897             : MOVE_RATIO * UNITS_PER_WORD;
1898           max_count = SRA_MAX_STRUCTURE_COUNT
1899             ? SRA_MAX_STRUCTURE_COUNT
1900             : MOVE_RATIO;
1901
1902           full_size = tree_low_cst (size_tree, 1);
1903           full_count = count_type_elements (elt->type, false);
1904           inst_count = sum_instantiated_sizes (elt, &inst_size);
1905
1906           /* If there is only one scalar field in the record, don't block copy.  */
1907           if (single_scalar_field_in_record_p (elt->type))
1908             use_block_copy = false;
1909
1910           /* ??? What to do here.  If there are two fields, and we've only
1911              instantiated one, then instantiating the other is clearly a win.
1912              If there are a large number of fields then the size of the copy
1913              is much more of a factor.  */
1914
1915           /* If the structure is small, and we've made copies, go ahead
1916              and instantiate, hoping that the copies will go away.  */
1917           if (full_size <= max_size
1918               && (full_count - inst_count) <= max_count
1919               && elt->n_copies > elt->n_uses)
1920             use_block_copy = false;
1921           else if (inst_count * 100 >= full_count * SRA_FIELD_STRUCTURE_RATIO
1922                    && inst_size * 100 >= full_size * SRA_FIELD_STRUCTURE_RATIO)
1923             use_block_copy = false;
1924
1925           /* In order to avoid block copy, we have to be able to instantiate
1926              all elements of the type.  See if this is possible.  */
1927           if (!use_block_copy
1928               && (!can_completely_scalarize_p (elt)
1929                   || !type_can_instantiate_all_elements (elt->type)))
1930             use_block_copy = true;
1931         }
1932
1933       elt->use_block_copy = use_block_copy;
1934
1935       /* Groups behave like their parent.  */
1936       for (c = elt->groups; c; c = c->sibling)
1937         c->use_block_copy = use_block_copy;
1938
1939       if (dump_file)
1940         {
1941           fprintf (dump_file, "Using %s for ",
1942                    use_block_copy ? "block-copy" : "element-copy");
1943           dump_sra_elt_name (dump_file, elt);
1944           fputc ('\n', dump_file);
1945         }
1946
1947       if (!use_block_copy)
1948         {
1949           instantiate_missing_elements (elt);
1950           return true;
1951         }
1952     }
1953
1954   any_inst = elt->replacement != NULL;
1955
1956   for (c = elt->children; c ; c = c->sibling)
1957     any_inst |= decide_block_copy (c);
1958
1959   return any_inst;
1960 }
1961
1962 /* Entry point to phase 3.  Instantiate scalar replacement variables.  */
1963
1964 static void
1965 decide_instantiations (void)
1966 {
1967   unsigned int i;
1968   bool cleared_any;
1969   bitmap_head done_head;
1970   bitmap_iterator bi;
1971
1972   /* We cannot clear bits from a bitmap we're iterating over,
1973      so save up all the bits to clear until the end.  */
1974   bitmap_initialize (&done_head, &bitmap_default_obstack);
1975   cleared_any = false;
1976
1977   EXECUTE_IF_SET_IN_BITMAP (sra_candidates, 0, i, bi)
1978     {
1979       tree var = referenced_var (i);
1980       struct sra_elt *elt = lookup_element (NULL, var, NULL, NO_INSERT);
1981       if (elt)
1982         {
1983           decide_instantiation_1 (elt, 0, 0);
1984           if (!decide_block_copy (elt))
1985             elt = NULL;
1986         }
1987       if (!elt)
1988         {
1989           bitmap_set_bit (&done_head, i);
1990           cleared_any = true;
1991         }
1992     }
1993
1994   if (cleared_any)
1995     {
1996       bitmap_and_compl_into (sra_candidates, &done_head);
1997       bitmap_and_compl_into (needs_copy_in, &done_head);
1998     }
1999   bitmap_clear (&done_head);
2000   
2001   mark_set_for_renaming (sra_candidates);
2002
2003   if (dump_file)
2004     fputc ('\n', dump_file);
2005 }
2006
2007 \f
2008 /* Phase Four: Update the function to match the replacements created.  */
2009
2010 /* Mark all the variables in VDEF/VUSE operators for STMT for
2011    renaming. This becomes necessary when we modify all of a
2012    non-scalar.  */
2013
2014 static void
2015 mark_all_v_defs_1 (tree stmt)
2016 {
2017   tree sym;
2018   ssa_op_iter iter;
2019
2020   update_stmt_if_modified (stmt);
2021
2022   FOR_EACH_SSA_TREE_OPERAND (sym, stmt, iter, SSA_OP_ALL_VIRTUALS)
2023     {
2024       if (TREE_CODE (sym) == SSA_NAME)
2025         sym = SSA_NAME_VAR (sym);
2026       mark_sym_for_renaming (sym);
2027     }
2028 }
2029
2030
2031 /* Mark all the variables in virtual operands in all the statements in
2032    LIST for renaming.  */
2033
2034 static void
2035 mark_all_v_defs (tree list)
2036 {
2037   if (TREE_CODE (list) != STATEMENT_LIST)
2038     mark_all_v_defs_1 (list);
2039   else
2040     {
2041       tree_stmt_iterator i;
2042       for (i = tsi_start (list); !tsi_end_p (i); tsi_next (&i))
2043         mark_all_v_defs_1 (tsi_stmt (i));
2044     }
2045 }
2046
2047
2048 /* Mark every replacement under ELT with TREE_NO_WARNING.  */
2049
2050 static void
2051 mark_no_warning (struct sra_elt *elt)
2052 {
2053   if (!elt->all_no_warning)
2054     {
2055       if (elt->replacement)
2056         TREE_NO_WARNING (elt->replacement) = 1;
2057       else
2058         {
2059           struct sra_elt *c;
2060           FOR_EACH_ACTUAL_CHILD (c, elt)
2061             mark_no_warning (c);
2062         }
2063       elt->all_no_warning = true;
2064     }
2065 }
2066
2067 /* Build a single level component reference to ELT rooted at BASE.  */
2068
2069 static tree
2070 generate_one_element_ref (struct sra_elt *elt, tree base)
2071 {
2072   switch (TREE_CODE (TREE_TYPE (base)))
2073     {
2074     case RECORD_TYPE:
2075       {
2076         tree field = elt->element;
2077
2078         /* We can't test elt->in_bitfld_block here because, when this is
2079            called from instantiate_element, we haven't set this field
2080            yet.  */
2081         if (TREE_CODE (field) == BIT_FIELD_REF)
2082           {
2083             tree ret = unshare_expr (field);
2084             TREE_OPERAND (ret, 0) = base;
2085             return ret;
2086           }
2087
2088         /* Watch out for compatible records with differing field lists.  */
2089         if (DECL_FIELD_CONTEXT (field) != TYPE_MAIN_VARIANT (TREE_TYPE (base)))
2090           field = find_compatible_field (TREE_TYPE (base), field);
2091
2092         return build3 (COMPONENT_REF, elt->type, base, field, NULL);
2093       }
2094
2095     case ARRAY_TYPE:
2096       if (TREE_CODE (elt->element) == RANGE_EXPR)
2097         return build4 (ARRAY_RANGE_REF, elt->type, base,
2098                        TREE_OPERAND (elt->element, 0), NULL, NULL);
2099       else
2100         return build4 (ARRAY_REF, elt->type, base, elt->element, NULL, NULL);
2101
2102     case COMPLEX_TYPE:
2103       if (elt->element == integer_zero_node)
2104         return build1 (REALPART_EXPR, elt->type, base);
2105       else
2106         return build1 (IMAGPART_EXPR, elt->type, base);
2107
2108     default:
2109       gcc_unreachable ();
2110     }
2111 }
2112
2113 /* Build a full component reference to ELT rooted at its native variable.  */
2114
2115 static tree
2116 generate_element_ref (struct sra_elt *elt)
2117 {
2118   if (elt->parent)
2119     return generate_one_element_ref (elt, generate_element_ref (elt->parent));
2120   else
2121     return elt->element;
2122 }
2123
2124 /* Return true if BF is a bit-field that we can handle like a scalar.  */
2125
2126 static bool
2127 scalar_bitfield_p (tree bf)
2128 {
2129   return (TREE_CODE (bf) == BIT_FIELD_REF
2130           && (is_gimple_reg (TREE_OPERAND (bf, 0))
2131               || (TYPE_MODE (TREE_TYPE (TREE_OPERAND (bf, 0))) != BLKmode
2132                   && (!TREE_SIDE_EFFECTS (TREE_OPERAND (bf, 0))
2133                       || (GET_MODE_BITSIZE (TYPE_MODE (TREE_TYPE
2134                                                        (TREE_OPERAND (bf, 0))))
2135                           <= BITS_PER_WORD)))));
2136 }
2137
2138 /* Create an assignment statement from SRC to DST.  */
2139
2140 static tree
2141 sra_build_assignment (tree dst, tree src)
2142 {
2143   /* Turning BIT_FIELD_REFs into bit operations enables other passes
2144      to do a much better job at optimizing the code.
2145      From dst = BIT_FIELD_REF <var, sz, off> we produce
2146
2147         SR.1 = (scalar type) var;
2148         SR.2 = SR.1 >> off;
2149         SR.3 = SR.2 & ((1 << sz) - 1);
2150         ... possible sign extension of SR.3 ...
2151         dst = (destination type) SR.3;
2152    */
2153   if (scalar_bitfield_p (src))
2154     {
2155       tree var, shift, width;
2156       tree utype, stype, stmp, utmp, dtmp;
2157       tree list, stmt;
2158       bool unsignedp = (INTEGRAL_TYPE_P (TREE_TYPE (src))
2159                         ? TYPE_UNSIGNED (TREE_TYPE (src)) : true);
2160
2161       var = TREE_OPERAND (src, 0);
2162       width = TREE_OPERAND (src, 1);
2163       /* The offset needs to be adjusted to a right shift quantity
2164          depending on the endianness.  */
2165       if (BYTES_BIG_ENDIAN)
2166         {
2167           tree tmp = size_binop (PLUS_EXPR, width, TREE_OPERAND (src, 2));
2168           shift = size_binop (MINUS_EXPR, TYPE_SIZE (TREE_TYPE (var)), tmp);
2169         }
2170       else
2171         shift = TREE_OPERAND (src, 2);
2172
2173       /* In weird cases we have non-integral types for the source or
2174          destination object.
2175          ???  For unknown reasons we also want an unsigned scalar type.  */
2176       stype = TREE_TYPE (var);
2177       if (!INTEGRAL_TYPE_P (stype))
2178         stype = lang_hooks.types.type_for_size (TREE_INT_CST_LOW
2179                                                 (TYPE_SIZE (stype)), 1);
2180       else if (!TYPE_UNSIGNED (stype))
2181         stype = unsigned_type_for (stype);
2182
2183       utype = TREE_TYPE (dst);
2184       if (!INTEGRAL_TYPE_P (utype))
2185         utype = lang_hooks.types.type_for_size (TREE_INT_CST_LOW
2186                                                 (TYPE_SIZE (utype)), 1);
2187       else if (!TYPE_UNSIGNED (utype))
2188         utype = unsigned_type_for (utype);
2189
2190       list = NULL;
2191       stmp = make_rename_temp (stype, "SR");
2192
2193       /* Convert the base var of the BIT_FIELD_REF to the scalar type
2194          we use for computation if we cannot use it directly.  */
2195       if (!useless_type_conversion_p (stype, TREE_TYPE (var)))
2196         {
2197           if (INTEGRAL_TYPE_P (TREE_TYPE (var)))
2198             stmt = build_gimple_modify_stmt (stmp,
2199                                              fold_convert (stype, var));
2200           else
2201             stmt = build_gimple_modify_stmt (stmp,
2202                                              fold_build1 (VIEW_CONVERT_EXPR,
2203                                                           stype, var));
2204           append_to_statement_list (stmt, &list);
2205           var = stmp;
2206         }
2207
2208       if (!integer_zerop (shift))
2209         {
2210           stmt = build_gimple_modify_stmt (stmp,
2211                                            fold_build2 (RSHIFT_EXPR, stype,
2212                                                         var, shift));
2213           append_to_statement_list (stmt, &list);
2214           var = stmp;
2215         }
2216
2217       /* If we need a masking operation, produce one.  */
2218       if (TREE_INT_CST_LOW (width) == TYPE_PRECISION (stype))
2219         unsignedp = true;
2220       else
2221         {
2222           tree one = build_int_cst_wide (stype, 1, 0);
2223           tree mask = int_const_binop (LSHIFT_EXPR, one, width, 0);
2224           mask = int_const_binop (MINUS_EXPR, mask, one, 0);
2225
2226           stmt = build_gimple_modify_stmt (stmp,
2227                                            fold_build2 (BIT_AND_EXPR, stype,
2228                                                         var, mask));
2229           append_to_statement_list (stmt, &list);
2230           var = stmp;
2231         }
2232
2233       /* After shifting and masking, convert to the target type.  */
2234       utmp = stmp;
2235       if (!useless_type_conversion_p (utype, stype))
2236         {
2237           utmp = make_rename_temp (utype, "SR");
2238
2239           stmt = build_gimple_modify_stmt (utmp, fold_convert (utype, var));
2240           append_to_statement_list (stmt, &list);
2241
2242           var = utmp;
2243         }
2244
2245       /* Perform sign extension, if required.
2246          ???  This should never be necessary.  */
2247       if (!unsignedp)
2248         {
2249           tree signbit = int_const_binop (LSHIFT_EXPR,
2250                                           build_int_cst_wide (utype, 1, 0),
2251                                           size_binop (MINUS_EXPR, width,
2252                                                       bitsize_int (1)), 0);
2253
2254           stmt = build_gimple_modify_stmt (utmp,
2255                                            fold_build2 (BIT_XOR_EXPR, utype,
2256                                                         var, signbit));
2257           append_to_statement_list (stmt, &list);
2258
2259           stmt = build_gimple_modify_stmt (utmp,
2260                                            fold_build2 (MINUS_EXPR, utype,
2261                                                         utmp, signbit));
2262           append_to_statement_list (stmt, &list);
2263
2264           var = utmp;
2265         }
2266
2267       /* Finally, move and convert to the destination.  */
2268       if (!useless_type_conversion_p (TREE_TYPE (dst), TREE_TYPE (var)))
2269         {
2270           if (INTEGRAL_TYPE_P (TREE_TYPE (dst)))
2271             var = fold_convert (TREE_TYPE (dst), var);
2272           else
2273             var = fold_build1 (VIEW_CONVERT_EXPR, TREE_TYPE (dst), var);
2274
2275           /* If the destination is not a register the conversion needs
2276              to be a separate statement.  */
2277           if (!is_gimple_reg (dst))
2278             {
2279               dtmp = make_rename_temp (TREE_TYPE (dst), "SR");
2280               stmt = build_gimple_modify_stmt (dtmp, var);
2281               append_to_statement_list (stmt, &list);
2282               var = dtmp;
2283             }
2284         }
2285       stmt = build_gimple_modify_stmt (dst, var);
2286       append_to_statement_list (stmt, &list);
2287
2288       return list;
2289     }
2290
2291   /* It was hoped that we could perform some type sanity checking
2292      here, but since front-ends can emit accesses of fields in types
2293      different from their nominal types and copy structures containing
2294      them as a whole, we'd have to handle such differences here.
2295      Since such accesses under different types require compatibility
2296      anyway, there's little point in making tests and/or adding
2297      conversions to ensure the types of src and dst are the same.
2298      So we just assume type differences at this point are ok.
2299      The only exception we make here are pointer types, which can be different
2300      in e.g. structurally equal, but non-identical RECORD_TYPEs.  */
2301   if (POINTER_TYPE_P (TREE_TYPE (dst))
2302       && !useless_type_conversion_p (TREE_TYPE (dst), TREE_TYPE (src)))
2303     src = fold_convert (TREE_TYPE (dst), src);
2304
2305   return build_gimple_modify_stmt (dst, src);
2306 }
2307
2308 /* BIT_FIELD_REFs must not be shared.  sra_build_elt_assignment()
2309    takes care of assignments, but we must create copies for uses.  */
2310 #define REPLDUP(t) (TREE_CODE (t) != BIT_FIELD_REF ? (t) : unshare_expr (t))
2311
2312 /* Emit an assignment from SRC to DST, but if DST is a scalarizable
2313    BIT_FIELD_REF, turn it into bit operations.  */
2314
2315 static tree
2316 sra_build_bf_assignment (tree dst, tree src)
2317 {
2318   tree var, type, utype, tmp, tmp2, tmp3;
2319   tree list, stmt;
2320   tree cst, cst2, mask;
2321   tree minshift, maxshift;
2322
2323   if (TREE_CODE (dst) != BIT_FIELD_REF)
2324     return sra_build_assignment (dst, src);
2325
2326   var = TREE_OPERAND (dst, 0);
2327
2328   if (!scalar_bitfield_p (dst))
2329     return sra_build_assignment (REPLDUP (dst), src);
2330
2331   list = NULL;
2332
2333   cst = fold_convert (bitsizetype, TREE_OPERAND (dst, 2));
2334   cst2 = size_binop (PLUS_EXPR,
2335                      fold_convert (bitsizetype, TREE_OPERAND (dst, 1)),
2336                      cst);
2337
2338   if (BYTES_BIG_ENDIAN)
2339     {
2340       maxshift = size_binop (MINUS_EXPR, TYPE_SIZE (TREE_TYPE (var)), cst);
2341       minshift = size_binop (MINUS_EXPR, TYPE_SIZE (TREE_TYPE (var)), cst2);
2342     }
2343   else
2344     {
2345       maxshift = cst2;
2346       minshift = cst;
2347     }
2348
2349   type = TREE_TYPE (var);
2350   if (!INTEGRAL_TYPE_P (type))
2351     type = lang_hooks.types.type_for_size
2352       (TREE_INT_CST_LOW (TYPE_SIZE (TREE_TYPE (var))), 1);
2353   if (TYPE_UNSIGNED (type))
2354     utype = type;
2355   else
2356     utype = unsigned_type_for (type);
2357
2358   mask = build_int_cst_wide (utype, 1, 0);
2359   if (TREE_INT_CST_LOW (maxshift) == TYPE_PRECISION (utype))
2360     cst = build_int_cst_wide (utype, 0, 0);
2361   else
2362     cst = int_const_binop (LSHIFT_EXPR, mask, maxshift, true);
2363   if (integer_zerop (minshift))
2364     cst2 = mask;
2365   else
2366     cst2 = int_const_binop (LSHIFT_EXPR, mask, minshift, true);
2367   mask = int_const_binop (MINUS_EXPR, cst, cst2, true);
2368   mask = fold_build1 (BIT_NOT_EXPR, utype, mask);
2369
2370   if (TYPE_MAIN_VARIANT (utype) != TYPE_MAIN_VARIANT (TREE_TYPE (var))
2371       && !integer_zerop (mask))
2372     {
2373       tmp = var;
2374       if (!is_gimple_variable (tmp))
2375         tmp = unshare_expr (var);
2376
2377       tmp2 = make_rename_temp (utype, "SR");
2378
2379       if (INTEGRAL_TYPE_P (TREE_TYPE (var)))
2380         stmt = build_gimple_modify_stmt (tmp2, fold_convert (utype, tmp));
2381       else
2382         stmt = build_gimple_modify_stmt (tmp2, fold_build1 (VIEW_CONVERT_EXPR,
2383                                                             utype, tmp));
2384       append_to_statement_list (stmt, &list);
2385     }
2386   else
2387     tmp2 = var;
2388
2389   if (!integer_zerop (mask))
2390     {
2391       tmp = make_rename_temp (utype, "SR");
2392       stmt = build_gimple_modify_stmt (tmp,
2393                                        fold_build2 (BIT_AND_EXPR, utype,
2394                                                     tmp2, mask));
2395       append_to_statement_list (stmt, &list);
2396     }
2397   else
2398     tmp = mask;
2399
2400   if (is_gimple_reg (src) && INTEGRAL_TYPE_P (TREE_TYPE (src)))
2401     tmp2 = src;
2402   else if (INTEGRAL_TYPE_P (TREE_TYPE (src)))
2403     {
2404       tmp2 = make_rename_temp (TREE_TYPE (src), "SR");
2405       stmt = sra_build_assignment (tmp2, src);
2406       append_to_statement_list (stmt, &list);
2407     }
2408   else
2409     {
2410       tmp2 = make_rename_temp
2411         (lang_hooks.types.type_for_size
2412          (TREE_INT_CST_LOW (TYPE_SIZE (TREE_TYPE (src))),
2413           1), "SR");
2414       stmt = sra_build_assignment (tmp2, fold_build1 (VIEW_CONVERT_EXPR,
2415                                                       TREE_TYPE (tmp2), src));
2416       append_to_statement_list (stmt, &list);
2417     }
2418
2419   if (!TYPE_UNSIGNED (TREE_TYPE (tmp2)))
2420     {
2421       tree ut = unsigned_type_for (TREE_TYPE (tmp2));
2422       tmp3 = make_rename_temp (ut, "SR");
2423       tmp2 = fold_convert (ut, tmp2);
2424       stmt = sra_build_assignment (tmp3, tmp2);
2425       append_to_statement_list (stmt, &list);
2426
2427       tmp2 = fold_build1 (BIT_NOT_EXPR, utype, mask);
2428       tmp2 = int_const_binop (RSHIFT_EXPR, tmp2, minshift, true);
2429       tmp2 = fold_convert (ut, tmp2);
2430       tmp2 = fold_build2 (BIT_AND_EXPR, ut, tmp3, tmp2);
2431
2432       if (tmp3 != tmp2)
2433         {
2434           tmp3 = make_rename_temp (ut, "SR");
2435           stmt = sra_build_assignment (tmp3, tmp2);
2436           append_to_statement_list (stmt, &list);
2437         }
2438
2439       tmp2 = tmp3;
2440     }
2441
2442   if (TYPE_MAIN_VARIANT (TREE_TYPE (tmp2)) != TYPE_MAIN_VARIANT (utype))
2443     {
2444       tmp3 = make_rename_temp (utype, "SR");
2445       tmp2 = fold_convert (utype, tmp2);
2446       stmt = sra_build_assignment (tmp3, tmp2);
2447       append_to_statement_list (stmt, &list);
2448       tmp2 = tmp3;
2449     }
2450
2451   if (!integer_zerop (minshift))
2452     {
2453       tmp3 = make_rename_temp (utype, "SR");
2454       stmt = build_gimple_modify_stmt (tmp3,
2455                                        fold_build2 (LSHIFT_EXPR, utype,
2456                                                     tmp2, minshift));
2457       append_to_statement_list (stmt, &list);
2458       tmp2 = tmp3;
2459     }
2460
2461   if (utype != TREE_TYPE (var))
2462     tmp3 = make_rename_temp (utype, "SR");
2463   else
2464     tmp3 = var;
2465   stmt = build_gimple_modify_stmt (tmp3,
2466                                    fold_build2 (BIT_IOR_EXPR, utype,
2467                                                 tmp, tmp2));
2468   append_to_statement_list (stmt, &list);
2469
2470   if (tmp3 != var)
2471     {
2472       if (TREE_TYPE (var) == type)
2473         stmt = build_gimple_modify_stmt (var,
2474                                          fold_convert (type, tmp3));
2475       else
2476         stmt = build_gimple_modify_stmt (var,
2477                                          fold_build1 (VIEW_CONVERT_EXPR,
2478                                                       TREE_TYPE (var), tmp3));
2479       append_to_statement_list (stmt, &list);
2480     }
2481
2482   return list;
2483 }
2484
2485 /* Expand an assignment of SRC to the scalarized representation of
2486    ELT.  If it is a field group, try to widen the assignment to cover
2487    the full variable.  */
2488
2489 static tree
2490 sra_build_elt_assignment (struct sra_elt *elt, tree src)
2491 {
2492   tree dst = elt->replacement;
2493   tree var, tmp, cst, cst2, list, stmt;
2494
2495   if (TREE_CODE (dst) != BIT_FIELD_REF
2496       || !elt->in_bitfld_block)
2497     return sra_build_assignment (REPLDUP (dst), src);
2498
2499   var = TREE_OPERAND (dst, 0);
2500
2501   /* Try to widen the assignment to the entire variable.
2502      We need the source to be a BIT_FIELD_REF as well, such that, for
2503      BIT_FIELD_REF<d,sz,dp> = BIT_FIELD_REF<s,sz,sp>,
2504      by design, conditions are met such that we can turn it into
2505      d = BIT_FIELD_REF<s,dw,sp-dp>.  */
2506   if (elt->in_bitfld_block == 2
2507       && TREE_CODE (src) == BIT_FIELD_REF)
2508     {
2509       tmp = src;
2510       cst = TYPE_SIZE (TREE_TYPE (var));
2511       cst2 = size_binop (MINUS_EXPR, TREE_OPERAND (src, 2),
2512                          TREE_OPERAND (dst, 2));
2513
2514       src = TREE_OPERAND (src, 0);
2515
2516       /* Avoid full-width bit-fields.  */
2517       if (integer_zerop (cst2)
2518           && tree_int_cst_equal (cst, TYPE_SIZE (TREE_TYPE (src))))
2519         {
2520           if (INTEGRAL_TYPE_P (TREE_TYPE (src))
2521               && !TYPE_UNSIGNED (TREE_TYPE (src)))
2522             src = fold_convert (unsigned_type_for (TREE_TYPE (src)), src);
2523
2524           /* If a single conversion won't do, we'll need a statement
2525              list.  */
2526           if (TYPE_MAIN_VARIANT (TREE_TYPE (var))
2527               != TYPE_MAIN_VARIANT (TREE_TYPE (src)))
2528             {
2529               list = NULL;
2530
2531               if (!INTEGRAL_TYPE_P (TREE_TYPE (src)))
2532                 src = fold_build1 (VIEW_CONVERT_EXPR,
2533                                    lang_hooks.types.type_for_size
2534                                    (TREE_INT_CST_LOW
2535                                     (TYPE_SIZE (TREE_TYPE (src))),
2536                                     1), src);
2537               gcc_assert (TYPE_UNSIGNED (TREE_TYPE (src)));
2538
2539               tmp = make_rename_temp (TREE_TYPE (src), "SR");
2540               stmt = build_gimple_modify_stmt (tmp, src);
2541               append_to_statement_list (stmt, &list);
2542
2543               stmt = sra_build_assignment (var,
2544                                            fold_convert (TREE_TYPE (var),
2545                                                          tmp));
2546               append_to_statement_list (stmt, &list);
2547
2548               return list;
2549             }
2550
2551           src = fold_convert (TREE_TYPE (var), src);
2552         }
2553       else
2554         {
2555           src = fold_convert (TREE_TYPE (var), tmp);
2556         }
2557
2558       return sra_build_assignment (var, src);
2559     }
2560
2561   return sra_build_bf_assignment (dst, src);
2562 }
2563
2564 /* Generate a set of assignment statements in *LIST_P to copy all
2565    instantiated elements under ELT to or from the equivalent structure
2566    rooted at EXPR.  COPY_OUT controls the direction of the copy, with
2567    true meaning to copy out of EXPR into ELT.  */
2568
2569 static void
2570 generate_copy_inout (struct sra_elt *elt, bool copy_out, tree expr,
2571                      tree *list_p)
2572 {
2573   struct sra_elt *c;
2574   tree t;
2575
2576   if (!copy_out && TREE_CODE (expr) == SSA_NAME
2577       && TREE_CODE (TREE_TYPE (expr)) == COMPLEX_TYPE)
2578     {
2579       tree r, i;
2580
2581       c = lookup_element (elt, integer_zero_node, NULL, NO_INSERT);
2582       r = c->replacement;
2583       c = lookup_element (elt, integer_one_node, NULL, NO_INSERT);
2584       i = c->replacement;
2585
2586       t = build2 (COMPLEX_EXPR, elt->type, r, i);
2587       t = sra_build_bf_assignment (expr, t);
2588       SSA_NAME_DEF_STMT (expr) = t;
2589       append_to_statement_list (t, list_p);
2590     }
2591   else if (elt->replacement)
2592     {
2593       if (copy_out)
2594         t = sra_build_elt_assignment (elt, expr);
2595       else
2596         t = sra_build_bf_assignment (expr, REPLDUP (elt->replacement));
2597       append_to_statement_list (t, list_p);
2598     }
2599   else
2600     {
2601       FOR_EACH_ACTUAL_CHILD (c, elt)
2602         {
2603           t = generate_one_element_ref (c, unshare_expr (expr));
2604           generate_copy_inout (c, copy_out, t, list_p);
2605         }
2606     }
2607 }
2608
2609 /* Generate a set of assignment statements in *LIST_P to copy all instantiated
2610    elements under SRC to their counterparts under DST.  There must be a 1-1
2611    correspondence of instantiated elements.  */
2612
2613 static void
2614 generate_element_copy (struct sra_elt *dst, struct sra_elt *src, tree *list_p)
2615 {
2616   struct sra_elt *dc, *sc;
2617
2618   FOR_EACH_ACTUAL_CHILD (dc, dst)
2619     {
2620       sc = lookup_element (src, dc->element, NULL, NO_INSERT);
2621       if (!sc && dc->in_bitfld_block == 2)
2622         {
2623           struct sra_elt *dcs;
2624
2625           FOR_EACH_ACTUAL_CHILD (dcs, dc)
2626             {
2627               sc = lookup_element (src, dcs->element, NULL, NO_INSERT);
2628               gcc_assert (sc);
2629               generate_element_copy (dcs, sc, list_p);
2630             }
2631
2632           continue;
2633         }
2634
2635       /* If DST and SRC are structs with the same elements, but do not have
2636          the same TYPE_MAIN_VARIANT, then lookup of DST FIELD_DECL in SRC
2637          will fail.  Try harder by finding the corresponding FIELD_DECL
2638          in SRC.  */
2639       if (!sc)
2640         {
2641           tree f;
2642
2643           gcc_assert (useless_type_conversion_p (dst->type, src->type));
2644           gcc_assert (TREE_CODE (dc->element) == FIELD_DECL);
2645           for (f = TYPE_FIELDS (src->type); f ; f = TREE_CHAIN (f))
2646             if (simple_cst_equal (DECL_FIELD_OFFSET (f),
2647                                   DECL_FIELD_OFFSET (dc->element)) > 0
2648                 && simple_cst_equal (DECL_FIELD_BIT_OFFSET (f),
2649                                      DECL_FIELD_BIT_OFFSET (dc->element)) > 0
2650                 && simple_cst_equal (DECL_SIZE (f),
2651                                      DECL_SIZE (dc->element)) > 0
2652                 && (useless_type_conversion_p (TREE_TYPE (dc->element),
2653                                                TREE_TYPE (f))
2654                     || (POINTER_TYPE_P (TREE_TYPE (dc->element))
2655                         && POINTER_TYPE_P (TREE_TYPE (f)))))
2656               break;
2657           gcc_assert (f != NULL_TREE);
2658           sc = lookup_element (src, f, NULL, NO_INSERT);
2659         }
2660
2661       generate_element_copy (dc, sc, list_p);
2662     }
2663
2664   if (dst->replacement)
2665     {
2666       tree t;
2667
2668       gcc_assert (src->replacement);
2669
2670       t = sra_build_elt_assignment (dst, REPLDUP (src->replacement));
2671       append_to_statement_list (t, list_p);
2672     }
2673 }
2674
2675 /* Generate a set of assignment statements in *LIST_P to zero all instantiated
2676    elements under ELT.  In addition, do not assign to elements that have been
2677    marked VISITED but do reset the visited flag; this allows easy coordination
2678    with generate_element_init.  */
2679
2680 static void
2681 generate_element_zero (struct sra_elt *elt, tree *list_p)
2682 {
2683   struct sra_elt *c;
2684
2685   if (elt->visited)
2686     {
2687       elt->visited = false;
2688       return;
2689     }
2690
2691   if (!elt->in_bitfld_block)
2692     FOR_EACH_ACTUAL_CHILD (c, elt)
2693       generate_element_zero (c, list_p);
2694
2695   if (elt->replacement)
2696     {
2697       tree t;
2698
2699       gcc_assert (elt->is_scalar);
2700       t = fold_convert (elt->type, integer_zero_node);
2701
2702       t = sra_build_elt_assignment (elt, t);
2703       append_to_statement_list (t, list_p);
2704     }
2705 }
2706
2707 /* Generate an assignment VAR = INIT, where INIT may need gimplification.
2708    Add the result to *LIST_P.  */
2709
2710 static void
2711 generate_one_element_init (struct sra_elt *elt, tree init, tree *list_p)
2712 {
2713   /* The replacement can be almost arbitrarily complex.  Gimplify.  */
2714   tree stmt = sra_build_elt_assignment (elt, init);
2715   gimplify_and_add (stmt, list_p);
2716 }
2717
2718 /* Generate a set of assignment statements in *LIST_P to set all instantiated
2719    elements under ELT with the contents of the initializer INIT.  In addition,
2720    mark all assigned elements VISITED; this allows easy coordination with
2721    generate_element_zero.  Return false if we found a case we couldn't
2722    handle.  */
2723
2724 static bool
2725 generate_element_init_1 (struct sra_elt *elt, tree init, tree *list_p)
2726 {
2727   bool result = true;
2728   enum tree_code init_code;
2729   struct sra_elt *sub;
2730   tree t;
2731   unsigned HOST_WIDE_INT idx;
2732   tree value, purpose;
2733
2734   /* We can be passed DECL_INITIAL of a static variable.  It might have a
2735      conversion, which we strip off here.  */
2736   STRIP_USELESS_TYPE_CONVERSION (init);
2737   init_code = TREE_CODE (init);
2738
2739   if (elt->is_scalar)
2740     {
2741       if (elt->replacement)
2742         {
2743           generate_one_element_init (elt, init, list_p);
2744           elt->visited = true;
2745         }
2746       return result;
2747     }
2748
2749   switch (init_code)
2750     {
2751     case COMPLEX_CST:
2752     case COMPLEX_EXPR:
2753       FOR_EACH_ACTUAL_CHILD (sub, elt)
2754         {
2755           if (sub->element == integer_zero_node)
2756             t = (init_code == COMPLEX_EXPR
2757                  ? TREE_OPERAND (init, 0) : TREE_REALPART (init));
2758           else
2759             t = (init_code == COMPLEX_EXPR
2760                  ? TREE_OPERAND (init, 1) : TREE_IMAGPART (init));
2761           result &= generate_element_init_1 (sub, t, list_p);
2762         }
2763       break;
2764
2765     case CONSTRUCTOR:
2766       FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (init), idx, purpose, value)
2767         {
2768           if (TREE_CODE (purpose) == RANGE_EXPR)
2769             {
2770               tree lower = TREE_OPERAND (purpose, 0);
2771               tree upper = TREE_OPERAND (purpose, 1);
2772
2773               while (1)
2774                 {
2775                   sub = lookup_element (elt, lower, NULL, NO_INSERT);
2776                   if (sub != NULL)
2777                     result &= generate_element_init_1 (sub, value, list_p);
2778                   if (tree_int_cst_equal (lower, upper))
2779                     break;
2780                   lower = int_const_binop (PLUS_EXPR, lower,
2781                                            integer_one_node, true);
2782                 }
2783             }
2784           else
2785             {
2786               sub = lookup_element (elt, purpose, NULL, NO_INSERT);
2787               if (sub != NULL)
2788                 result &= generate_element_init_1 (sub, value, list_p);
2789             }
2790         }
2791       break;
2792
2793     default:
2794       elt->visited = true;
2795       result = false;
2796     }
2797
2798   return result;
2799 }
2800
2801 /* A wrapper function for generate_element_init_1 that handles cleanup after
2802    gimplification.  */
2803
2804 static bool
2805 generate_element_init (struct sra_elt *elt, tree init, tree *list_p)
2806 {
2807   bool ret;
2808
2809   push_gimplify_context ();
2810   ret = generate_element_init_1 (elt, init, list_p);
2811   pop_gimplify_context (NULL);
2812
2813   /* The replacement can expose previously unreferenced variables.  */
2814   if (ret && *list_p)
2815     {
2816       tree_stmt_iterator i;
2817
2818       for (i = tsi_start (*list_p); !tsi_end_p (i); tsi_next (&i))
2819         find_new_referenced_vars (tsi_stmt_ptr (i));
2820     }
2821
2822   return ret;
2823 }
2824
2825 /* Insert STMT on all the outgoing edges out of BB.  Note that if BB
2826    has more than one edge, STMT will be replicated for each edge.  Also,
2827    abnormal edges will be ignored.  */
2828
2829 void
2830 insert_edge_copies (tree stmt, basic_block bb)
2831 {
2832   edge e;
2833   edge_iterator ei;
2834   bool first_copy;
2835
2836   first_copy = true;
2837   FOR_EACH_EDGE (e, ei, bb->succs)
2838     {
2839       /* We don't need to insert copies on abnormal edges.  The
2840          value of the scalar replacement is not guaranteed to
2841          be valid through an abnormal edge.  */
2842       if (!(e->flags & EDGE_ABNORMAL))
2843         {
2844           if (first_copy)
2845             {
2846               bsi_insert_on_edge (e, stmt);
2847               first_copy = false;
2848             }
2849           else
2850             bsi_insert_on_edge (e, unsave_expr_now (stmt));
2851         }
2852     }
2853 }
2854
2855 /* Helper function to insert LIST before BSI, and set up line number info.  */
2856
2857 void
2858 sra_insert_before (block_stmt_iterator *bsi, tree list)
2859 {
2860   tree stmt = bsi_stmt (*bsi);
2861
2862   if (EXPR_HAS_LOCATION (stmt))
2863     annotate_all_with_locus (&list, EXPR_LOCATION (stmt));
2864   bsi_insert_before (bsi, list, BSI_SAME_STMT);
2865 }
2866
2867 /* Similarly, but insert after BSI.  Handles insertion onto edges as well.  */
2868
2869 void
2870 sra_insert_after (block_stmt_iterator *bsi, tree list)
2871 {
2872   tree stmt = bsi_stmt (*bsi);
2873
2874   if (EXPR_HAS_LOCATION (stmt))
2875     annotate_all_with_locus (&list, EXPR_LOCATION (stmt));
2876
2877   if (stmt_ends_bb_p (stmt))
2878     insert_edge_copies (list, bsi->bb);
2879   else
2880     bsi_insert_after (bsi, list, BSI_SAME_STMT);
2881 }
2882
2883 /* Similarly, but replace the statement at BSI.  */
2884
2885 static void
2886 sra_replace (block_stmt_iterator *bsi, tree list)
2887 {
2888   sra_insert_before (bsi, list);
2889   bsi_remove (bsi, false);
2890   if (bsi_end_p (*bsi))
2891     *bsi = bsi_last (bsi->bb);
2892   else
2893     bsi_prev (bsi);
2894 }
2895
2896 /* Data structure that bitfield_overlaps_p fills in with information
2897    about the element passed in and how much of it overlaps with the
2898    bit-range passed it to.  */
2899
2900 struct bitfield_overlap_info
2901 {
2902   /* The bit-length of an element.  */
2903   tree field_len;
2904
2905   /* The bit-position of the element in its parent.  */
2906   tree field_pos;
2907
2908   /* The number of bits of the element that overlap with the incoming
2909      bit range.  */
2910   tree overlap_len;
2911
2912   /* The first bit of the element that overlaps with the incoming bit
2913      range.  */
2914   tree overlap_pos;
2915 };
2916
2917 /* Return true if a BIT_FIELD_REF<(FLD->parent), BLEN, BPOS>
2918    expression (referenced as BF below) accesses any of the bits in FLD,
2919    false if it doesn't.  If DATA is non-null, its field_len and
2920    field_pos are filled in such that BIT_FIELD_REF<(FLD->parent),
2921    field_len, field_pos> (referenced as BFLD below) represents the
2922    entire field FLD->element, and BIT_FIELD_REF<BFLD, overlap_len,
2923    overlap_pos> represents the portion of the entire field that
2924    overlaps with BF.  */
2925
2926 static bool
2927 bitfield_overlaps_p (tree blen, tree bpos, struct sra_elt *fld,
2928                      struct bitfield_overlap_info *data)
2929 {
2930   tree flen, fpos;
2931   bool ret;
2932
2933   if (TREE_CODE (fld->element) == FIELD_DECL)
2934     {
2935       flen = fold_convert (bitsizetype, DECL_SIZE (fld->element));
2936       fpos = fold_convert (bitsizetype, DECL_FIELD_OFFSET (fld->element));
2937       fpos = size_binop (MULT_EXPR, fpos, bitsize_int (BITS_PER_UNIT));
2938       fpos = size_binop (PLUS_EXPR, fpos, DECL_FIELD_BIT_OFFSET (fld->element));
2939     }
2940   else if (TREE_CODE (fld->element) == BIT_FIELD_REF)
2941     {
2942       flen = fold_convert (bitsizetype, TREE_OPERAND (fld->element, 1));
2943       fpos = fold_convert (bitsizetype, TREE_OPERAND (fld->element, 2));
2944     }
2945   else if (TREE_CODE (fld->element) == INTEGER_CST)
2946     {
2947       flen = fold_convert (bitsizetype, TYPE_SIZE (fld->type));
2948       fpos = fold_convert (bitsizetype, fld->element);
2949       fpos = size_binop (MULT_EXPR, flen, fpos);
2950     }
2951   else
2952     gcc_unreachable ();
2953
2954   gcc_assert (host_integerp (blen, 1)
2955               && host_integerp (bpos, 1)
2956               && host_integerp (flen, 1)
2957               && host_integerp (fpos, 1));
2958
2959   ret = ((!tree_int_cst_lt (fpos, bpos)
2960           && tree_int_cst_lt (size_binop (MINUS_EXPR, fpos, bpos),
2961                               blen))
2962          || (!tree_int_cst_lt (bpos, fpos)
2963              && tree_int_cst_lt (size_binop (MINUS_EXPR, bpos, fpos),
2964                                  flen)));
2965
2966   if (!ret)
2967     return ret;
2968
2969   if (data)
2970     {
2971       tree bend, fend;
2972
2973       data->field_len = flen;
2974       data->field_pos = fpos;
2975
2976       fend = size_binop (PLUS_EXPR, fpos, flen);
2977       bend = size_binop (PLUS_EXPR, bpos, blen);
2978
2979       if (tree_int_cst_lt (bend, fend))
2980         data->overlap_len = size_binop (MINUS_EXPR, bend, fpos);
2981       else
2982         data->overlap_len = NULL;
2983
2984       if (tree_int_cst_lt (fpos, bpos))
2985         {
2986           data->overlap_pos = size_binop (MINUS_EXPR, bpos, fpos);
2987           data->overlap_len = size_binop (MINUS_EXPR,
2988                                           data->overlap_len
2989                                           ? data->overlap_len
2990                                           : data->field_len,
2991                                           data->overlap_pos);
2992         }
2993       else
2994         data->overlap_pos = NULL;
2995     }
2996
2997   return ret;
2998 }
2999
3000 /* Add to LISTP a sequence of statements that copies BLEN bits between
3001    VAR and the scalarized elements of ELT, starting a bit VPOS of VAR
3002    and at bit BPOS of ELT.  The direction of the copy is given by
3003    TO_VAR.  */
3004
3005 static void
3006 sra_explode_bitfield_assignment (tree var, tree vpos, bool to_var,
3007                                  tree *listp, tree blen, tree bpos,
3008                                  struct sra_elt *elt)
3009 {
3010   struct sra_elt *fld;
3011   struct bitfield_overlap_info flp;
3012
3013   FOR_EACH_ACTUAL_CHILD (fld, elt)
3014     {
3015       tree flen, fpos;
3016
3017       if (!bitfield_overlaps_p (blen, bpos, fld, &flp))
3018         continue;
3019
3020       flen = flp.overlap_len ? flp.overlap_len : flp.field_len;
3021       fpos = flp.overlap_pos ? flp.overlap_pos : bitsize_int (0);
3022
3023       if (fld->replacement)
3024         {
3025           tree infld, invar, st, type;
3026
3027           infld = fld->replacement;
3028
3029           type = TREE_TYPE (infld);
3030           if (TYPE_PRECISION (type) != TREE_INT_CST_LOW (flen))
3031             type = lang_hooks.types.type_for_size (TREE_INT_CST_LOW (flen), 1);
3032           else
3033             type = unsigned_type_for (type);
3034
3035           if (TREE_CODE (infld) == BIT_FIELD_REF)
3036             {
3037               fpos = size_binop (PLUS_EXPR, fpos, TREE_OPERAND (infld, 2));
3038               infld = TREE_OPERAND (infld, 0);
3039             }
3040           else if (BYTES_BIG_ENDIAN && DECL_P (fld->element)
3041                    && !tree_int_cst_equal (TYPE_SIZE (TREE_TYPE (infld)),
3042                                            DECL_SIZE (fld->element)))
3043             {
3044               fpos = size_binop (PLUS_EXPR, fpos,
3045                                  TYPE_SIZE (TREE_TYPE (infld)));
3046               fpos = size_binop (MINUS_EXPR, fpos,
3047                                  DECL_SIZE (fld->element));
3048             }
3049
3050           infld = fold_build3 (BIT_FIELD_REF, type, infld, flen, fpos);
3051
3052           invar = size_binop (MINUS_EXPR, flp.field_pos, bpos);
3053           if (flp.overlap_pos)
3054             invar = size_binop (PLUS_EXPR, invar, flp.overlap_pos);
3055           invar = size_binop (PLUS_EXPR, invar, vpos);
3056
3057           invar = fold_build3 (BIT_FIELD_REF, type, var, flen, invar);
3058
3059           if (to_var)
3060             st = sra_build_bf_assignment (invar, infld);
3061           else
3062             st = sra_build_bf_assignment (infld, invar);
3063
3064           append_to_statement_list (st, listp);
3065         }
3066       else
3067         {
3068           tree sub = size_binop (MINUS_EXPR, flp.field_pos, bpos);
3069           sub = size_binop (PLUS_EXPR, vpos, sub);
3070           if (flp.overlap_pos)
3071             sub = size_binop (PLUS_EXPR, sub, flp.overlap_pos);
3072
3073           sra_explode_bitfield_assignment (var, sub, to_var, listp,
3074                                            flen, fpos, fld);
3075         }
3076     }
3077 }
3078
3079 /* Add to LISTBEFOREP statements that copy scalarized members of ELT
3080    that overlap with BIT_FIELD_REF<(ELT->element), BLEN, BPOS> back
3081    into the full variable, and to LISTAFTERP, if non-NULL, statements
3082    that copy the (presumably modified) overlapping portions of the
3083    full variable back to the scalarized variables.  */
3084
3085 static void
3086 sra_sync_for_bitfield_assignment (tree *listbeforep, tree *listafterp,
3087                                   tree blen, tree bpos,
3088                                   struct sra_elt *elt)
3089 {
3090   struct sra_elt *fld;
3091   struct bitfield_overlap_info flp;
3092
3093   FOR_EACH_ACTUAL_CHILD (fld, elt)
3094     if (bitfield_overlaps_p (blen, bpos, fld, &flp))
3095       {
3096         if (fld->replacement || (!flp.overlap_len && !flp.overlap_pos))
3097           {
3098             generate_copy_inout (fld, false, generate_element_ref (fld),
3099                                  listbeforep);
3100             mark_no_warning (fld);
3101             if (listafterp)
3102               generate_copy_inout (fld, true, generate_element_ref (fld),
3103                                    listafterp);
3104           }
3105         else
3106           {
3107             tree flen = flp.overlap_len ? flp.overlap_len : flp.field_len;
3108             tree fpos = flp.overlap_pos ? flp.overlap_pos : bitsize_int (0);
3109
3110             sra_sync_for_bitfield_assignment (listbeforep, listafterp,
3111                                               flen, fpos, fld);
3112           }
3113       }
3114 }
3115
3116 /* Scalarize a USE.  To recap, this is either a simple reference to ELT,
3117    if elt is scalar, or some occurrence of ELT that requires a complete
3118    aggregate.  IS_OUTPUT is true if ELT is being modified.  */
3119
3120 static void
3121 scalarize_use (struct sra_elt *elt, tree *expr_p, block_stmt_iterator *bsi,
3122                bool is_output, bool use_all)
3123 {
3124   tree stmt = bsi_stmt (*bsi);
3125   tree bfexpr;
3126
3127   if (elt->replacement)
3128     {
3129       tree replacement = elt->replacement;
3130
3131       /* If we have a replacement, then updating the reference is as
3132          simple as modifying the existing statement in place.  */
3133       if (is_output
3134           && TREE_CODE (elt->replacement) == BIT_FIELD_REF
3135           && is_gimple_reg (TREE_OPERAND (elt->replacement, 0))
3136           && TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
3137           && &GIMPLE_STMT_OPERAND (stmt, 0) == expr_p)
3138         {
3139           tree newstmt = sra_build_elt_assignment
3140             (elt, GIMPLE_STMT_OPERAND (stmt, 1));
3141           if (TREE_CODE (newstmt) != STATEMENT_LIST)
3142             {
3143               tree list = NULL;
3144               append_to_statement_list (newstmt, &list);
3145               newstmt = list;
3146             }
3147           sra_replace (bsi, newstmt);
3148           return;
3149         }
3150       else if (!is_output
3151                && TREE_CODE (elt->replacement) == BIT_FIELD_REF
3152                && TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
3153                && &GIMPLE_STMT_OPERAND (stmt, 1) == expr_p)
3154         {
3155           tree tmp = make_rename_temp
3156             (TREE_TYPE (GIMPLE_STMT_OPERAND (stmt, 0)), "SR");
3157           tree newstmt = sra_build_assignment (tmp, REPLDUP (elt->replacement));
3158
3159           if (TREE_CODE (newstmt) != STATEMENT_LIST)
3160             {
3161               tree list = NULL;
3162               append_to_statement_list (newstmt, &list);
3163               newstmt = list;
3164             }
3165           sra_insert_before (bsi, newstmt);
3166           replacement = tmp;
3167         }
3168       if (is_output)
3169           mark_all_v_defs (stmt);
3170       *expr_p = REPLDUP (replacement);
3171       update_stmt (stmt);
3172     }
3173   else if (use_all && is_output
3174            && TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
3175            && TREE_CODE (bfexpr
3176                          = GIMPLE_STMT_OPERAND (stmt, 0)) == BIT_FIELD_REF
3177            && &TREE_OPERAND (bfexpr, 0) == expr_p
3178            && INTEGRAL_TYPE_P (TREE_TYPE (bfexpr))
3179            && TREE_CODE (TREE_TYPE (*expr_p)) == RECORD_TYPE)
3180     {
3181       tree listbefore = NULL, listafter = NULL;
3182       tree blen = fold_convert (bitsizetype, TREE_OPERAND (bfexpr, 1));
3183       tree bpos = fold_convert (bitsizetype, TREE_OPERAND (bfexpr, 2));
3184       bool update = false;
3185
3186       if (!elt->use_block_copy)
3187         {
3188           tree type = TREE_TYPE (bfexpr);
3189           tree var = make_rename_temp (type, "SR"), tmp, st, vpos;
3190
3191           GIMPLE_STMT_OPERAND (stmt, 0) = var;
3192           update = true;
3193
3194           if (!TYPE_UNSIGNED (type))
3195             {
3196               type = unsigned_type_for (type);
3197               tmp = make_rename_temp (type, "SR");
3198               st = build_gimple_modify_stmt (tmp,
3199                                              fold_convert (type, var));
3200               append_to_statement_list (st, &listafter);
3201               var = tmp;
3202             }
3203
3204           /* If VAR is wider than BLEN bits, it is padded at the
3205              most-significant end.  We want to set VPOS such that
3206              <BIT_FIELD_REF VAR BLEN VPOS> would refer to the
3207              least-significant BLEN bits of VAR.  */
3208           if (BYTES_BIG_ENDIAN)
3209             vpos = size_binop (MINUS_EXPR, TYPE_SIZE (type), blen);
3210           else
3211             vpos = bitsize_int (0);
3212           sra_explode_bitfield_assignment
3213             (var, vpos, false, &listafter, blen, bpos, elt);
3214         }
3215       else
3216         sra_sync_for_bitfield_assignment
3217           (&listbefore, &listafter, blen, bpos, elt);
3218
3219       if (listbefore)
3220         {
3221           mark_all_v_defs (listbefore);
3222           sra_insert_before (bsi, listbefore);
3223         }
3224       if (listafter)
3225         {
3226           mark_all_v_defs (listafter);
3227           sra_insert_after (bsi, listafter);
3228         }
3229
3230       if (update)
3231         update_stmt (stmt);
3232     }
3233   else if (use_all && !is_output
3234            && TREE_CODE (stmt) == GIMPLE_MODIFY_STMT
3235            && TREE_CODE (bfexpr
3236                          = GIMPLE_STMT_OPERAND (stmt, 1)) == BIT_FIELD_REF
3237            && &TREE_OPERAND (GIMPLE_STMT_OPERAND (stmt, 1), 0) == expr_p
3238            && INTEGRAL_TYPE_P (TREE_TYPE (bfexpr))
3239            && TREE_CODE (TREE_TYPE (*expr_p)) == RECORD_TYPE)
3240     {
3241       tree list = NULL;
3242       tree blen = fold_convert (bitsizetype, TREE_OPERAND (bfexpr, 1));
3243       tree bpos = fold_convert (bitsizetype, TREE_OPERAND (bfexpr, 2));
3244       bool update = false;
3245
3246       if (!elt->use_block_copy)
3247         {
3248           tree type = TREE_TYPE (bfexpr);
3249           tree var, vpos;
3250
3251           if (!TYPE_UNSIGNED (type))
3252             type = unsigned_type_for (type);
3253
3254           var = make_rename_temp (type, "SR");
3255
3256           append_to_statement_list (build_gimple_modify_stmt
3257                                     (var, build_int_cst_wide (type, 0, 0)),
3258                                     &list);
3259
3260           /* If VAR is wider than BLEN bits, it is padded at the
3261              most-significant end.  We want to set VPOS such that
3262              <BIT_FIELD_REF VAR BLEN VPOS> would refer to the
3263              least-significant BLEN bits of VAR.  */
3264           if (BYTES_BIG_ENDIAN)
3265             vpos = size_binop (MINUS_EXPR, TYPE_SIZE (type), blen);
3266           else
3267             vpos = bitsize_int (0);
3268           sra_explode_bitfield_assignment
3269             (var, vpos, true, &list, blen, bpos, elt);
3270
3271           GIMPLE_STMT_OPERAND (stmt, 1) = var;
3272           update = true;
3273         }
3274       else
3275         sra_sync_for_bitfield_assignment
3276           (&list, NULL, blen, bpos, elt);
3277
3278       if (list)
3279         {
3280           mark_all_v_defs (list);
3281           sra_insert_before (bsi, list);
3282         }
3283
3284       if (update)
3285         update_stmt (stmt);
3286     }
3287   else
3288     {
3289       tree list = NULL;
3290
3291       /* Otherwise we need some copies.  If ELT is being read, then we
3292          want to store all (modified) sub-elements back into the
3293          structure before the reference takes place.  If ELT is being
3294          written, then we want to load the changed values back into
3295          our shadow variables.  */
3296       /* ??? We don't check modified for reads, we just always write all of
3297          the values.  We should be able to record the SSA number of the VOP
3298          for which the values were last read.  If that number matches the
3299          SSA number of the VOP in the current statement, then we needn't
3300          emit an assignment.  This would also eliminate double writes when
3301          a structure is passed as more than one argument to a function call.
3302          This optimization would be most effective if sra_walk_function
3303          processed the blocks in dominator order.  */
3304
3305       generate_copy_inout (elt, is_output, generate_element_ref (elt), &list);
3306       if (list == NULL)
3307         return;
3308       mark_all_v_defs (list);
3309       if (is_output)
3310         sra_insert_after (bsi, list);
3311       else
3312         {
3313           sra_insert_before (bsi, list);
3314           if (use_all)
3315             mark_no_warning (elt);
3316         }
3317     }
3318 }
3319
3320 /* Scalarize a COPY.  To recap, this is an assignment statement between
3321    two scalarizable references, LHS_ELT and RHS_ELT.  */
3322
3323 static void
3324 scalarize_copy (struct sra_elt *lhs_elt, struct sra_elt *rhs_elt,
3325                 block_stmt_iterator *bsi)
3326 {
3327   tree list, stmt;
3328
3329   if (lhs_elt->replacement && rhs_elt->replacement)
3330     {
3331       /* If we have two scalar operands, modify the existing statement.  */
3332       stmt = bsi_stmt (*bsi);
3333
3334       /* See the commentary in sra_walk_function concerning
3335          RETURN_EXPR, and why we should never see one here.  */
3336       gcc_assert (TREE_CODE (stmt) == GIMPLE_MODIFY_STMT);
3337
3338       GIMPLE_STMT_OPERAND (stmt, 0) = lhs_elt->replacement;
3339       GIMPLE_STMT_OPERAND (stmt, 1) = REPLDUP (rhs_elt->replacement);
3340       update_stmt (stmt);
3341     }
3342   else if (lhs_elt->use_block_copy || rhs_elt->use_block_copy)
3343     {
3344       /* If either side requires a block copy, then sync the RHS back
3345          to the original structure, leave the original assignment
3346          statement (which will perform the block copy), then load the
3347          LHS values out of its now-updated original structure.  */
3348       /* ??? Could perform a modified pair-wise element copy.  That
3349          would at least allow those elements that are instantiated in
3350          both structures to be optimized well.  */
3351
3352       list = NULL;
3353       generate_copy_inout (rhs_elt, false,
3354                            generate_element_ref (rhs_elt), &list);
3355       if (list)
3356         {
3357           mark_all_v_defs (list);
3358           sra_insert_before (bsi, list);
3359         }
3360
3361       list = NULL;
3362       generate_copy_inout (lhs_elt, true,
3363                            generate_element_ref (lhs_elt), &list);
3364       if (list)
3365         {
3366           mark_all_v_defs (list);
3367           sra_insert_after (bsi, list);
3368         }
3369     }
3370   else
3371     {
3372       /* Otherwise both sides must be fully instantiated.  In which
3373          case perform pair-wise element assignments and replace the
3374          original block copy statement.  */
3375
3376       stmt = bsi_stmt (*bsi);
3377       mark_all_v_defs (stmt);
3378
3379       list = NULL;
3380       generate_element_copy (lhs_elt, rhs_elt, &list);
3381       gcc_assert (list);
3382       mark_all_v_defs (list);
3383       sra_replace (bsi, list);
3384     }
3385 }
3386
3387 /* Scalarize an INIT.  To recap, this is an assignment to a scalarizable
3388    reference from some form of constructor: CONSTRUCTOR, COMPLEX_CST or
3389    COMPLEX_EXPR.  If RHS is NULL, it should be treated as an empty
3390    CONSTRUCTOR.  */
3391
3392 static void
3393 scalarize_init (struct sra_elt *lhs_elt, tree rhs, block_stmt_iterator *bsi)
3394 {
3395   bool result = true;
3396   tree list = NULL, init_list = NULL;
3397
3398   /* Generate initialization statements for all members extant in the RHS.  */
3399   if (rhs)
3400     {
3401       /* Unshare the expression just in case this is from a decl's initial.  */
3402       rhs = unshare_expr (rhs);
3403       result = generate_element_init (lhs_elt, rhs, &init_list);
3404     }
3405
3406   /* CONSTRUCTOR is defined such that any member not mentioned is assigned
3407      a zero value.  Initialize the rest of the instantiated elements.  */
3408   generate_element_zero (lhs_elt, &list);
3409   append_to_statement_list (init_list, &list);
3410
3411   if (!result)
3412     {
3413       /* If we failed to convert the entire initializer, then we must
3414          leave the structure assignment in place and must load values
3415          from the structure into the slots for which we did not find
3416          constants.  The easiest way to do this is to generate a complete
3417          copy-out, and then follow that with the constant assignments
3418          that we were able to build.  DCE will clean things up.  */
3419       tree list0 = NULL;
3420       generate_copy_inout (lhs_elt, true, generate_element_ref (lhs_elt),
3421                            &list0);
3422       append_to_statement_list (list, &list0);
3423       list = list0;
3424     }
3425
3426   if (lhs_elt->use_block_copy || !result)
3427     {
3428       /* Since LHS is not fully instantiated, we must leave the structure
3429          assignment in place.  Treating this case differently from a USE
3430          exposes constants to later optimizations.  */
3431       if (list)
3432         {
3433           mark_all_v_defs (list);
3434           sra_insert_after (bsi, list);
3435         }
3436     }
3437   else
3438     {
3439       /* The LHS is fully instantiated.  The list of initializations
3440          replaces the original structure assignment.  */
3441       gcc_assert (list);
3442       mark_all_v_defs (bsi_stmt (*bsi));
3443       mark_all_v_defs (list);
3444       sra_replace (bsi, list);
3445     }
3446 }
3447
3448 /* A subroutine of scalarize_ldst called via walk_tree.  Set TREE_NO_TRAP
3449    on all INDIRECT_REFs.  */
3450
3451 static tree
3452 mark_notrap (tree *tp, int *walk_subtrees, void *data ATTRIBUTE_UNUSED)
3453 {
3454   tree t = *tp;
3455
3456   if (TREE_CODE (t) == INDIRECT_REF)
3457     {
3458       TREE_THIS_NOTRAP (t) = 1;
3459       *walk_subtrees = 0;
3460     }
3461   else if (IS_TYPE_OR_DECL_P (t))
3462     *walk_subtrees = 0;
3463
3464   return NULL;
3465 }
3466
3467 /* Scalarize a LDST.  To recap, this is an assignment between one scalarizable
3468    reference ELT and one non-scalarizable reference OTHER.  IS_OUTPUT is true
3469    if ELT is on the left-hand side.  */
3470
3471 static void
3472 scalarize_ldst (struct sra_elt *elt, tree other,
3473                 block_stmt_iterator *bsi, bool is_output)
3474 {
3475   /* Shouldn't have gotten called for a scalar.  */
3476   gcc_assert (!elt->replacement);
3477
3478   if (elt->use_block_copy)
3479     {
3480       /* Since ELT is not fully instantiated, we have to leave the
3481          block copy in place.  Treat this as a USE.  */
3482       scalarize_use (elt, NULL, bsi, is_output, false);
3483     }
3484   else
3485     {
3486       /* The interesting case is when ELT is fully instantiated.  In this
3487          case we can have each element stored/loaded directly to/from the
3488          corresponding slot in OTHER.  This avoids a block copy.  */
3489
3490       tree list = NULL, stmt = bsi_stmt (*bsi);
3491
3492       mark_all_v_defs (stmt);
3493       generate_copy_inout (elt, is_output, other, &list);
3494       gcc_assert (list);
3495       mark_all_v_defs (list);
3496
3497       /* Preserve EH semantics.  */
3498       if (stmt_ends_bb_p (stmt))
3499         {
3500           tree_stmt_iterator tsi;
3501           tree first, blist = NULL;
3502           bool thr = tree_could_throw_p (stmt);
3503
3504           /* If the last statement of this BB created an EH edge
3505              before scalarization, we have to locate the first
3506              statement that can throw in the new statement list and
3507              use that as the last statement of this BB, such that EH
3508              semantics is preserved.  All statements up to this one
3509              are added to the same BB.  All other statements in the
3510              list will be added to normal outgoing edges of the same
3511              BB.  If they access any memory, it's the same memory, so
3512              we can assume they won't throw.  */
3513           tsi = tsi_start (list);
3514           for (first = tsi_stmt (tsi);
3515                thr && !tsi_end_p (tsi) && !tree_could_throw_p (first);
3516                first = tsi_stmt (tsi))
3517             {
3518               tsi_delink (&tsi);
3519               append_to_statement_list (first, &blist);
3520             }
3521
3522           /* Extract the first remaining statement from LIST, this is
3523              the EH statement if there is one.  */
3524           tsi_delink (&tsi);
3525
3526           if (blist)
3527             sra_insert_before (bsi, blist);
3528
3529           /* Replace the old statement with this new representative.  */
3530           bsi_replace (bsi, first, true);
3531
3532           if (!tsi_end_p (tsi))
3533             {
3534               /* If any reference would trap, then they all would.  And more
3535                  to the point, the first would.  Therefore none of the rest
3536                  will trap since the first didn't.  Indicate this by
3537                  iterating over the remaining statements and set
3538                  TREE_THIS_NOTRAP in all INDIRECT_REFs.  */
3539               do
3540                 {
3541                   walk_tree (tsi_stmt_ptr (tsi), mark_notrap, NULL, NULL);
3542                   tsi_next (&tsi);
3543                 }
3544               while (!tsi_end_p (tsi));
3545
3546               insert_edge_copies (list, bsi->bb);
3547             }
3548         }
3549       else
3550         sra_replace (bsi, list);
3551     }
3552 }
3553
3554 /* Generate initializations for all scalarizable parameters.  */
3555
3556 static void
3557 scalarize_parms (void)
3558 {
3559   tree list = NULL;
3560   unsigned i;
3561   bitmap_iterator bi;
3562
3563   EXECUTE_IF_SET_IN_BITMAP (needs_copy_in, 0, i, bi)
3564     {
3565       tree var = referenced_var (i);
3566       struct sra_elt *elt = lookup_element (NULL, var, NULL, NO_INSERT);
3567       generate_copy_inout (elt, true, var, &list);
3568     }
3569
3570   if (list)
3571     {
3572       insert_edge_copies (list, ENTRY_BLOCK_PTR);
3573       mark_all_v_defs (list);
3574     }
3575 }
3576
3577 /* Entry point to phase 4.  Update the function to match replacements.  */
3578
3579 static void
3580 scalarize_function (void)
3581 {
3582   static const struct sra_walk_fns fns = {
3583     scalarize_use, scalarize_copy, scalarize_init, scalarize_ldst, false
3584   };
3585
3586   sra_walk_function (&fns);
3587   scalarize_parms ();
3588   bsi_commit_edge_inserts ();
3589 }
3590
3591 \f
3592 /* Debug helper function.  Print ELT in a nice human-readable format.  */
3593
3594 static void
3595 dump_sra_elt_name (FILE *f, struct sra_elt *elt)
3596 {
3597   if (elt->parent && TREE_CODE (elt->parent->type) == COMPLEX_TYPE)
3598     {
3599       fputs (elt->element == integer_zero_node ? "__real__ " : "__imag__ ", f);
3600       dump_sra_elt_name (f, elt->parent);
3601     }
3602   else
3603     {
3604       if (elt->parent)
3605         dump_sra_elt_name (f, elt->parent);
3606       if (DECL_P (elt->element))
3607         {
3608           if (TREE_CODE (elt->element) == FIELD_DECL)
3609             fputc ('.', f);
3610           print_generic_expr (f, elt->element, dump_flags);
3611         }
3612       else if (TREE_CODE (elt->element) == BIT_FIELD_REF)
3613         fprintf (f, "$B" HOST_WIDE_INT_PRINT_DEC "F" HOST_WIDE_INT_PRINT_DEC,
3614                  tree_low_cst (TREE_OPERAND (elt->element, 2), 1),
3615                  tree_low_cst (TREE_OPERAND (elt->element, 1), 1));
3616       else if (TREE_CODE (elt->element) == RANGE_EXPR)
3617         fprintf (f, "["HOST_WIDE_INT_PRINT_DEC".."HOST_WIDE_INT_PRINT_DEC"]",
3618                  TREE_INT_CST_LOW (TREE_OPERAND (elt->element, 0)),
3619                  TREE_INT_CST_LOW (TREE_OPERAND (elt->element, 1)));
3620       else
3621         fprintf (f, "[" HOST_WIDE_INT_PRINT_DEC "]",
3622                  TREE_INT_CST_LOW (elt->element));
3623     }
3624 }
3625
3626 /* Likewise, but callable from the debugger.  */
3627
3628 void
3629 debug_sra_elt_name (struct sra_elt *elt)
3630 {
3631   dump_sra_elt_name (stderr, elt);
3632   fputc ('\n', stderr);
3633 }
3634
3635 void 
3636 sra_init_cache (void)
3637 {
3638   if (sra_type_decomp_cache) 
3639     return;
3640
3641   sra_type_decomp_cache = BITMAP_ALLOC (NULL);
3642   sra_type_inst_cache = BITMAP_ALLOC (NULL);
3643 }
3644
3645 /* Main entry point.  */
3646
3647 static unsigned int
3648 tree_sra (void)
3649 {
3650   /* Initialize local variables.  */
3651   todoflags = 0;
3652   gcc_obstack_init (&sra_obstack);
3653   sra_candidates = BITMAP_ALLOC (NULL);
3654   needs_copy_in = BITMAP_ALLOC (NULL);
3655   sra_init_cache ();
3656   sra_map = htab_create (101, sra_elt_hash, sra_elt_eq, NULL);
3657
3658   /* Scan.  If we find anything, instantiate and scalarize.  */
3659   if (find_candidates_for_sra ())
3660     {
3661       scan_function ();
3662       decide_instantiations ();
3663       scalarize_function ();
3664       if (!bitmap_empty_p (sra_candidates))
3665         todoflags |= TODO_rebuild_alias;
3666     }
3667
3668   /* Free allocated memory.  */
3669   htab_delete (sra_map);
3670   sra_map = NULL;
3671   BITMAP_FREE (sra_candidates);
3672   BITMAP_FREE (needs_copy_in);
3673   BITMAP_FREE (sra_type_decomp_cache);
3674   BITMAP_FREE (sra_type_inst_cache);
3675   obstack_free (&sra_obstack, NULL);
3676   return todoflags;
3677 }
3678
3679 static unsigned int
3680 tree_sra_early (void)
3681 {
3682   unsigned int ret;
3683
3684   early_sra = true;
3685   ret = tree_sra ();
3686   early_sra = false;
3687
3688   return ret & ~TODO_rebuild_alias;
3689 }
3690
3691 static bool
3692 gate_sra (void)
3693 {
3694   return flag_tree_sra != 0;
3695 }
3696
3697 struct gimple_opt_pass pass_sra_early =
3698 {
3699  {
3700   GIMPLE_PASS,
3701   "esra",                               /* name */
3702   gate_sra,                             /* gate */
3703   tree_sra_early,                       /* execute */
3704   NULL,                                 /* sub */
3705   NULL,                                 /* next */
3706   0,                                    /* static_pass_number */
3707   TV_TREE_SRA,                          /* tv_id */
3708   PROP_cfg | PROP_ssa,                  /* properties_required */
3709   0,                                    /* properties_provided */
3710   0,                                    /* properties_destroyed */
3711   0,                                    /* todo_flags_start */
3712   TODO_dump_func
3713   | TODO_update_ssa
3714   | TODO_ggc_collect
3715   | TODO_verify_ssa                     /* todo_flags_finish */
3716  }
3717 };
3718
3719 struct gimple_opt_pass pass_sra =
3720 {
3721  {
3722   GIMPLE_PASS,
3723   "sra",                                /* name */
3724   gate_sra,                             /* gate */
3725   tree_sra,                             /* execute */
3726   NULL,                                 /* sub */
3727   NULL,                                 /* next */
3728   0,                                    /* static_pass_number */
3729   TV_TREE_SRA,                          /* tv_id */
3730   PROP_cfg | PROP_ssa,                  /* properties_required */
3731   0,                                    /* properties_provided */
3732   0,                                    /* properties_destroyed */
3733   0,                                    /* todo_flags_start */
3734   TODO_dump_func
3735   | TODO_update_ssa
3736   | TODO_ggc_collect
3737   | TODO_verify_ssa                     /* todo_flags_finish */
3738  }
3739 };