PR lto/57602
[official-gcc.git] / gcc / tree-sra.c
blob7e950aeecdf2d2a36b966ae1f8c129cab34ab0d4
1 /* Scalar Replacement of Aggregates (SRA) converts some structure
2 references into scalar references, exposing them to the scalar
3 optimizers.
4 Copyright (C) 2008-2013 Free Software Foundation, Inc.
5 Contributed by Martin Jambor <mjambor@suse.cz>
7 This file is part of GCC.
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 for more details.
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3. If not see
21 <http://www.gnu.org/licenses/>. */
23 /* This file implements Scalar Reduction of Aggregates (SRA). SRA is run
24 twice, once in the early stages of compilation (early SRA) and once in the
25 late stages (late SRA). The aim of both is to turn references to scalar
26 parts of aggregates into uses of independent scalar variables.
28 The two passes are nearly identical, the only difference is that early SRA
29 does not scalarize unions which are used as the result in a GIMPLE_RETURN
30 statement because together with inlining this can lead to weird type
31 conversions.
33 Both passes operate in four stages:
35 1. The declarations that have properties which make them candidates for
36 scalarization are identified in function find_var_candidates(). The
37 candidates are stored in candidate_bitmap.
39 2. The function body is scanned. In the process, declarations which are
40 used in a manner that prevent their scalarization are removed from the
41 candidate bitmap. More importantly, for every access into an aggregate,
42 an access structure (struct access) is created by create_access() and
43 stored in a vector associated with the aggregate. Among other
44 information, the aggregate declaration, the offset and size of the access
45 and its type are stored in the structure.
47 On a related note, assign_link structures are created for every assign
48 statement between candidate aggregates and attached to the related
49 accesses.
51 3. The vectors of accesses are analyzed. They are first sorted according to
52 their offset and size and then scanned for partially overlapping accesses
53 (i.e. those which overlap but one is not entirely within another). Such
54 an access disqualifies the whole aggregate from being scalarized.
56 If there is no such inhibiting overlap, a representative access structure
57 is chosen for every unique combination of offset and size. Afterwards,
58 the pass builds a set of trees from these structures, in which children
59 of an access are within their parent (in terms of offset and size).
61 Then accesses are propagated whenever possible (i.e. in cases when it
62 does not create a partially overlapping access) across assign_links from
63 the right hand side to the left hand side.
65 Then the set of trees for each declaration is traversed again and those
66 accesses which should be replaced by a scalar are identified.
68 4. The function is traversed again, and for every reference into an
69 aggregate that has some component which is about to be scalarized,
70 statements are amended and new statements are created as necessary.
71 Finally, if a parameter got scalarized, the scalar replacements are
72 initialized with values from respective parameter aggregates. */
74 #include "config.h"
75 #include "system.h"
76 #include "coretypes.h"
77 #include "hash-table.h"
78 #include "alloc-pool.h"
79 #include "tm.h"
80 #include "tree.h"
81 #include "gimple.h"
82 #include "cgraph.h"
83 #include "tree-flow.h"
84 #include "tree-pass.h"
85 #include "ipa-prop.h"
86 #include "statistics.h"
87 #include "params.h"
88 #include "target.h"
89 #include "flags.h"
90 #include "dbgcnt.h"
91 #include "tree-inline.h"
92 #include "gimple-pretty-print.h"
93 #include "ipa-inline.h"
95 /* Enumeration of all aggregate reductions we can do. */
96 enum sra_mode { SRA_MODE_EARLY_IPA, /* early call regularization */
97 SRA_MODE_EARLY_INTRA, /* early intraprocedural SRA */
98 SRA_MODE_INTRA }; /* late intraprocedural SRA */
100 /* Global variable describing which aggregate reduction we are performing at
101 the moment. */
102 static enum sra_mode sra_mode;
104 struct assign_link;
106 /* ACCESS represents each access to an aggregate variable (as a whole or a
107 part). It can also represent a group of accesses that refer to exactly the
108 same fragment of an aggregate (i.e. those that have exactly the same offset
109 and size). Such representatives for a single aggregate, once determined,
110 are linked in a linked list and have the group fields set.
112 Moreover, when doing intraprocedural SRA, a tree is built from those
113 representatives (by the means of first_child and next_sibling pointers), in
114 which all items in a subtree are "within" the root, i.e. their offset is
115 greater or equal to offset of the root and offset+size is smaller or equal
116 to offset+size of the root. Children of an access are sorted by offset.
118 Note that accesses to parts of vector and complex number types always
119 represented by an access to the whole complex number or a vector. It is a
120 duty of the modifying functions to replace them appropriately. */
122 struct access
124 /* Values returned by `get_ref_base_and_extent' for each component reference
125 If EXPR isn't a component reference just set `BASE = EXPR', `OFFSET = 0',
126 `SIZE = TREE_SIZE (TREE_TYPE (expr))'. */
127 HOST_WIDE_INT offset;
128 HOST_WIDE_INT size;
129 tree base;
131 /* Expression. It is context dependent so do not use it to create new
132 expressions to access the original aggregate. See PR 42154 for a
133 testcase. */
134 tree expr;
135 /* Type. */
136 tree type;
138 /* The statement this access belongs to. */
139 gimple stmt;
141 /* Next group representative for this aggregate. */
142 struct access *next_grp;
144 /* Pointer to the group representative. Pointer to itself if the struct is
145 the representative. */
146 struct access *group_representative;
148 /* If this access has any children (in terms of the definition above), this
149 points to the first one. */
150 struct access *first_child;
152 /* In intraprocedural SRA, pointer to the next sibling in the access tree as
153 described above. In IPA-SRA this is a pointer to the next access
154 belonging to the same group (having the same representative). */
155 struct access *next_sibling;
157 /* Pointers to the first and last element in the linked list of assign
158 links. */
159 struct assign_link *first_link, *last_link;
161 /* Pointer to the next access in the work queue. */
162 struct access *next_queued;
164 /* Replacement variable for this access "region." Never to be accessed
165 directly, always only by the means of get_access_replacement() and only
166 when grp_to_be_replaced flag is set. */
167 tree replacement_decl;
169 /* Is this particular access write access? */
170 unsigned write : 1;
172 /* Is this access an access to a non-addressable field? */
173 unsigned non_addressable : 1;
175 /* Is this access currently in the work queue? */
176 unsigned grp_queued : 1;
178 /* Does this group contain a write access? This flag is propagated down the
179 access tree. */
180 unsigned grp_write : 1;
182 /* Does this group contain a read access? This flag is propagated down the
183 access tree. */
184 unsigned grp_read : 1;
186 /* Does this group contain a read access that comes from an assignment
187 statement? This flag is propagated down the access tree. */
188 unsigned grp_assignment_read : 1;
190 /* Does this group contain a write access that comes from an assignment
191 statement? This flag is propagated down the access tree. */
192 unsigned grp_assignment_write : 1;
194 /* Does this group contain a read access through a scalar type? This flag is
195 not propagated in the access tree in any direction. */
196 unsigned grp_scalar_read : 1;
198 /* Does this group contain a write access through a scalar type? This flag
199 is not propagated in the access tree in any direction. */
200 unsigned grp_scalar_write : 1;
202 /* Is this access an artificial one created to scalarize some record
203 entirely? */
204 unsigned grp_total_scalarization : 1;
206 /* Other passes of the analysis use this bit to make function
207 analyze_access_subtree create scalar replacements for this group if
208 possible. */
209 unsigned grp_hint : 1;
211 /* Is the subtree rooted in this access fully covered by scalar
212 replacements? */
213 unsigned grp_covered : 1;
215 /* If set to true, this access and all below it in an access tree must not be
216 scalarized. */
217 unsigned grp_unscalarizable_region : 1;
219 /* Whether data have been written to parts of the aggregate covered by this
220 access which is not to be scalarized. This flag is propagated up in the
221 access tree. */
222 unsigned grp_unscalarized_data : 1;
224 /* Does this access and/or group contain a write access through a
225 BIT_FIELD_REF? */
226 unsigned grp_partial_lhs : 1;
228 /* Set when a scalar replacement should be created for this variable. */
229 unsigned grp_to_be_replaced : 1;
231 /* Set when we want a replacement for the sole purpose of having it in
232 generated debug statements. */
233 unsigned grp_to_be_debug_replaced : 1;
235 /* Should TREE_NO_WARNING of a replacement be set? */
236 unsigned grp_no_warning : 1;
238 /* Is it possible that the group refers to data which might be (directly or
239 otherwise) modified? */
240 unsigned grp_maybe_modified : 1;
242 /* Set when this is a representative of a pointer to scalar (i.e. by
243 reference) parameter which we consider for turning into a plain scalar
244 (i.e. a by value parameter). */
245 unsigned grp_scalar_ptr : 1;
247 /* Set when we discover that this pointer is not safe to dereference in the
248 caller. */
249 unsigned grp_not_necessarilly_dereferenced : 1;
252 typedef struct access *access_p;
255 /* Alloc pool for allocating access structures. */
256 static alloc_pool access_pool;
258 /* A structure linking lhs and rhs accesses from an aggregate assignment. They
259 are used to propagate subaccesses from rhs to lhs as long as they don't
260 conflict with what is already there. */
261 struct assign_link
263 struct access *lacc, *racc;
264 struct assign_link *next;
267 /* Alloc pool for allocating assign link structures. */
268 static alloc_pool link_pool;
270 /* Base (tree) -> Vector (vec<access_p> *) map. */
271 static struct pointer_map_t *base_access_vec;
273 /* Candidate hash table helpers. */
275 struct uid_decl_hasher : typed_noop_remove <tree_node>
277 typedef tree_node value_type;
278 typedef tree_node compare_type;
279 static inline hashval_t hash (const value_type *);
280 static inline bool equal (const value_type *, const compare_type *);
283 /* Hash a tree in a uid_decl_map. */
285 inline hashval_t
286 uid_decl_hasher::hash (const value_type *item)
288 return item->decl_minimal.uid;
291 /* Return true if the DECL_UID in both trees are equal. */
293 inline bool
294 uid_decl_hasher::equal (const value_type *a, const compare_type *b)
296 return (a->decl_minimal.uid == b->decl_minimal.uid);
299 /* Set of candidates. */
300 static bitmap candidate_bitmap;
301 static hash_table <uid_decl_hasher> candidates;
303 /* For a candidate UID return the candidates decl. */
305 static inline tree
306 candidate (unsigned uid)
308 tree_node t;
309 t.decl_minimal.uid = uid;
310 return candidates.find_with_hash (&t, static_cast <hashval_t> (uid));
313 /* Bitmap of candidates which we should try to entirely scalarize away and
314 those which cannot be (because they are and need be used as a whole). */
315 static bitmap should_scalarize_away_bitmap, cannot_scalarize_away_bitmap;
317 /* Obstack for creation of fancy names. */
318 static struct obstack name_obstack;
320 /* Head of a linked list of accesses that need to have its subaccesses
321 propagated to their assignment counterparts. */
322 static struct access *work_queue_head;
324 /* Number of parameters of the analyzed function when doing early ipa SRA. */
325 static int func_param_count;
327 /* scan_function sets the following to true if it encounters a call to
328 __builtin_apply_args. */
329 static bool encountered_apply_args;
331 /* Set by scan_function when it finds a recursive call. */
332 static bool encountered_recursive_call;
334 /* Set by scan_function when it finds a recursive call with less actual
335 arguments than formal parameters.. */
336 static bool encountered_unchangable_recursive_call;
338 /* This is a table in which for each basic block and parameter there is a
339 distance (offset + size) in that parameter which is dereferenced and
340 accessed in that BB. */
341 static HOST_WIDE_INT *bb_dereferences;
342 /* Bitmap of BBs that can cause the function to "stop" progressing by
343 returning, throwing externally, looping infinitely or calling a function
344 which might abort etc.. */
345 static bitmap final_bbs;
347 /* Representative of no accesses at all. */
348 static struct access no_accesses_representant;
350 /* Predicate to test the special value. */
352 static inline bool
353 no_accesses_p (struct access *access)
355 return access == &no_accesses_representant;
358 /* Dump contents of ACCESS to file F in a human friendly way. If GRP is true,
359 representative fields are dumped, otherwise those which only describe the
360 individual access are. */
362 static struct
364 /* Number of processed aggregates is readily available in
365 analyze_all_variable_accesses and so is not stored here. */
367 /* Number of created scalar replacements. */
368 int replacements;
370 /* Number of times sra_modify_expr or sra_modify_assign themselves changed an
371 expression. */
372 int exprs;
374 /* Number of statements created by generate_subtree_copies. */
375 int subtree_copies;
377 /* Number of statements created by load_assign_lhs_subreplacements. */
378 int subreplacements;
380 /* Number of times sra_modify_assign has deleted a statement. */
381 int deleted;
383 /* Number of times sra_modify_assign has to deal with subaccesses of LHS and
384 RHS reparately due to type conversions or nonexistent matching
385 references. */
386 int separate_lhs_rhs_handling;
388 /* Number of parameters that were removed because they were unused. */
389 int deleted_unused_parameters;
391 /* Number of scalars passed as parameters by reference that have been
392 converted to be passed by value. */
393 int scalar_by_ref_to_by_val;
395 /* Number of aggregate parameters that were replaced by one or more of their
396 components. */
397 int aggregate_params_reduced;
399 /* Numbber of components created when splitting aggregate parameters. */
400 int param_reductions_created;
401 } sra_stats;
403 static void
404 dump_access (FILE *f, struct access *access, bool grp)
406 fprintf (f, "access { ");
407 fprintf (f, "base = (%d)'", DECL_UID (access->base));
408 print_generic_expr (f, access->base, 0);
409 fprintf (f, "', offset = " HOST_WIDE_INT_PRINT_DEC, access->offset);
410 fprintf (f, ", size = " HOST_WIDE_INT_PRINT_DEC, access->size);
411 fprintf (f, ", expr = ");
412 print_generic_expr (f, access->expr, 0);
413 fprintf (f, ", type = ");
414 print_generic_expr (f, access->type, 0);
415 if (grp)
416 fprintf (f, ", grp_read = %d, grp_write = %d, grp_assignment_read = %d, "
417 "grp_assignment_write = %d, grp_scalar_read = %d, "
418 "grp_scalar_write = %d, grp_total_scalarization = %d, "
419 "grp_hint = %d, grp_covered = %d, "
420 "grp_unscalarizable_region = %d, grp_unscalarized_data = %d, "
421 "grp_partial_lhs = %d, grp_to_be_replaced = %d, "
422 "grp_to_be_debug_replaced = %d, grp_maybe_modified = %d, "
423 "grp_not_necessarilly_dereferenced = %d\n",
424 access->grp_read, access->grp_write, access->grp_assignment_read,
425 access->grp_assignment_write, access->grp_scalar_read,
426 access->grp_scalar_write, access->grp_total_scalarization,
427 access->grp_hint, access->grp_covered,
428 access->grp_unscalarizable_region, access->grp_unscalarized_data,
429 access->grp_partial_lhs, access->grp_to_be_replaced,
430 access->grp_to_be_debug_replaced, access->grp_maybe_modified,
431 access->grp_not_necessarilly_dereferenced);
432 else
433 fprintf (f, ", write = %d, grp_total_scalarization = %d, "
434 "grp_partial_lhs = %d\n",
435 access->write, access->grp_total_scalarization,
436 access->grp_partial_lhs);
439 /* Dump a subtree rooted in ACCESS to file F, indent by LEVEL. */
441 static void
442 dump_access_tree_1 (FILE *f, struct access *access, int level)
446 int i;
448 for (i = 0; i < level; i++)
449 fputs ("* ", dump_file);
451 dump_access (f, access, true);
453 if (access->first_child)
454 dump_access_tree_1 (f, access->first_child, level + 1);
456 access = access->next_sibling;
458 while (access);
461 /* Dump all access trees for a variable, given the pointer to the first root in
462 ACCESS. */
464 static void
465 dump_access_tree (FILE *f, struct access *access)
467 for (; access; access = access->next_grp)
468 dump_access_tree_1 (f, access, 0);
471 /* Return true iff ACC is non-NULL and has subaccesses. */
473 static inline bool
474 access_has_children_p (struct access *acc)
476 return acc && acc->first_child;
479 /* Return true iff ACC is (partly) covered by at least one replacement. */
481 static bool
482 access_has_replacements_p (struct access *acc)
484 struct access *child;
485 if (acc->grp_to_be_replaced)
486 return true;
487 for (child = acc->first_child; child; child = child->next_sibling)
488 if (access_has_replacements_p (child))
489 return true;
490 return false;
493 /* Return a vector of pointers to accesses for the variable given in BASE or
494 NULL if there is none. */
496 static vec<access_p> *
497 get_base_access_vector (tree base)
499 void **slot;
501 slot = pointer_map_contains (base_access_vec, base);
502 if (!slot)
503 return NULL;
504 else
505 return *(vec<access_p> **) slot;
508 /* Find an access with required OFFSET and SIZE in a subtree of accesses rooted
509 in ACCESS. Return NULL if it cannot be found. */
511 static struct access *
512 find_access_in_subtree (struct access *access, HOST_WIDE_INT offset,
513 HOST_WIDE_INT size)
515 while (access && (access->offset != offset || access->size != size))
517 struct access *child = access->first_child;
519 while (child && (child->offset + child->size <= offset))
520 child = child->next_sibling;
521 access = child;
524 return access;
527 /* Return the first group representative for DECL or NULL if none exists. */
529 static struct access *
530 get_first_repr_for_decl (tree base)
532 vec<access_p> *access_vec;
534 access_vec = get_base_access_vector (base);
535 if (!access_vec)
536 return NULL;
538 return (*access_vec)[0];
541 /* Find an access representative for the variable BASE and given OFFSET and
542 SIZE. Requires that access trees have already been built. Return NULL if
543 it cannot be found. */
545 static struct access *
546 get_var_base_offset_size_access (tree base, HOST_WIDE_INT offset,
547 HOST_WIDE_INT size)
549 struct access *access;
551 access = get_first_repr_for_decl (base);
552 while (access && (access->offset + access->size <= offset))
553 access = access->next_grp;
554 if (!access)
555 return NULL;
557 return find_access_in_subtree (access, offset, size);
560 /* Add LINK to the linked list of assign links of RACC. */
561 static void
562 add_link_to_rhs (struct access *racc, struct assign_link *link)
564 gcc_assert (link->racc == racc);
566 if (!racc->first_link)
568 gcc_assert (!racc->last_link);
569 racc->first_link = link;
571 else
572 racc->last_link->next = link;
574 racc->last_link = link;
575 link->next = NULL;
578 /* Move all link structures in their linked list in OLD_RACC to the linked list
579 in NEW_RACC. */
580 static void
581 relink_to_new_repr (struct access *new_racc, struct access *old_racc)
583 if (!old_racc->first_link)
585 gcc_assert (!old_racc->last_link);
586 return;
589 if (new_racc->first_link)
591 gcc_assert (!new_racc->last_link->next);
592 gcc_assert (!old_racc->last_link || !old_racc->last_link->next);
594 new_racc->last_link->next = old_racc->first_link;
595 new_racc->last_link = old_racc->last_link;
597 else
599 gcc_assert (!new_racc->last_link);
601 new_racc->first_link = old_racc->first_link;
602 new_racc->last_link = old_racc->last_link;
604 old_racc->first_link = old_racc->last_link = NULL;
607 /* Add ACCESS to the work queue (which is actually a stack). */
609 static void
610 add_access_to_work_queue (struct access *access)
612 if (!access->grp_queued)
614 gcc_assert (!access->next_queued);
615 access->next_queued = work_queue_head;
616 access->grp_queued = 1;
617 work_queue_head = access;
621 /* Pop an access from the work queue, and return it, assuming there is one. */
623 static struct access *
624 pop_access_from_work_queue (void)
626 struct access *access = work_queue_head;
628 work_queue_head = access->next_queued;
629 access->next_queued = NULL;
630 access->grp_queued = 0;
631 return access;
635 /* Allocate necessary structures. */
637 static void
638 sra_initialize (void)
640 candidate_bitmap = BITMAP_ALLOC (NULL);
641 candidates.create (vec_safe_length (cfun->local_decls) / 2);
642 should_scalarize_away_bitmap = BITMAP_ALLOC (NULL);
643 cannot_scalarize_away_bitmap = BITMAP_ALLOC (NULL);
644 gcc_obstack_init (&name_obstack);
645 access_pool = create_alloc_pool ("SRA accesses", sizeof (struct access), 16);
646 link_pool = create_alloc_pool ("SRA links", sizeof (struct assign_link), 16);
647 base_access_vec = pointer_map_create ();
648 memset (&sra_stats, 0, sizeof (sra_stats));
649 encountered_apply_args = false;
650 encountered_recursive_call = false;
651 encountered_unchangable_recursive_call = false;
654 /* Hook fed to pointer_map_traverse, deallocate stored vectors. */
656 static bool
657 delete_base_accesses (const void *key ATTRIBUTE_UNUSED, void **value,
658 void *data ATTRIBUTE_UNUSED)
660 vec<access_p> *access_vec = (vec<access_p> *) *value;
661 vec_free (access_vec);
662 return true;
665 /* Deallocate all general structures. */
667 static void
668 sra_deinitialize (void)
670 BITMAP_FREE (candidate_bitmap);
671 candidates.dispose ();
672 BITMAP_FREE (should_scalarize_away_bitmap);
673 BITMAP_FREE (cannot_scalarize_away_bitmap);
674 free_alloc_pool (access_pool);
675 free_alloc_pool (link_pool);
676 obstack_free (&name_obstack, NULL);
678 pointer_map_traverse (base_access_vec, delete_base_accesses, NULL);
679 pointer_map_destroy (base_access_vec);
682 /* Remove DECL from candidates for SRA and write REASON to the dump file if
683 there is one. */
684 static void
685 disqualify_candidate (tree decl, const char *reason)
687 if (bitmap_clear_bit (candidate_bitmap, DECL_UID (decl)))
688 candidates.clear_slot (candidates.find_slot_with_hash (decl,
689 DECL_UID (decl),
690 NO_INSERT));
692 if (dump_file && (dump_flags & TDF_DETAILS))
694 fprintf (dump_file, "! Disqualifying ");
695 print_generic_expr (dump_file, decl, 0);
696 fprintf (dump_file, " - %s\n", reason);
700 /* Return true iff the type contains a field or an element which does not allow
701 scalarization. */
703 static bool
704 type_internals_preclude_sra_p (tree type, const char **msg)
706 tree fld;
707 tree et;
709 switch (TREE_CODE (type))
711 case RECORD_TYPE:
712 case UNION_TYPE:
713 case QUAL_UNION_TYPE:
714 for (fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
715 if (TREE_CODE (fld) == FIELD_DECL)
717 tree ft = TREE_TYPE (fld);
719 if (TREE_THIS_VOLATILE (fld))
721 *msg = "volatile structure field";
722 return true;
724 if (!DECL_FIELD_OFFSET (fld))
726 *msg = "no structure field offset";
727 return true;
729 if (!DECL_SIZE (fld))
731 *msg = "zero structure field size";
732 return true;
734 if (!host_integerp (DECL_FIELD_OFFSET (fld), 1))
736 *msg = "structure field offset not fixed";
737 return true;
739 if (!host_integerp (DECL_SIZE (fld), 1))
741 *msg = "structure field size not fixed";
742 return true;
744 if (!host_integerp (bit_position (fld), 0))
746 *msg = "structure field size too big";
747 return true;
749 if (AGGREGATE_TYPE_P (ft)
750 && int_bit_position (fld) % BITS_PER_UNIT != 0)
752 *msg = "structure field is bit field";
753 return true;
756 if (AGGREGATE_TYPE_P (ft) && type_internals_preclude_sra_p (ft, msg))
757 return true;
760 return false;
762 case ARRAY_TYPE:
763 et = TREE_TYPE (type);
765 if (TYPE_VOLATILE (et))
767 *msg = "element type is volatile";
768 return true;
771 if (AGGREGATE_TYPE_P (et) && type_internals_preclude_sra_p (et, msg))
772 return true;
774 return false;
776 default:
777 return false;
781 /* If T is an SSA_NAME, return NULL if it is not a default def or return its
782 base variable if it is. Return T if it is not an SSA_NAME. */
784 static tree
785 get_ssa_base_param (tree t)
787 if (TREE_CODE (t) == SSA_NAME)
789 if (SSA_NAME_IS_DEFAULT_DEF (t))
790 return SSA_NAME_VAR (t);
791 else
792 return NULL_TREE;
794 return t;
797 /* Mark a dereference of BASE of distance DIST in a basic block tht STMT
798 belongs to, unless the BB has already been marked as a potentially
799 final. */
801 static void
802 mark_parm_dereference (tree base, HOST_WIDE_INT dist, gimple stmt)
804 basic_block bb = gimple_bb (stmt);
805 int idx, parm_index = 0;
806 tree parm;
808 if (bitmap_bit_p (final_bbs, bb->index))
809 return;
811 for (parm = DECL_ARGUMENTS (current_function_decl);
812 parm && parm != base;
813 parm = DECL_CHAIN (parm))
814 parm_index++;
816 gcc_assert (parm_index < func_param_count);
818 idx = bb->index * func_param_count + parm_index;
819 if (bb_dereferences[idx] < dist)
820 bb_dereferences[idx] = dist;
823 /* Allocate an access structure for BASE, OFFSET and SIZE, clear it, fill in
824 the three fields. Also add it to the vector of accesses corresponding to
825 the base. Finally, return the new access. */
827 static struct access *
828 create_access_1 (tree base, HOST_WIDE_INT offset, HOST_WIDE_INT size)
830 vec<access_p> *v;
831 struct access *access;
832 void **slot;
834 access = (struct access *) pool_alloc (access_pool);
835 memset (access, 0, sizeof (struct access));
836 access->base = base;
837 access->offset = offset;
838 access->size = size;
840 slot = pointer_map_contains (base_access_vec, base);
841 if (slot)
842 v = (vec<access_p> *) *slot;
843 else
844 vec_alloc (v, 32);
846 v->safe_push (access);
848 *((vec<access_p> **)
849 pointer_map_insert (base_access_vec, base)) = v;
851 return access;
854 /* Create and insert access for EXPR. Return created access, or NULL if it is
855 not possible. */
857 static struct access *
858 create_access (tree expr, gimple stmt, bool write)
860 struct access *access;
861 HOST_WIDE_INT offset, size, max_size;
862 tree base = expr;
863 bool ptr, unscalarizable_region = false;
865 base = get_ref_base_and_extent (expr, &offset, &size, &max_size);
867 if (sra_mode == SRA_MODE_EARLY_IPA
868 && TREE_CODE (base) == MEM_REF)
870 base = get_ssa_base_param (TREE_OPERAND (base, 0));
871 if (!base)
872 return NULL;
873 ptr = true;
875 else
876 ptr = false;
878 if (!DECL_P (base) || !bitmap_bit_p (candidate_bitmap, DECL_UID (base)))
879 return NULL;
881 if (sra_mode == SRA_MODE_EARLY_IPA)
883 if (size < 0 || size != max_size)
885 disqualify_candidate (base, "Encountered a variable sized access.");
886 return NULL;
888 if (TREE_CODE (expr) == COMPONENT_REF
889 && DECL_BIT_FIELD (TREE_OPERAND (expr, 1)))
891 disqualify_candidate (base, "Encountered a bit-field access.");
892 return NULL;
894 gcc_checking_assert ((offset % BITS_PER_UNIT) == 0);
896 if (ptr)
897 mark_parm_dereference (base, offset + size, stmt);
899 else
901 if (size != max_size)
903 size = max_size;
904 unscalarizable_region = true;
906 if (size < 0)
908 disqualify_candidate (base, "Encountered an unconstrained access.");
909 return NULL;
913 access = create_access_1 (base, offset, size);
914 access->expr = expr;
915 access->type = TREE_TYPE (expr);
916 access->write = write;
917 access->grp_unscalarizable_region = unscalarizable_region;
918 access->stmt = stmt;
920 if (TREE_CODE (expr) == COMPONENT_REF
921 && DECL_NONADDRESSABLE_P (TREE_OPERAND (expr, 1)))
922 access->non_addressable = 1;
924 return access;
928 /* Return true iff TYPE is a RECORD_TYPE with fields that are either of gimple
929 register types or (recursively) records with only these two kinds of fields.
930 It also returns false if any of these records contains a bit-field. */
932 static bool
933 type_consists_of_records_p (tree type)
935 tree fld;
937 if (TREE_CODE (type) != RECORD_TYPE)
938 return false;
940 for (fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
941 if (TREE_CODE (fld) == FIELD_DECL)
943 tree ft = TREE_TYPE (fld);
945 if (DECL_BIT_FIELD (fld))
946 return false;
948 if (!is_gimple_reg_type (ft)
949 && !type_consists_of_records_p (ft))
950 return false;
953 return true;
956 /* Create total_scalarization accesses for all scalar type fields in DECL that
957 must be of a RECORD_TYPE conforming to type_consists_of_records_p. BASE
958 must be the top-most VAR_DECL representing the variable, OFFSET must be the
959 offset of DECL within BASE. REF must be the memory reference expression for
960 the given decl. */
962 static void
963 completely_scalarize_record (tree base, tree decl, HOST_WIDE_INT offset,
964 tree ref)
966 tree fld, decl_type = TREE_TYPE (decl);
968 for (fld = TYPE_FIELDS (decl_type); fld; fld = DECL_CHAIN (fld))
969 if (TREE_CODE (fld) == FIELD_DECL)
971 HOST_WIDE_INT pos = offset + int_bit_position (fld);
972 tree ft = TREE_TYPE (fld);
973 tree nref = build3 (COMPONENT_REF, TREE_TYPE (fld), ref, fld,
974 NULL_TREE);
976 if (is_gimple_reg_type (ft))
978 struct access *access;
979 HOST_WIDE_INT size;
981 size = tree_low_cst (DECL_SIZE (fld), 1);
982 access = create_access_1 (base, pos, size);
983 access->expr = nref;
984 access->type = ft;
985 access->grp_total_scalarization = 1;
986 /* Accesses for intraprocedural SRA can have their stmt NULL. */
988 else
989 completely_scalarize_record (base, fld, pos, nref);
993 /* Create total_scalarization accesses for all scalar type fields in VAR and
994 for VAR a a whole. VAR must be of a RECORD_TYPE conforming to
995 type_consists_of_records_p. */
997 static void
998 completely_scalarize_var (tree var)
1000 HOST_WIDE_INT size = tree_low_cst (DECL_SIZE (var), 1);
1001 struct access *access;
1003 access = create_access_1 (var, 0, size);
1004 access->expr = var;
1005 access->type = TREE_TYPE (var);
1006 access->grp_total_scalarization = 1;
1008 completely_scalarize_record (var, var, 0, var);
1011 /* Search the given tree for a declaration by skipping handled components and
1012 exclude it from the candidates. */
1014 static void
1015 disqualify_base_of_expr (tree t, const char *reason)
1017 t = get_base_address (t);
1018 if (sra_mode == SRA_MODE_EARLY_IPA
1019 && TREE_CODE (t) == MEM_REF)
1020 t = get_ssa_base_param (TREE_OPERAND (t, 0));
1022 if (t && DECL_P (t))
1023 disqualify_candidate (t, reason);
1026 /* Scan expression EXPR and create access structures for all accesses to
1027 candidates for scalarization. Return the created access or NULL if none is
1028 created. */
1030 static struct access *
1031 build_access_from_expr_1 (tree expr, gimple stmt, bool write)
1033 struct access *ret = NULL;
1034 bool partial_ref;
1036 if (TREE_CODE (expr) == BIT_FIELD_REF
1037 || TREE_CODE (expr) == IMAGPART_EXPR
1038 || TREE_CODE (expr) == REALPART_EXPR)
1040 expr = TREE_OPERAND (expr, 0);
1041 partial_ref = true;
1043 else
1044 partial_ref = false;
1046 /* We need to dive through V_C_Es in order to get the size of its parameter
1047 and not the result type. Ada produces such statements. We are also
1048 capable of handling the topmost V_C_E but not any of those buried in other
1049 handled components. */
1050 if (TREE_CODE (expr) == VIEW_CONVERT_EXPR)
1051 expr = TREE_OPERAND (expr, 0);
1053 if (contains_view_convert_expr_p (expr))
1055 disqualify_base_of_expr (expr, "V_C_E under a different handled "
1056 "component.");
1057 return NULL;
1060 switch (TREE_CODE (expr))
1062 case MEM_REF:
1063 if (TREE_CODE (TREE_OPERAND (expr, 0)) != ADDR_EXPR
1064 && sra_mode != SRA_MODE_EARLY_IPA)
1065 return NULL;
1066 /* fall through */
1067 case VAR_DECL:
1068 case PARM_DECL:
1069 case RESULT_DECL:
1070 case COMPONENT_REF:
1071 case ARRAY_REF:
1072 case ARRAY_RANGE_REF:
1073 ret = create_access (expr, stmt, write);
1074 break;
1076 default:
1077 break;
1080 if (write && partial_ref && ret)
1081 ret->grp_partial_lhs = 1;
1083 return ret;
1086 /* Scan expression EXPR and create access structures for all accesses to
1087 candidates for scalarization. Return true if any access has been inserted.
1088 STMT must be the statement from which the expression is taken, WRITE must be
1089 true if the expression is a store and false otherwise. */
1091 static bool
1092 build_access_from_expr (tree expr, gimple stmt, bool write)
1094 struct access *access;
1096 access = build_access_from_expr_1 (expr, stmt, write);
1097 if (access)
1099 /* This means the aggregate is accesses as a whole in a way other than an
1100 assign statement and thus cannot be removed even if we had a scalar
1101 replacement for everything. */
1102 if (cannot_scalarize_away_bitmap)
1103 bitmap_set_bit (cannot_scalarize_away_bitmap, DECL_UID (access->base));
1104 return true;
1106 return false;
1109 /* Disqualify LHS and RHS for scalarization if STMT must end its basic block in
1110 modes in which it matters, return true iff they have been disqualified. RHS
1111 may be NULL, in that case ignore it. If we scalarize an aggregate in
1112 intra-SRA we may need to add statements after each statement. This is not
1113 possible if a statement unconditionally has to end the basic block. */
1114 static bool
1115 disqualify_ops_if_throwing_stmt (gimple stmt, tree lhs, tree rhs)
1117 if ((sra_mode == SRA_MODE_EARLY_INTRA || sra_mode == SRA_MODE_INTRA)
1118 && (stmt_can_throw_internal (stmt) || stmt_ends_bb_p (stmt)))
1120 disqualify_base_of_expr (lhs, "LHS of a throwing stmt.");
1121 if (rhs)
1122 disqualify_base_of_expr (rhs, "RHS of a throwing stmt.");
1123 return true;
1125 return false;
1128 /* Scan expressions occurring in STMT, create access structures for all accesses
1129 to candidates for scalarization and remove those candidates which occur in
1130 statements or expressions that prevent them from being split apart. Return
1131 true if any access has been inserted. */
1133 static bool
1134 build_accesses_from_assign (gimple stmt)
1136 tree lhs, rhs;
1137 struct access *lacc, *racc;
1139 if (!gimple_assign_single_p (stmt)
1140 /* Scope clobbers don't influence scalarization. */
1141 || gimple_clobber_p (stmt))
1142 return false;
1144 lhs = gimple_assign_lhs (stmt);
1145 rhs = gimple_assign_rhs1 (stmt);
1147 if (disqualify_ops_if_throwing_stmt (stmt, lhs, rhs))
1148 return false;
1150 racc = build_access_from_expr_1 (rhs, stmt, false);
1151 lacc = build_access_from_expr_1 (lhs, stmt, true);
1153 if (lacc)
1154 lacc->grp_assignment_write = 1;
1156 if (racc)
1158 racc->grp_assignment_read = 1;
1159 if (should_scalarize_away_bitmap && !gimple_has_volatile_ops (stmt)
1160 && !is_gimple_reg_type (racc->type))
1161 bitmap_set_bit (should_scalarize_away_bitmap, DECL_UID (racc->base));
1164 if (lacc && racc
1165 && (sra_mode == SRA_MODE_EARLY_INTRA || sra_mode == SRA_MODE_INTRA)
1166 && !lacc->grp_unscalarizable_region
1167 && !racc->grp_unscalarizable_region
1168 && AGGREGATE_TYPE_P (TREE_TYPE (lhs))
1169 && lacc->size == racc->size
1170 && useless_type_conversion_p (lacc->type, racc->type))
1172 struct assign_link *link;
1174 link = (struct assign_link *) pool_alloc (link_pool);
1175 memset (link, 0, sizeof (struct assign_link));
1177 link->lacc = lacc;
1178 link->racc = racc;
1180 add_link_to_rhs (racc, link);
1183 return lacc || racc;
1186 /* Callback of walk_stmt_load_store_addr_ops visit_addr used to determine
1187 GIMPLE_ASM operands with memory constrains which cannot be scalarized. */
1189 static bool
1190 asm_visit_addr (gimple stmt ATTRIBUTE_UNUSED, tree op,
1191 void *data ATTRIBUTE_UNUSED)
1193 op = get_base_address (op);
1194 if (op
1195 && DECL_P (op))
1196 disqualify_candidate (op, "Non-scalarizable GIMPLE_ASM operand.");
1198 return false;
1201 /* Return true iff callsite CALL has at least as many actual arguments as there
1202 are formal parameters of the function currently processed by IPA-SRA. */
1204 static inline bool
1205 callsite_has_enough_arguments_p (gimple call)
1207 return gimple_call_num_args (call) >= (unsigned) func_param_count;
1210 /* Scan function and look for interesting expressions and create access
1211 structures for them. Return true iff any access is created. */
1213 static bool
1214 scan_function (void)
1216 basic_block bb;
1217 bool ret = false;
1219 FOR_EACH_BB (bb)
1221 gimple_stmt_iterator gsi;
1222 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1224 gimple stmt = gsi_stmt (gsi);
1225 tree t;
1226 unsigned i;
1228 if (final_bbs && stmt_can_throw_external (stmt))
1229 bitmap_set_bit (final_bbs, bb->index);
1230 switch (gimple_code (stmt))
1232 case GIMPLE_RETURN:
1233 t = gimple_return_retval (stmt);
1234 if (t != NULL_TREE)
1235 ret |= build_access_from_expr (t, stmt, false);
1236 if (final_bbs)
1237 bitmap_set_bit (final_bbs, bb->index);
1238 break;
1240 case GIMPLE_ASSIGN:
1241 ret |= build_accesses_from_assign (stmt);
1242 break;
1244 case GIMPLE_CALL:
1245 for (i = 0; i < gimple_call_num_args (stmt); i++)
1246 ret |= build_access_from_expr (gimple_call_arg (stmt, i),
1247 stmt, false);
1249 if (sra_mode == SRA_MODE_EARLY_IPA)
1251 tree dest = gimple_call_fndecl (stmt);
1252 int flags = gimple_call_flags (stmt);
1254 if (dest)
1256 if (DECL_BUILT_IN_CLASS (dest) == BUILT_IN_NORMAL
1257 && DECL_FUNCTION_CODE (dest) == BUILT_IN_APPLY_ARGS)
1258 encountered_apply_args = true;
1259 if (cgraph_get_node (dest)
1260 == cgraph_get_node (current_function_decl))
1262 encountered_recursive_call = true;
1263 if (!callsite_has_enough_arguments_p (stmt))
1264 encountered_unchangable_recursive_call = true;
1268 if (final_bbs
1269 && (flags & (ECF_CONST | ECF_PURE)) == 0)
1270 bitmap_set_bit (final_bbs, bb->index);
1273 t = gimple_call_lhs (stmt);
1274 if (t && !disqualify_ops_if_throwing_stmt (stmt, t, NULL))
1275 ret |= build_access_from_expr (t, stmt, true);
1276 break;
1278 case GIMPLE_ASM:
1279 walk_stmt_load_store_addr_ops (stmt, NULL, NULL, NULL,
1280 asm_visit_addr);
1281 if (final_bbs)
1282 bitmap_set_bit (final_bbs, bb->index);
1284 for (i = 0; i < gimple_asm_ninputs (stmt); i++)
1286 t = TREE_VALUE (gimple_asm_input_op (stmt, i));
1287 ret |= build_access_from_expr (t, stmt, false);
1289 for (i = 0; i < gimple_asm_noutputs (stmt); i++)
1291 t = TREE_VALUE (gimple_asm_output_op (stmt, i));
1292 ret |= build_access_from_expr (t, stmt, true);
1294 break;
1296 default:
1297 break;
1302 return ret;
1305 /* Helper of QSORT function. There are pointers to accesses in the array. An
1306 access is considered smaller than another if it has smaller offset or if the
1307 offsets are the same but is size is bigger. */
1309 static int
1310 compare_access_positions (const void *a, const void *b)
1312 const access_p *fp1 = (const access_p *) a;
1313 const access_p *fp2 = (const access_p *) b;
1314 const access_p f1 = *fp1;
1315 const access_p f2 = *fp2;
1317 if (f1->offset != f2->offset)
1318 return f1->offset < f2->offset ? -1 : 1;
1320 if (f1->size == f2->size)
1322 if (f1->type == f2->type)
1323 return 0;
1324 /* Put any non-aggregate type before any aggregate type. */
1325 else if (!is_gimple_reg_type (f1->type)
1326 && is_gimple_reg_type (f2->type))
1327 return 1;
1328 else if (is_gimple_reg_type (f1->type)
1329 && !is_gimple_reg_type (f2->type))
1330 return -1;
1331 /* Put any complex or vector type before any other scalar type. */
1332 else if (TREE_CODE (f1->type) != COMPLEX_TYPE
1333 && TREE_CODE (f1->type) != VECTOR_TYPE
1334 && (TREE_CODE (f2->type) == COMPLEX_TYPE
1335 || TREE_CODE (f2->type) == VECTOR_TYPE))
1336 return 1;
1337 else if ((TREE_CODE (f1->type) == COMPLEX_TYPE
1338 || TREE_CODE (f1->type) == VECTOR_TYPE)
1339 && TREE_CODE (f2->type) != COMPLEX_TYPE
1340 && TREE_CODE (f2->type) != VECTOR_TYPE)
1341 return -1;
1342 /* Put the integral type with the bigger precision first. */
1343 else if (INTEGRAL_TYPE_P (f1->type)
1344 && INTEGRAL_TYPE_P (f2->type))
1345 return TYPE_PRECISION (f2->type) - TYPE_PRECISION (f1->type);
1346 /* Put any integral type with non-full precision last. */
1347 else if (INTEGRAL_TYPE_P (f1->type)
1348 && (TREE_INT_CST_LOW (TYPE_SIZE (f1->type))
1349 != TYPE_PRECISION (f1->type)))
1350 return 1;
1351 else if (INTEGRAL_TYPE_P (f2->type)
1352 && (TREE_INT_CST_LOW (TYPE_SIZE (f2->type))
1353 != TYPE_PRECISION (f2->type)))
1354 return -1;
1355 /* Stabilize the sort. */
1356 return TYPE_UID (f1->type) - TYPE_UID (f2->type);
1359 /* We want the bigger accesses first, thus the opposite operator in the next
1360 line: */
1361 return f1->size > f2->size ? -1 : 1;
1365 /* Append a name of the declaration to the name obstack. A helper function for
1366 make_fancy_name. */
1368 static void
1369 make_fancy_decl_name (tree decl)
1371 char buffer[32];
1373 tree name = DECL_NAME (decl);
1374 if (name)
1375 obstack_grow (&name_obstack, IDENTIFIER_POINTER (name),
1376 IDENTIFIER_LENGTH (name));
1377 else
1379 sprintf (buffer, "D%u", DECL_UID (decl));
1380 obstack_grow (&name_obstack, buffer, strlen (buffer));
1384 /* Helper for make_fancy_name. */
1386 static void
1387 make_fancy_name_1 (tree expr)
1389 char buffer[32];
1390 tree index;
1392 if (DECL_P (expr))
1394 make_fancy_decl_name (expr);
1395 return;
1398 switch (TREE_CODE (expr))
1400 case COMPONENT_REF:
1401 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1402 obstack_1grow (&name_obstack, '$');
1403 make_fancy_decl_name (TREE_OPERAND (expr, 1));
1404 break;
1406 case ARRAY_REF:
1407 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1408 obstack_1grow (&name_obstack, '$');
1409 /* Arrays with only one element may not have a constant as their
1410 index. */
1411 index = TREE_OPERAND (expr, 1);
1412 if (TREE_CODE (index) != INTEGER_CST)
1413 break;
1414 sprintf (buffer, HOST_WIDE_INT_PRINT_DEC, TREE_INT_CST_LOW (index));
1415 obstack_grow (&name_obstack, buffer, strlen (buffer));
1416 break;
1418 case ADDR_EXPR:
1419 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1420 break;
1422 case MEM_REF:
1423 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1424 if (!integer_zerop (TREE_OPERAND (expr, 1)))
1426 obstack_1grow (&name_obstack, '$');
1427 sprintf (buffer, HOST_WIDE_INT_PRINT_DEC,
1428 TREE_INT_CST_LOW (TREE_OPERAND (expr, 1)));
1429 obstack_grow (&name_obstack, buffer, strlen (buffer));
1431 break;
1433 case BIT_FIELD_REF:
1434 case REALPART_EXPR:
1435 case IMAGPART_EXPR:
1436 gcc_unreachable (); /* we treat these as scalars. */
1437 break;
1438 default:
1439 break;
1443 /* Create a human readable name for replacement variable of ACCESS. */
1445 static char *
1446 make_fancy_name (tree expr)
1448 make_fancy_name_1 (expr);
1449 obstack_1grow (&name_obstack, '\0');
1450 return XOBFINISH (&name_obstack, char *);
1453 /* Construct a MEM_REF that would reference a part of aggregate BASE of type
1454 EXP_TYPE at the given OFFSET. If BASE is something for which
1455 get_addr_base_and_unit_offset returns NULL, gsi must be non-NULL and is used
1456 to insert new statements either before or below the current one as specified
1457 by INSERT_AFTER. This function is not capable of handling bitfields.
1459 BASE must be either a declaration or a memory reference that has correct
1460 alignment ifformation embeded in it (e.g. a pre-existing one in SRA). */
1462 tree
1463 build_ref_for_offset (location_t loc, tree base, HOST_WIDE_INT offset,
1464 tree exp_type, gimple_stmt_iterator *gsi,
1465 bool insert_after)
1467 tree prev_base = base;
1468 tree off;
1469 HOST_WIDE_INT base_offset;
1470 unsigned HOST_WIDE_INT misalign;
1471 unsigned int align;
1473 gcc_checking_assert (offset % BITS_PER_UNIT == 0);
1474 get_object_alignment_1 (base, &align, &misalign);
1475 base = get_addr_base_and_unit_offset (base, &base_offset);
1477 /* get_addr_base_and_unit_offset returns NULL for references with a variable
1478 offset such as array[var_index]. */
1479 if (!base)
1481 gimple stmt;
1482 tree tmp, addr;
1484 gcc_checking_assert (gsi);
1485 tmp = make_ssa_name (build_pointer_type (TREE_TYPE (prev_base)), NULL);
1486 addr = build_fold_addr_expr (unshare_expr (prev_base));
1487 STRIP_USELESS_TYPE_CONVERSION (addr);
1488 stmt = gimple_build_assign (tmp, addr);
1489 gimple_set_location (stmt, loc);
1490 if (insert_after)
1491 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
1492 else
1493 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
1495 off = build_int_cst (reference_alias_ptr_type (prev_base),
1496 offset / BITS_PER_UNIT);
1497 base = tmp;
1499 else if (TREE_CODE (base) == MEM_REF)
1501 off = build_int_cst (TREE_TYPE (TREE_OPERAND (base, 1)),
1502 base_offset + offset / BITS_PER_UNIT);
1503 off = int_const_binop (PLUS_EXPR, TREE_OPERAND (base, 1), off);
1504 base = unshare_expr (TREE_OPERAND (base, 0));
1506 else
1508 off = build_int_cst (reference_alias_ptr_type (base),
1509 base_offset + offset / BITS_PER_UNIT);
1510 base = build_fold_addr_expr (unshare_expr (base));
1513 misalign = (misalign + offset) & (align - 1);
1514 if (misalign != 0)
1515 align = (misalign & -misalign);
1516 if (align < TYPE_ALIGN (exp_type))
1517 exp_type = build_aligned_type (exp_type, align);
1519 return fold_build2_loc (loc, MEM_REF, exp_type, base, off);
1522 /* Construct a memory reference to a part of an aggregate BASE at the given
1523 OFFSET and of the same type as MODEL. In case this is a reference to a
1524 bit-field, the function will replicate the last component_ref of model's
1525 expr to access it. GSI and INSERT_AFTER have the same meaning as in
1526 build_ref_for_offset. */
1528 static tree
1529 build_ref_for_model (location_t loc, tree base, HOST_WIDE_INT offset,
1530 struct access *model, gimple_stmt_iterator *gsi,
1531 bool insert_after)
1533 if (TREE_CODE (model->expr) == COMPONENT_REF
1534 && DECL_BIT_FIELD (TREE_OPERAND (model->expr, 1)))
1536 /* This access represents a bit-field. */
1537 tree t, exp_type, fld = TREE_OPERAND (model->expr, 1);
1539 offset -= int_bit_position (fld);
1540 exp_type = TREE_TYPE (TREE_OPERAND (model->expr, 0));
1541 t = build_ref_for_offset (loc, base, offset, exp_type, gsi, insert_after);
1542 return fold_build3_loc (loc, COMPONENT_REF, TREE_TYPE (fld), t, fld,
1543 NULL_TREE);
1545 else
1546 return build_ref_for_offset (loc, base, offset, model->type,
1547 gsi, insert_after);
1550 /* Attempt to build a memory reference that we could but into a gimple
1551 debug_bind statement. Similar to build_ref_for_model but punts if it has to
1552 create statements and return s NULL instead. This function also ignores
1553 alignment issues and so its results should never end up in non-debug
1554 statements. */
1556 static tree
1557 build_debug_ref_for_model (location_t loc, tree base, HOST_WIDE_INT offset,
1558 struct access *model)
1560 HOST_WIDE_INT base_offset;
1561 tree off;
1563 if (TREE_CODE (model->expr) == COMPONENT_REF
1564 && DECL_BIT_FIELD (TREE_OPERAND (model->expr, 1)))
1565 return NULL_TREE;
1567 base = get_addr_base_and_unit_offset (base, &base_offset);
1568 if (!base)
1569 return NULL_TREE;
1570 if (TREE_CODE (base) == MEM_REF)
1572 off = build_int_cst (TREE_TYPE (TREE_OPERAND (base, 1)),
1573 base_offset + offset / BITS_PER_UNIT);
1574 off = int_const_binop (PLUS_EXPR, TREE_OPERAND (base, 1), off);
1575 base = unshare_expr (TREE_OPERAND (base, 0));
1577 else
1579 off = build_int_cst (reference_alias_ptr_type (base),
1580 base_offset + offset / BITS_PER_UNIT);
1581 base = build_fold_addr_expr (unshare_expr (base));
1584 return fold_build2_loc (loc, MEM_REF, model->type, base, off);
1587 /* Construct a memory reference consisting of component_refs and array_refs to
1588 a part of an aggregate *RES (which is of type TYPE). The requested part
1589 should have type EXP_TYPE at be the given OFFSET. This function might not
1590 succeed, it returns true when it does and only then *RES points to something
1591 meaningful. This function should be used only to build expressions that we
1592 might need to present to user (e.g. in warnings). In all other situations,
1593 build_ref_for_model or build_ref_for_offset should be used instead. */
1595 static bool
1596 build_user_friendly_ref_for_offset (tree *res, tree type, HOST_WIDE_INT offset,
1597 tree exp_type)
1599 while (1)
1601 tree fld;
1602 tree tr_size, index, minidx;
1603 HOST_WIDE_INT el_size;
1605 if (offset == 0 && exp_type
1606 && types_compatible_p (exp_type, type))
1607 return true;
1609 switch (TREE_CODE (type))
1611 case UNION_TYPE:
1612 case QUAL_UNION_TYPE:
1613 case RECORD_TYPE:
1614 for (fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
1616 HOST_WIDE_INT pos, size;
1617 tree tr_pos, expr, *expr_ptr;
1619 if (TREE_CODE (fld) != FIELD_DECL)
1620 continue;
1622 tr_pos = bit_position (fld);
1623 if (!tr_pos || !host_integerp (tr_pos, 1))
1624 continue;
1625 pos = TREE_INT_CST_LOW (tr_pos);
1626 gcc_assert (TREE_CODE (type) == RECORD_TYPE || pos == 0);
1627 tr_size = DECL_SIZE (fld);
1628 if (!tr_size || !host_integerp (tr_size, 1))
1629 continue;
1630 size = TREE_INT_CST_LOW (tr_size);
1631 if (size == 0)
1633 if (pos != offset)
1634 continue;
1636 else if (pos > offset || (pos + size) <= offset)
1637 continue;
1639 expr = build3 (COMPONENT_REF, TREE_TYPE (fld), *res, fld,
1640 NULL_TREE);
1641 expr_ptr = &expr;
1642 if (build_user_friendly_ref_for_offset (expr_ptr, TREE_TYPE (fld),
1643 offset - pos, exp_type))
1645 *res = expr;
1646 return true;
1649 return false;
1651 case ARRAY_TYPE:
1652 tr_size = TYPE_SIZE (TREE_TYPE (type));
1653 if (!tr_size || !host_integerp (tr_size, 1))
1654 return false;
1655 el_size = tree_low_cst (tr_size, 1);
1657 minidx = TYPE_MIN_VALUE (TYPE_DOMAIN (type));
1658 if (TREE_CODE (minidx) != INTEGER_CST || el_size == 0)
1659 return false;
1660 index = build_int_cst (TYPE_DOMAIN (type), offset / el_size);
1661 if (!integer_zerop (minidx))
1662 index = int_const_binop (PLUS_EXPR, index, minidx);
1663 *res = build4 (ARRAY_REF, TREE_TYPE (type), *res, index,
1664 NULL_TREE, NULL_TREE);
1665 offset = offset % el_size;
1666 type = TREE_TYPE (type);
1667 break;
1669 default:
1670 if (offset != 0)
1671 return false;
1673 if (exp_type)
1674 return false;
1675 else
1676 return true;
1681 /* Return true iff TYPE is stdarg va_list type. */
1683 static inline bool
1684 is_va_list_type (tree type)
1686 return TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (va_list_type_node);
1689 /* Print message to dump file why a variable was rejected. */
1691 static void
1692 reject (tree var, const char *msg)
1694 if (dump_file && (dump_flags & TDF_DETAILS))
1696 fprintf (dump_file, "Rejected (%d): %s: ", DECL_UID (var), msg);
1697 print_generic_expr (dump_file, var, 0);
1698 fprintf (dump_file, "\n");
1702 /* Return true if VAR is a candidate for SRA. */
1704 static bool
1705 maybe_add_sra_candidate (tree var)
1707 tree type = TREE_TYPE (var);
1708 const char *msg;
1709 tree_node **slot;
1711 if (!AGGREGATE_TYPE_P (type))
1713 reject (var, "not aggregate");
1714 return false;
1716 if (needs_to_live_in_memory (var))
1718 reject (var, "needs to live in memory");
1719 return false;
1721 if (TREE_THIS_VOLATILE (var))
1723 reject (var, "is volatile");
1724 return false;
1726 if (!COMPLETE_TYPE_P (type))
1728 reject (var, "has incomplete type");
1729 return false;
1731 if (!host_integerp (TYPE_SIZE (type), 1))
1733 reject (var, "type size not fixed");
1734 return false;
1736 if (tree_low_cst (TYPE_SIZE (type), 1) == 0)
1738 reject (var, "type size is zero");
1739 return false;
1741 if (type_internals_preclude_sra_p (type, &msg))
1743 reject (var, msg);
1744 return false;
1746 if (/* Fix for PR 41089. tree-stdarg.c needs to have va_lists intact but
1747 we also want to schedule it rather late. Thus we ignore it in
1748 the early pass. */
1749 (sra_mode == SRA_MODE_EARLY_INTRA
1750 && is_va_list_type (type)))
1752 reject (var, "is va_list");
1753 return false;
1756 bitmap_set_bit (candidate_bitmap, DECL_UID (var));
1757 slot = candidates.find_slot_with_hash (var, DECL_UID (var), INSERT);
1758 *slot = var;
1760 if (dump_file && (dump_flags & TDF_DETAILS))
1762 fprintf (dump_file, "Candidate (%d): ", DECL_UID (var));
1763 print_generic_expr (dump_file, var, 0);
1764 fprintf (dump_file, "\n");
1767 return true;
1770 /* The very first phase of intraprocedural SRA. It marks in candidate_bitmap
1771 those with type which is suitable for scalarization. */
1773 static bool
1774 find_var_candidates (void)
1776 tree var, parm;
1777 unsigned int i;
1778 bool ret = false;
1780 for (parm = DECL_ARGUMENTS (current_function_decl);
1781 parm;
1782 parm = DECL_CHAIN (parm))
1783 ret |= maybe_add_sra_candidate (parm);
1785 FOR_EACH_LOCAL_DECL (cfun, i, var)
1787 if (TREE_CODE (var) != VAR_DECL)
1788 continue;
1790 ret |= maybe_add_sra_candidate (var);
1793 return ret;
1796 /* Sort all accesses for the given variable, check for partial overlaps and
1797 return NULL if there are any. If there are none, pick a representative for
1798 each combination of offset and size and create a linked list out of them.
1799 Return the pointer to the first representative and make sure it is the first
1800 one in the vector of accesses. */
1802 static struct access *
1803 sort_and_splice_var_accesses (tree var)
1805 int i, j, access_count;
1806 struct access *res, **prev_acc_ptr = &res;
1807 vec<access_p> *access_vec;
1808 bool first = true;
1809 HOST_WIDE_INT low = -1, high = 0;
1811 access_vec = get_base_access_vector (var);
1812 if (!access_vec)
1813 return NULL;
1814 access_count = access_vec->length ();
1816 /* Sort by <OFFSET, SIZE>. */
1817 access_vec->qsort (compare_access_positions);
1819 i = 0;
1820 while (i < access_count)
1822 struct access *access = (*access_vec)[i];
1823 bool grp_write = access->write;
1824 bool grp_read = !access->write;
1825 bool grp_scalar_write = access->write
1826 && is_gimple_reg_type (access->type);
1827 bool grp_scalar_read = !access->write
1828 && is_gimple_reg_type (access->type);
1829 bool grp_assignment_read = access->grp_assignment_read;
1830 bool grp_assignment_write = access->grp_assignment_write;
1831 bool multiple_scalar_reads = false;
1832 bool total_scalarization = access->grp_total_scalarization;
1833 bool grp_partial_lhs = access->grp_partial_lhs;
1834 bool first_scalar = is_gimple_reg_type (access->type);
1835 bool unscalarizable_region = access->grp_unscalarizable_region;
1837 if (first || access->offset >= high)
1839 first = false;
1840 low = access->offset;
1841 high = access->offset + access->size;
1843 else if (access->offset > low && access->offset + access->size > high)
1844 return NULL;
1845 else
1846 gcc_assert (access->offset >= low
1847 && access->offset + access->size <= high);
1849 j = i + 1;
1850 while (j < access_count)
1852 struct access *ac2 = (*access_vec)[j];
1853 if (ac2->offset != access->offset || ac2->size != access->size)
1854 break;
1855 if (ac2->write)
1857 grp_write = true;
1858 grp_scalar_write = (grp_scalar_write
1859 || is_gimple_reg_type (ac2->type));
1861 else
1863 grp_read = true;
1864 if (is_gimple_reg_type (ac2->type))
1866 if (grp_scalar_read)
1867 multiple_scalar_reads = true;
1868 else
1869 grp_scalar_read = true;
1872 grp_assignment_read |= ac2->grp_assignment_read;
1873 grp_assignment_write |= ac2->grp_assignment_write;
1874 grp_partial_lhs |= ac2->grp_partial_lhs;
1875 unscalarizable_region |= ac2->grp_unscalarizable_region;
1876 total_scalarization |= ac2->grp_total_scalarization;
1877 relink_to_new_repr (access, ac2);
1879 /* If there are both aggregate-type and scalar-type accesses with
1880 this combination of size and offset, the comparison function
1881 should have put the scalars first. */
1882 gcc_assert (first_scalar || !is_gimple_reg_type (ac2->type));
1883 ac2->group_representative = access;
1884 j++;
1887 i = j;
1889 access->group_representative = access;
1890 access->grp_write = grp_write;
1891 access->grp_read = grp_read;
1892 access->grp_scalar_read = grp_scalar_read;
1893 access->grp_scalar_write = grp_scalar_write;
1894 access->grp_assignment_read = grp_assignment_read;
1895 access->grp_assignment_write = grp_assignment_write;
1896 access->grp_hint = multiple_scalar_reads || total_scalarization;
1897 access->grp_total_scalarization = total_scalarization;
1898 access->grp_partial_lhs = grp_partial_lhs;
1899 access->grp_unscalarizable_region = unscalarizable_region;
1900 if (access->first_link)
1901 add_access_to_work_queue (access);
1903 *prev_acc_ptr = access;
1904 prev_acc_ptr = &access->next_grp;
1907 gcc_assert (res == (*access_vec)[0]);
1908 return res;
1911 /* Create a variable for the given ACCESS which determines the type, name and a
1912 few other properties. Return the variable declaration and store it also to
1913 ACCESS->replacement. */
1915 static tree
1916 create_access_replacement (struct access *access)
1918 tree repl;
1920 if (access->grp_to_be_debug_replaced)
1922 repl = create_tmp_var_raw (access->type, NULL);
1923 DECL_CONTEXT (repl) = current_function_decl;
1925 else
1926 repl = create_tmp_var (access->type, "SR");
1927 if (TREE_CODE (access->type) == COMPLEX_TYPE
1928 || TREE_CODE (access->type) == VECTOR_TYPE)
1930 if (!access->grp_partial_lhs)
1931 DECL_GIMPLE_REG_P (repl) = 1;
1933 else if (access->grp_partial_lhs
1934 && is_gimple_reg_type (access->type))
1935 TREE_ADDRESSABLE (repl) = 1;
1937 DECL_SOURCE_LOCATION (repl) = DECL_SOURCE_LOCATION (access->base);
1938 DECL_ARTIFICIAL (repl) = 1;
1939 DECL_IGNORED_P (repl) = DECL_IGNORED_P (access->base);
1941 if (DECL_NAME (access->base)
1942 && !DECL_IGNORED_P (access->base)
1943 && !DECL_ARTIFICIAL (access->base))
1945 char *pretty_name = make_fancy_name (access->expr);
1946 tree debug_expr = unshare_expr_without_location (access->expr), d;
1947 bool fail = false;
1949 DECL_NAME (repl) = get_identifier (pretty_name);
1950 obstack_free (&name_obstack, pretty_name);
1952 /* Get rid of any SSA_NAMEs embedded in debug_expr,
1953 as DECL_DEBUG_EXPR isn't considered when looking for still
1954 used SSA_NAMEs and thus they could be freed. All debug info
1955 generation cares is whether something is constant or variable
1956 and that get_ref_base_and_extent works properly on the
1957 expression. It cannot handle accesses at a non-constant offset
1958 though, so just give up in those cases. */
1959 for (d = debug_expr;
1960 !fail && (handled_component_p (d) || TREE_CODE (d) == MEM_REF);
1961 d = TREE_OPERAND (d, 0))
1962 switch (TREE_CODE (d))
1964 case ARRAY_REF:
1965 case ARRAY_RANGE_REF:
1966 if (TREE_OPERAND (d, 1)
1967 && TREE_CODE (TREE_OPERAND (d, 1)) != INTEGER_CST)
1968 fail = true;
1969 if (TREE_OPERAND (d, 3)
1970 && TREE_CODE (TREE_OPERAND (d, 3)) != INTEGER_CST)
1971 fail = true;
1972 /* FALLTHRU */
1973 case COMPONENT_REF:
1974 if (TREE_OPERAND (d, 2)
1975 && TREE_CODE (TREE_OPERAND (d, 2)) != INTEGER_CST)
1976 fail = true;
1977 break;
1978 case MEM_REF:
1979 if (TREE_CODE (TREE_OPERAND (d, 0)) != ADDR_EXPR)
1980 fail = true;
1981 else
1982 d = TREE_OPERAND (d, 0);
1983 break;
1984 default:
1985 break;
1987 if (!fail)
1989 SET_DECL_DEBUG_EXPR (repl, debug_expr);
1990 DECL_HAS_DEBUG_EXPR_P (repl) = 1;
1992 if (access->grp_no_warning)
1993 TREE_NO_WARNING (repl) = 1;
1994 else
1995 TREE_NO_WARNING (repl) = TREE_NO_WARNING (access->base);
1997 else
1998 TREE_NO_WARNING (repl) = 1;
2000 if (dump_file)
2002 if (access->grp_to_be_debug_replaced)
2004 fprintf (dump_file, "Created a debug-only replacement for ");
2005 print_generic_expr (dump_file, access->base, 0);
2006 fprintf (dump_file, " offset: %u, size: %u\n",
2007 (unsigned) access->offset, (unsigned) access->size);
2009 else
2011 fprintf (dump_file, "Created a replacement for ");
2012 print_generic_expr (dump_file, access->base, 0);
2013 fprintf (dump_file, " offset: %u, size: %u: ",
2014 (unsigned) access->offset, (unsigned) access->size);
2015 print_generic_expr (dump_file, repl, 0);
2016 fprintf (dump_file, "\n");
2019 sra_stats.replacements++;
2021 return repl;
2024 /* Return ACCESS scalar replacement, create it if it does not exist yet. */
2026 static inline tree
2027 get_access_replacement (struct access *access)
2029 gcc_checking_assert (access->replacement_decl);
2030 return access->replacement_decl;
2034 /* Build a subtree of accesses rooted in *ACCESS, and move the pointer in the
2035 linked list along the way. Stop when *ACCESS is NULL or the access pointed
2036 to it is not "within" the root. Return false iff some accesses partially
2037 overlap. */
2039 static bool
2040 build_access_subtree (struct access **access)
2042 struct access *root = *access, *last_child = NULL;
2043 HOST_WIDE_INT limit = root->offset + root->size;
2045 *access = (*access)->next_grp;
2046 while (*access && (*access)->offset + (*access)->size <= limit)
2048 if (!last_child)
2049 root->first_child = *access;
2050 else
2051 last_child->next_sibling = *access;
2052 last_child = *access;
2054 if (!build_access_subtree (access))
2055 return false;
2058 if (*access && (*access)->offset < limit)
2059 return false;
2061 return true;
2064 /* Build a tree of access representatives, ACCESS is the pointer to the first
2065 one, others are linked in a list by the next_grp field. Return false iff
2066 some accesses partially overlap. */
2068 static bool
2069 build_access_trees (struct access *access)
2071 while (access)
2073 struct access *root = access;
2075 if (!build_access_subtree (&access))
2076 return false;
2077 root->next_grp = access;
2079 return true;
2082 /* Return true if expr contains some ARRAY_REFs into a variable bounded
2083 array. */
2085 static bool
2086 expr_with_var_bounded_array_refs_p (tree expr)
2088 while (handled_component_p (expr))
2090 if (TREE_CODE (expr) == ARRAY_REF
2091 && !host_integerp (array_ref_low_bound (expr), 0))
2092 return true;
2093 expr = TREE_OPERAND (expr, 0);
2095 return false;
2098 /* Analyze the subtree of accesses rooted in ROOT, scheduling replacements when
2099 both seeming beneficial and when ALLOW_REPLACEMENTS allows it. Also set all
2100 sorts of access flags appropriately along the way, notably always set
2101 grp_read and grp_assign_read according to MARK_READ and grp_write when
2102 MARK_WRITE is true.
2104 Creating a replacement for a scalar access is considered beneficial if its
2105 grp_hint is set (this means we are either attempting total scalarization or
2106 there is more than one direct read access) or according to the following
2107 table:
2109 Access written to through a scalar type (once or more times)
2111 | Written to in an assignment statement
2113 | | Access read as scalar _once_
2114 | | |
2115 | | | Read in an assignment statement
2116 | | | |
2117 | | | | Scalarize Comment
2118 -----------------------------------------------------------------------------
2119 0 0 0 0 No access for the scalar
2120 0 0 0 1 No access for the scalar
2121 0 0 1 0 No Single read - won't help
2122 0 0 1 1 No The same case
2123 0 1 0 0 No access for the scalar
2124 0 1 0 1 No access for the scalar
2125 0 1 1 0 Yes s = *g; return s.i;
2126 0 1 1 1 Yes The same case as above
2127 1 0 0 0 No Won't help
2128 1 0 0 1 Yes s.i = 1; *g = s;
2129 1 0 1 0 Yes s.i = 5; g = s.i;
2130 1 0 1 1 Yes The same case as above
2131 1 1 0 0 No Won't help.
2132 1 1 0 1 Yes s.i = 1; *g = s;
2133 1 1 1 0 Yes s = *g; return s.i;
2134 1 1 1 1 Yes Any of the above yeses */
2136 static bool
2137 analyze_access_subtree (struct access *root, struct access *parent,
2138 bool allow_replacements)
2140 struct access *child;
2141 HOST_WIDE_INT limit = root->offset + root->size;
2142 HOST_WIDE_INT covered_to = root->offset;
2143 bool scalar = is_gimple_reg_type (root->type);
2144 bool hole = false, sth_created = false;
2146 if (parent)
2148 if (parent->grp_read)
2149 root->grp_read = 1;
2150 if (parent->grp_assignment_read)
2151 root->grp_assignment_read = 1;
2152 if (parent->grp_write)
2153 root->grp_write = 1;
2154 if (parent->grp_assignment_write)
2155 root->grp_assignment_write = 1;
2156 if (parent->grp_total_scalarization)
2157 root->grp_total_scalarization = 1;
2160 if (root->grp_unscalarizable_region)
2161 allow_replacements = false;
2163 if (allow_replacements && expr_with_var_bounded_array_refs_p (root->expr))
2164 allow_replacements = false;
2166 for (child = root->first_child; child; child = child->next_sibling)
2168 hole |= covered_to < child->offset;
2169 sth_created |= analyze_access_subtree (child, root,
2170 allow_replacements && !scalar);
2172 root->grp_unscalarized_data |= child->grp_unscalarized_data;
2173 root->grp_total_scalarization &= child->grp_total_scalarization;
2174 if (child->grp_covered)
2175 covered_to += child->size;
2176 else
2177 hole = true;
2180 if (allow_replacements && scalar && !root->first_child
2181 && (root->grp_hint
2182 || ((root->grp_scalar_read || root->grp_assignment_read)
2183 && (root->grp_scalar_write || root->grp_assignment_write))))
2185 /* Always create access replacements that cover the whole access.
2186 For integral types this means the precision has to match.
2187 Avoid assumptions based on the integral type kind, too. */
2188 if (INTEGRAL_TYPE_P (root->type)
2189 && (TREE_CODE (root->type) != INTEGER_TYPE
2190 || TYPE_PRECISION (root->type) != root->size)
2191 /* But leave bitfield accesses alone. */
2192 && (TREE_CODE (root->expr) != COMPONENT_REF
2193 || !DECL_BIT_FIELD (TREE_OPERAND (root->expr, 1))))
2195 tree rt = root->type;
2196 gcc_assert ((root->offset % BITS_PER_UNIT) == 0
2197 && (root->size % BITS_PER_UNIT) == 0);
2198 root->type = build_nonstandard_integer_type (root->size,
2199 TYPE_UNSIGNED (rt));
2200 root->expr = build_ref_for_offset (UNKNOWN_LOCATION,
2201 root->base, root->offset,
2202 root->type, NULL, false);
2204 if (dump_file && (dump_flags & TDF_DETAILS))
2206 fprintf (dump_file, "Changing the type of a replacement for ");
2207 print_generic_expr (dump_file, root->base, 0);
2208 fprintf (dump_file, " offset: %u, size: %u ",
2209 (unsigned) root->offset, (unsigned) root->size);
2210 fprintf (dump_file, " to an integer.\n");
2214 root->grp_to_be_replaced = 1;
2215 root->replacement_decl = create_access_replacement (root);
2216 sth_created = true;
2217 hole = false;
2219 else
2221 if (allow_replacements
2222 && scalar && !root->first_child
2223 && (root->grp_scalar_write || root->grp_assignment_write)
2224 && !bitmap_bit_p (cannot_scalarize_away_bitmap,
2225 DECL_UID (root->base)))
2227 gcc_checking_assert (!root->grp_scalar_read
2228 && !root->grp_assignment_read);
2229 sth_created = true;
2230 if (MAY_HAVE_DEBUG_STMTS)
2232 root->grp_to_be_debug_replaced = 1;
2233 root->replacement_decl = create_access_replacement (root);
2237 if (covered_to < limit)
2238 hole = true;
2239 if (scalar)
2240 root->grp_total_scalarization = 0;
2243 if (!hole || root->grp_total_scalarization)
2244 root->grp_covered = 1;
2245 else if (root->grp_write || TREE_CODE (root->base) == PARM_DECL)
2246 root->grp_unscalarized_data = 1; /* not covered and written to */
2247 return sth_created;
2250 /* Analyze all access trees linked by next_grp by the means of
2251 analyze_access_subtree. */
2252 static bool
2253 analyze_access_trees (struct access *access)
2255 bool ret = false;
2257 while (access)
2259 if (analyze_access_subtree (access, NULL, true))
2260 ret = true;
2261 access = access->next_grp;
2264 return ret;
2267 /* Return true iff a potential new child of LACC at offset OFFSET and with size
2268 SIZE would conflict with an already existing one. If exactly such a child
2269 already exists in LACC, store a pointer to it in EXACT_MATCH. */
2271 static bool
2272 child_would_conflict_in_lacc (struct access *lacc, HOST_WIDE_INT norm_offset,
2273 HOST_WIDE_INT size, struct access **exact_match)
2275 struct access *child;
2277 for (child = lacc->first_child; child; child = child->next_sibling)
2279 if (child->offset == norm_offset && child->size == size)
2281 *exact_match = child;
2282 return true;
2285 if (child->offset < norm_offset + size
2286 && child->offset + child->size > norm_offset)
2287 return true;
2290 return false;
2293 /* Create a new child access of PARENT, with all properties just like MODEL
2294 except for its offset and with its grp_write false and grp_read true.
2295 Return the new access or NULL if it cannot be created. Note that this access
2296 is created long after all splicing and sorting, it's not located in any
2297 access vector and is automatically a representative of its group. */
2299 static struct access *
2300 create_artificial_child_access (struct access *parent, struct access *model,
2301 HOST_WIDE_INT new_offset)
2303 struct access *access;
2304 struct access **child;
2305 tree expr = parent->base;
2307 gcc_assert (!model->grp_unscalarizable_region);
2309 access = (struct access *) pool_alloc (access_pool);
2310 memset (access, 0, sizeof (struct access));
2311 if (!build_user_friendly_ref_for_offset (&expr, TREE_TYPE (expr), new_offset,
2312 model->type))
2314 access->grp_no_warning = true;
2315 expr = build_ref_for_model (EXPR_LOCATION (parent->base), parent->base,
2316 new_offset, model, NULL, false);
2319 access->base = parent->base;
2320 access->expr = expr;
2321 access->offset = new_offset;
2322 access->size = model->size;
2323 access->type = model->type;
2324 access->grp_write = true;
2325 access->grp_read = false;
2327 child = &parent->first_child;
2328 while (*child && (*child)->offset < new_offset)
2329 child = &(*child)->next_sibling;
2331 access->next_sibling = *child;
2332 *child = access;
2334 return access;
2338 /* Propagate all subaccesses of RACC across an assignment link to LACC. Return
2339 true if any new subaccess was created. Additionally, if RACC is a scalar
2340 access but LACC is not, change the type of the latter, if possible. */
2342 static bool
2343 propagate_subaccesses_across_link (struct access *lacc, struct access *racc)
2345 struct access *rchild;
2346 HOST_WIDE_INT norm_delta = lacc->offset - racc->offset;
2347 bool ret = false;
2349 if (is_gimple_reg_type (lacc->type)
2350 || lacc->grp_unscalarizable_region
2351 || racc->grp_unscalarizable_region)
2352 return false;
2354 if (is_gimple_reg_type (racc->type))
2356 if (!lacc->first_child && !racc->first_child)
2358 tree t = lacc->base;
2360 lacc->type = racc->type;
2361 if (build_user_friendly_ref_for_offset (&t, TREE_TYPE (t),
2362 lacc->offset, racc->type))
2363 lacc->expr = t;
2364 else
2366 lacc->expr = build_ref_for_model (EXPR_LOCATION (lacc->base),
2367 lacc->base, lacc->offset,
2368 racc, NULL, false);
2369 lacc->grp_no_warning = true;
2372 return false;
2375 for (rchild = racc->first_child; rchild; rchild = rchild->next_sibling)
2377 struct access *new_acc = NULL;
2378 HOST_WIDE_INT norm_offset = rchild->offset + norm_delta;
2380 if (rchild->grp_unscalarizable_region)
2381 continue;
2383 if (child_would_conflict_in_lacc (lacc, norm_offset, rchild->size,
2384 &new_acc))
2386 if (new_acc)
2388 rchild->grp_hint = 1;
2389 new_acc->grp_hint |= new_acc->grp_read;
2390 if (rchild->first_child)
2391 ret |= propagate_subaccesses_across_link (new_acc, rchild);
2393 continue;
2396 rchild->grp_hint = 1;
2397 new_acc = create_artificial_child_access (lacc, rchild, norm_offset);
2398 if (new_acc)
2400 ret = true;
2401 if (racc->first_child)
2402 propagate_subaccesses_across_link (new_acc, rchild);
2406 return ret;
2409 /* Propagate all subaccesses across assignment links. */
2411 static void
2412 propagate_all_subaccesses (void)
2414 while (work_queue_head)
2416 struct access *racc = pop_access_from_work_queue ();
2417 struct assign_link *link;
2419 gcc_assert (racc->first_link);
2421 for (link = racc->first_link; link; link = link->next)
2423 struct access *lacc = link->lacc;
2425 if (!bitmap_bit_p (candidate_bitmap, DECL_UID (lacc->base)))
2426 continue;
2427 lacc = lacc->group_representative;
2428 if (propagate_subaccesses_across_link (lacc, racc)
2429 && lacc->first_link)
2430 add_access_to_work_queue (lacc);
2435 /* Go through all accesses collected throughout the (intraprocedural) analysis
2436 stage, exclude overlapping ones, identify representatives and build trees
2437 out of them, making decisions about scalarization on the way. Return true
2438 iff there are any to-be-scalarized variables after this stage. */
2440 static bool
2441 analyze_all_variable_accesses (void)
2443 int res = 0;
2444 bitmap tmp = BITMAP_ALLOC (NULL);
2445 bitmap_iterator bi;
2446 unsigned i, max_total_scalarization_size;
2448 max_total_scalarization_size = UNITS_PER_WORD * BITS_PER_UNIT
2449 * MOVE_RATIO (optimize_function_for_speed_p (cfun));
2451 EXECUTE_IF_SET_IN_BITMAP (candidate_bitmap, 0, i, bi)
2452 if (bitmap_bit_p (should_scalarize_away_bitmap, i)
2453 && !bitmap_bit_p (cannot_scalarize_away_bitmap, i))
2455 tree var = candidate (i);
2457 if (TREE_CODE (var) == VAR_DECL
2458 && type_consists_of_records_p (TREE_TYPE (var)))
2460 if ((unsigned) tree_low_cst (TYPE_SIZE (TREE_TYPE (var)), 1)
2461 <= max_total_scalarization_size)
2463 completely_scalarize_var (var);
2464 if (dump_file && (dump_flags & TDF_DETAILS))
2466 fprintf (dump_file, "Will attempt to totally scalarize ");
2467 print_generic_expr (dump_file, var, 0);
2468 fprintf (dump_file, " (UID: %u): \n", DECL_UID (var));
2471 else if (dump_file && (dump_flags & TDF_DETAILS))
2473 fprintf (dump_file, "Too big to totally scalarize: ");
2474 print_generic_expr (dump_file, var, 0);
2475 fprintf (dump_file, " (UID: %u)\n", DECL_UID (var));
2480 bitmap_copy (tmp, candidate_bitmap);
2481 EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, bi)
2483 tree var = candidate (i);
2484 struct access *access;
2486 access = sort_and_splice_var_accesses (var);
2487 if (!access || !build_access_trees (access))
2488 disqualify_candidate (var,
2489 "No or inhibitingly overlapping accesses.");
2492 propagate_all_subaccesses ();
2494 bitmap_copy (tmp, candidate_bitmap);
2495 EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, bi)
2497 tree var = candidate (i);
2498 struct access *access = get_first_repr_for_decl (var);
2500 if (analyze_access_trees (access))
2502 res++;
2503 if (dump_file && (dump_flags & TDF_DETAILS))
2505 fprintf (dump_file, "\nAccess trees for ");
2506 print_generic_expr (dump_file, var, 0);
2507 fprintf (dump_file, " (UID: %u): \n", DECL_UID (var));
2508 dump_access_tree (dump_file, access);
2509 fprintf (dump_file, "\n");
2512 else
2513 disqualify_candidate (var, "No scalar replacements to be created.");
2516 BITMAP_FREE (tmp);
2518 if (res)
2520 statistics_counter_event (cfun, "Scalarized aggregates", res);
2521 return true;
2523 else
2524 return false;
2527 /* Generate statements copying scalar replacements of accesses within a subtree
2528 into or out of AGG. ACCESS, all its children, siblings and their children
2529 are to be processed. AGG is an aggregate type expression (can be a
2530 declaration but does not have to be, it can for example also be a mem_ref or
2531 a series of handled components). TOP_OFFSET is the offset of the processed
2532 subtree which has to be subtracted from offsets of individual accesses to
2533 get corresponding offsets for AGG. If CHUNK_SIZE is non-null, copy only
2534 replacements in the interval <start_offset, start_offset + chunk_size>,
2535 otherwise copy all. GSI is a statement iterator used to place the new
2536 statements. WRITE should be true when the statements should write from AGG
2537 to the replacement and false if vice versa. if INSERT_AFTER is true, new
2538 statements will be added after the current statement in GSI, they will be
2539 added before the statement otherwise. */
2541 static void
2542 generate_subtree_copies (struct access *access, tree agg,
2543 HOST_WIDE_INT top_offset,
2544 HOST_WIDE_INT start_offset, HOST_WIDE_INT chunk_size,
2545 gimple_stmt_iterator *gsi, bool write,
2546 bool insert_after, location_t loc)
2550 if (chunk_size && access->offset >= start_offset + chunk_size)
2551 return;
2553 if (access->grp_to_be_replaced
2554 && (chunk_size == 0
2555 || access->offset + access->size > start_offset))
2557 tree expr, repl = get_access_replacement (access);
2558 gimple stmt;
2560 expr = build_ref_for_model (loc, agg, access->offset - top_offset,
2561 access, gsi, insert_after);
2563 if (write)
2565 if (access->grp_partial_lhs)
2566 expr = force_gimple_operand_gsi (gsi, expr, true, NULL_TREE,
2567 !insert_after,
2568 insert_after ? GSI_NEW_STMT
2569 : GSI_SAME_STMT);
2570 stmt = gimple_build_assign (repl, expr);
2572 else
2574 TREE_NO_WARNING (repl) = 1;
2575 if (access->grp_partial_lhs)
2576 repl = force_gimple_operand_gsi (gsi, repl, true, NULL_TREE,
2577 !insert_after,
2578 insert_after ? GSI_NEW_STMT
2579 : GSI_SAME_STMT);
2580 stmt = gimple_build_assign (expr, repl);
2582 gimple_set_location (stmt, loc);
2584 if (insert_after)
2585 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
2586 else
2587 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
2588 update_stmt (stmt);
2589 sra_stats.subtree_copies++;
2591 else if (write
2592 && access->grp_to_be_debug_replaced
2593 && (chunk_size == 0
2594 || access->offset + access->size > start_offset))
2596 gimple ds;
2597 tree drhs = build_debug_ref_for_model (loc, agg,
2598 access->offset - top_offset,
2599 access);
2600 ds = gimple_build_debug_bind (get_access_replacement (access),
2601 drhs, gsi_stmt (*gsi));
2602 if (insert_after)
2603 gsi_insert_after (gsi, ds, GSI_NEW_STMT);
2604 else
2605 gsi_insert_before (gsi, ds, GSI_SAME_STMT);
2608 if (access->first_child)
2609 generate_subtree_copies (access->first_child, agg, top_offset,
2610 start_offset, chunk_size, gsi,
2611 write, insert_after, loc);
2613 access = access->next_sibling;
2615 while (access);
2618 /* Assign zero to all scalar replacements in an access subtree. ACCESS is the
2619 the root of the subtree to be processed. GSI is the statement iterator used
2620 for inserting statements which are added after the current statement if
2621 INSERT_AFTER is true or before it otherwise. */
2623 static void
2624 init_subtree_with_zero (struct access *access, gimple_stmt_iterator *gsi,
2625 bool insert_after, location_t loc)
2628 struct access *child;
2630 if (access->grp_to_be_replaced)
2632 gimple stmt;
2634 stmt = gimple_build_assign (get_access_replacement (access),
2635 build_zero_cst (access->type));
2636 if (insert_after)
2637 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
2638 else
2639 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
2640 update_stmt (stmt);
2641 gimple_set_location (stmt, loc);
2643 else if (access->grp_to_be_debug_replaced)
2645 gimple ds = gimple_build_debug_bind (get_access_replacement (access),
2646 build_zero_cst (access->type),
2647 gsi_stmt (*gsi));
2648 if (insert_after)
2649 gsi_insert_after (gsi, ds, GSI_NEW_STMT);
2650 else
2651 gsi_insert_before (gsi, ds, GSI_SAME_STMT);
2654 for (child = access->first_child; child; child = child->next_sibling)
2655 init_subtree_with_zero (child, gsi, insert_after, loc);
2658 /* Search for an access representative for the given expression EXPR and
2659 return it or NULL if it cannot be found. */
2661 static struct access *
2662 get_access_for_expr (tree expr)
2664 HOST_WIDE_INT offset, size, max_size;
2665 tree base;
2667 /* FIXME: This should not be necessary but Ada produces V_C_Es with a type of
2668 a different size than the size of its argument and we need the latter
2669 one. */
2670 if (TREE_CODE (expr) == VIEW_CONVERT_EXPR)
2671 expr = TREE_OPERAND (expr, 0);
2673 base = get_ref_base_and_extent (expr, &offset, &size, &max_size);
2674 if (max_size == -1 || !DECL_P (base))
2675 return NULL;
2677 if (!bitmap_bit_p (candidate_bitmap, DECL_UID (base)))
2678 return NULL;
2680 return get_var_base_offset_size_access (base, offset, max_size);
2683 /* Replace the expression EXPR with a scalar replacement if there is one and
2684 generate other statements to do type conversion or subtree copying if
2685 necessary. GSI is used to place newly created statements, WRITE is true if
2686 the expression is being written to (it is on a LHS of a statement or output
2687 in an assembly statement). */
2689 static bool
2690 sra_modify_expr (tree *expr, gimple_stmt_iterator *gsi, bool write)
2692 location_t loc;
2693 struct access *access;
2694 tree type, bfr;
2696 if (TREE_CODE (*expr) == BIT_FIELD_REF)
2698 bfr = *expr;
2699 expr = &TREE_OPERAND (*expr, 0);
2701 else
2702 bfr = NULL_TREE;
2704 if (TREE_CODE (*expr) == REALPART_EXPR || TREE_CODE (*expr) == IMAGPART_EXPR)
2705 expr = &TREE_OPERAND (*expr, 0);
2706 access = get_access_for_expr (*expr);
2707 if (!access)
2708 return false;
2709 type = TREE_TYPE (*expr);
2711 loc = gimple_location (gsi_stmt (*gsi));
2712 if (access->grp_to_be_replaced)
2714 tree repl = get_access_replacement (access);
2715 /* If we replace a non-register typed access simply use the original
2716 access expression to extract the scalar component afterwards.
2717 This happens if scalarizing a function return value or parameter
2718 like in gcc.c-torture/execute/20041124-1.c, 20050316-1.c and
2719 gcc.c-torture/compile/20011217-1.c.
2721 We also want to use this when accessing a complex or vector which can
2722 be accessed as a different type too, potentially creating a need for
2723 type conversion (see PR42196) and when scalarized unions are involved
2724 in assembler statements (see PR42398). */
2725 if (!useless_type_conversion_p (type, access->type))
2727 tree ref;
2729 ref = build_ref_for_model (loc, access->base, access->offset, access,
2730 NULL, false);
2732 if (write)
2734 gimple stmt;
2736 if (access->grp_partial_lhs)
2737 ref = force_gimple_operand_gsi (gsi, ref, true, NULL_TREE,
2738 false, GSI_NEW_STMT);
2739 stmt = gimple_build_assign (repl, ref);
2740 gimple_set_location (stmt, loc);
2741 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
2743 else
2745 gimple stmt;
2747 if (access->grp_partial_lhs)
2748 repl = force_gimple_operand_gsi (gsi, repl, true, NULL_TREE,
2749 true, GSI_SAME_STMT);
2750 stmt = gimple_build_assign (ref, repl);
2751 gimple_set_location (stmt, loc);
2752 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
2755 else
2756 *expr = repl;
2757 sra_stats.exprs++;
2759 else if (write && access->grp_to_be_debug_replaced)
2761 gimple ds = gimple_build_debug_bind (get_access_replacement (access),
2762 NULL_TREE,
2763 gsi_stmt (*gsi));
2764 gsi_insert_after (gsi, ds, GSI_NEW_STMT);
2767 if (access->first_child)
2769 HOST_WIDE_INT start_offset, chunk_size;
2770 if (bfr
2771 && host_integerp (TREE_OPERAND (bfr, 1), 1)
2772 && host_integerp (TREE_OPERAND (bfr, 2), 1))
2774 chunk_size = tree_low_cst (TREE_OPERAND (bfr, 1), 1);
2775 start_offset = access->offset
2776 + tree_low_cst (TREE_OPERAND (bfr, 2), 1);
2778 else
2779 start_offset = chunk_size = 0;
2781 generate_subtree_copies (access->first_child, access->base, 0,
2782 start_offset, chunk_size, gsi, write, write,
2783 loc);
2785 return true;
2788 /* Where scalar replacements of the RHS have been written to when a replacement
2789 of a LHS of an assigments cannot be direclty loaded from a replacement of
2790 the RHS. */
2791 enum unscalarized_data_handling { SRA_UDH_NONE, /* Nothing done so far. */
2792 SRA_UDH_RIGHT, /* Data flushed to the RHS. */
2793 SRA_UDH_LEFT }; /* Data flushed to the LHS. */
2795 /* Store all replacements in the access tree rooted in TOP_RACC either to their
2796 base aggregate if there are unscalarized data or directly to LHS of the
2797 statement that is pointed to by GSI otherwise. */
2799 static enum unscalarized_data_handling
2800 handle_unscalarized_data_in_subtree (struct access *top_racc,
2801 gimple_stmt_iterator *gsi)
2803 if (top_racc->grp_unscalarized_data)
2805 generate_subtree_copies (top_racc->first_child, top_racc->base, 0, 0, 0,
2806 gsi, false, false,
2807 gimple_location (gsi_stmt (*gsi)));
2808 return SRA_UDH_RIGHT;
2810 else
2812 tree lhs = gimple_assign_lhs (gsi_stmt (*gsi));
2813 generate_subtree_copies (top_racc->first_child, lhs, top_racc->offset,
2814 0, 0, gsi, false, false,
2815 gimple_location (gsi_stmt (*gsi)));
2816 return SRA_UDH_LEFT;
2821 /* Try to generate statements to load all sub-replacements in an access subtree
2822 formed by children of LACC from scalar replacements in the TOP_RACC subtree.
2823 If that is not possible, refresh the TOP_RACC base aggregate and load the
2824 accesses from it. LEFT_OFFSET is the offset of the left whole subtree being
2825 copied. NEW_GSI is stmt iterator used for statement insertions after the
2826 original assignment, OLD_GSI is used to insert statements before the
2827 assignment. *REFRESHED keeps the information whether we have needed to
2828 refresh replacements of the LHS and from which side of the assignments this
2829 takes place. */
2831 static void
2832 load_assign_lhs_subreplacements (struct access *lacc, struct access *top_racc,
2833 HOST_WIDE_INT left_offset,
2834 gimple_stmt_iterator *old_gsi,
2835 gimple_stmt_iterator *new_gsi,
2836 enum unscalarized_data_handling *refreshed)
2838 location_t loc = gimple_location (gsi_stmt (*old_gsi));
2839 for (lacc = lacc->first_child; lacc; lacc = lacc->next_sibling)
2841 HOST_WIDE_INT offset = lacc->offset - left_offset + top_racc->offset;
2843 if (lacc->grp_to_be_replaced)
2845 struct access *racc;
2846 gimple stmt;
2847 tree rhs;
2849 racc = find_access_in_subtree (top_racc, offset, lacc->size);
2850 if (racc && racc->grp_to_be_replaced)
2852 rhs = get_access_replacement (racc);
2853 if (!useless_type_conversion_p (lacc->type, racc->type))
2854 rhs = fold_build1_loc (loc, VIEW_CONVERT_EXPR, lacc->type, rhs);
2856 if (racc->grp_partial_lhs && lacc->grp_partial_lhs)
2857 rhs = force_gimple_operand_gsi (old_gsi, rhs, true, NULL_TREE,
2858 true, GSI_SAME_STMT);
2860 else
2862 /* No suitable access on the right hand side, need to load from
2863 the aggregate. See if we have to update it first... */
2864 if (*refreshed == SRA_UDH_NONE)
2865 *refreshed = handle_unscalarized_data_in_subtree (top_racc,
2866 old_gsi);
2868 if (*refreshed == SRA_UDH_LEFT)
2869 rhs = build_ref_for_model (loc, lacc->base, lacc->offset, lacc,
2870 new_gsi, true);
2871 else
2872 rhs = build_ref_for_model (loc, top_racc->base, offset, lacc,
2873 new_gsi, true);
2874 if (lacc->grp_partial_lhs)
2875 rhs = force_gimple_operand_gsi (new_gsi, rhs, true, NULL_TREE,
2876 false, GSI_NEW_STMT);
2879 stmt = gimple_build_assign (get_access_replacement (lacc), rhs);
2880 gsi_insert_after (new_gsi, stmt, GSI_NEW_STMT);
2881 gimple_set_location (stmt, loc);
2882 update_stmt (stmt);
2883 sra_stats.subreplacements++;
2885 else
2887 if (*refreshed == SRA_UDH_NONE
2888 && lacc->grp_read && !lacc->grp_covered)
2889 *refreshed = handle_unscalarized_data_in_subtree (top_racc,
2890 old_gsi);
2891 if (lacc && lacc->grp_to_be_debug_replaced)
2893 gimple ds;
2894 tree drhs;
2895 struct access *racc = find_access_in_subtree (top_racc, offset,
2896 lacc->size);
2898 if (racc && racc->grp_to_be_replaced)
2900 if (racc->grp_write)
2901 drhs = get_access_replacement (racc);
2902 else
2903 drhs = NULL;
2905 else if (*refreshed == SRA_UDH_LEFT)
2906 drhs = build_debug_ref_for_model (loc, lacc->base, lacc->offset,
2907 lacc);
2908 else if (*refreshed == SRA_UDH_RIGHT)
2909 drhs = build_debug_ref_for_model (loc, top_racc->base, offset,
2910 lacc);
2911 else
2912 drhs = NULL_TREE;
2913 ds = gimple_build_debug_bind (get_access_replacement (lacc),
2914 drhs, gsi_stmt (*old_gsi));
2915 gsi_insert_after (new_gsi, ds, GSI_NEW_STMT);
2919 if (lacc->first_child)
2920 load_assign_lhs_subreplacements (lacc, top_racc, left_offset,
2921 old_gsi, new_gsi, refreshed);
2925 /* Result code for SRA assignment modification. */
2926 enum assignment_mod_result { SRA_AM_NONE, /* nothing done for the stmt */
2927 SRA_AM_MODIFIED, /* stmt changed but not
2928 removed */
2929 SRA_AM_REMOVED }; /* stmt eliminated */
2931 /* Modify assignments with a CONSTRUCTOR on their RHS. STMT contains a pointer
2932 to the assignment and GSI is the statement iterator pointing at it. Returns
2933 the same values as sra_modify_assign. */
2935 static enum assignment_mod_result
2936 sra_modify_constructor_assign (gimple *stmt, gimple_stmt_iterator *gsi)
2938 tree lhs = gimple_assign_lhs (*stmt);
2939 struct access *acc;
2940 location_t loc;
2942 acc = get_access_for_expr (lhs);
2943 if (!acc)
2944 return SRA_AM_NONE;
2946 if (gimple_clobber_p (*stmt))
2948 /* Remove clobbers of fully scalarized variables, otherwise
2949 do nothing. */
2950 if (acc->grp_covered)
2952 unlink_stmt_vdef (*stmt);
2953 gsi_remove (gsi, true);
2954 release_defs (*stmt);
2955 return SRA_AM_REMOVED;
2957 else
2958 return SRA_AM_NONE;
2961 loc = gimple_location (*stmt);
2962 if (vec_safe_length (CONSTRUCTOR_ELTS (gimple_assign_rhs1 (*stmt))) > 0)
2964 /* I have never seen this code path trigger but if it can happen the
2965 following should handle it gracefully. */
2966 if (access_has_children_p (acc))
2967 generate_subtree_copies (acc->first_child, acc->base, 0, 0, 0, gsi,
2968 true, true, loc);
2969 return SRA_AM_MODIFIED;
2972 if (acc->grp_covered)
2974 init_subtree_with_zero (acc, gsi, false, loc);
2975 unlink_stmt_vdef (*stmt);
2976 gsi_remove (gsi, true);
2977 release_defs (*stmt);
2978 return SRA_AM_REMOVED;
2980 else
2982 init_subtree_with_zero (acc, gsi, true, loc);
2983 return SRA_AM_MODIFIED;
2987 /* Create and return a new suitable default definition SSA_NAME for RACC which
2988 is an access describing an uninitialized part of an aggregate that is being
2989 loaded. */
2991 static tree
2992 get_repl_default_def_ssa_name (struct access *racc)
2994 gcc_checking_assert (!racc->grp_to_be_replaced
2995 && !racc->grp_to_be_debug_replaced);
2996 if (!racc->replacement_decl)
2997 racc->replacement_decl = create_access_replacement (racc);
2998 return get_or_create_ssa_default_def (cfun, racc->replacement_decl);
3001 /* Return true if REF has an VIEW_CONVERT_EXPR or a COMPONENT_REF with a
3002 bit-field field declaration somewhere in it. */
3004 static inline bool
3005 contains_vce_or_bfcref_p (const_tree ref)
3007 while (handled_component_p (ref))
3009 if (TREE_CODE (ref) == VIEW_CONVERT_EXPR
3010 || (TREE_CODE (ref) == COMPONENT_REF
3011 && DECL_BIT_FIELD (TREE_OPERAND (ref, 1))))
3012 return true;
3013 ref = TREE_OPERAND (ref, 0);
3016 return false;
3019 /* Examine both sides of the assignment statement pointed to by STMT, replace
3020 them with a scalare replacement if there is one and generate copying of
3021 replacements if scalarized aggregates have been used in the assignment. GSI
3022 is used to hold generated statements for type conversions and subtree
3023 copying. */
3025 static enum assignment_mod_result
3026 sra_modify_assign (gimple *stmt, gimple_stmt_iterator *gsi)
3028 struct access *lacc, *racc;
3029 tree lhs, rhs;
3030 bool modify_this_stmt = false;
3031 bool force_gimple_rhs = false;
3032 location_t loc;
3033 gimple_stmt_iterator orig_gsi = *gsi;
3035 if (!gimple_assign_single_p (*stmt))
3036 return SRA_AM_NONE;
3037 lhs = gimple_assign_lhs (*stmt);
3038 rhs = gimple_assign_rhs1 (*stmt);
3040 if (TREE_CODE (rhs) == CONSTRUCTOR)
3041 return sra_modify_constructor_assign (stmt, gsi);
3043 if (TREE_CODE (rhs) == REALPART_EXPR || TREE_CODE (lhs) == REALPART_EXPR
3044 || TREE_CODE (rhs) == IMAGPART_EXPR || TREE_CODE (lhs) == IMAGPART_EXPR
3045 || TREE_CODE (rhs) == BIT_FIELD_REF || TREE_CODE (lhs) == BIT_FIELD_REF)
3047 modify_this_stmt = sra_modify_expr (gimple_assign_rhs1_ptr (*stmt),
3048 gsi, false);
3049 modify_this_stmt |= sra_modify_expr (gimple_assign_lhs_ptr (*stmt),
3050 gsi, true);
3051 return modify_this_stmt ? SRA_AM_MODIFIED : SRA_AM_NONE;
3054 lacc = get_access_for_expr (lhs);
3055 racc = get_access_for_expr (rhs);
3056 if (!lacc && !racc)
3057 return SRA_AM_NONE;
3059 loc = gimple_location (*stmt);
3060 if (lacc && lacc->grp_to_be_replaced)
3062 lhs = get_access_replacement (lacc);
3063 gimple_assign_set_lhs (*stmt, lhs);
3064 modify_this_stmt = true;
3065 if (lacc->grp_partial_lhs)
3066 force_gimple_rhs = true;
3067 sra_stats.exprs++;
3070 if (racc && racc->grp_to_be_replaced)
3072 rhs = get_access_replacement (racc);
3073 modify_this_stmt = true;
3074 if (racc->grp_partial_lhs)
3075 force_gimple_rhs = true;
3076 sra_stats.exprs++;
3078 else if (racc
3079 && !racc->grp_unscalarized_data
3080 && TREE_CODE (lhs) == SSA_NAME
3081 && !access_has_replacements_p (racc))
3083 rhs = get_repl_default_def_ssa_name (racc);
3084 modify_this_stmt = true;
3085 sra_stats.exprs++;
3088 if (modify_this_stmt)
3090 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (rhs)))
3092 /* If we can avoid creating a VIEW_CONVERT_EXPR do so.
3093 ??? This should move to fold_stmt which we simply should
3094 call after building a VIEW_CONVERT_EXPR here. */
3095 if (AGGREGATE_TYPE_P (TREE_TYPE (lhs))
3096 && !contains_bitfld_component_ref_p (lhs))
3098 lhs = build_ref_for_model (loc, lhs, 0, racc, gsi, false);
3099 gimple_assign_set_lhs (*stmt, lhs);
3101 else if (AGGREGATE_TYPE_P (TREE_TYPE (rhs))
3102 && !contains_vce_or_bfcref_p (rhs))
3103 rhs = build_ref_for_model (loc, rhs, 0, lacc, gsi, false);
3105 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (rhs)))
3107 rhs = fold_build1_loc (loc, VIEW_CONVERT_EXPR, TREE_TYPE (lhs),
3108 rhs);
3109 if (is_gimple_reg_type (TREE_TYPE (lhs))
3110 && TREE_CODE (lhs) != SSA_NAME)
3111 force_gimple_rhs = true;
3116 if (lacc && lacc->grp_to_be_debug_replaced)
3118 tree dlhs = get_access_replacement (lacc);
3119 tree drhs = unshare_expr (rhs);
3120 if (!useless_type_conversion_p (TREE_TYPE (dlhs), TREE_TYPE (drhs)))
3122 if (AGGREGATE_TYPE_P (TREE_TYPE (drhs))
3123 && !contains_vce_or_bfcref_p (drhs))
3124 drhs = build_debug_ref_for_model (loc, drhs, 0, lacc);
3125 if (drhs
3126 && !useless_type_conversion_p (TREE_TYPE (dlhs),
3127 TREE_TYPE (drhs)))
3128 drhs = fold_build1_loc (loc, VIEW_CONVERT_EXPR,
3129 TREE_TYPE (dlhs), drhs);
3131 gimple ds = gimple_build_debug_bind (dlhs, drhs, *stmt);
3132 gsi_insert_before (gsi, ds, GSI_SAME_STMT);
3135 /* From this point on, the function deals with assignments in between
3136 aggregates when at least one has scalar reductions of some of its
3137 components. There are three possible scenarios: Both the LHS and RHS have
3138 to-be-scalarized components, 2) only the RHS has or 3) only the LHS has.
3140 In the first case, we would like to load the LHS components from RHS
3141 components whenever possible. If that is not possible, we would like to
3142 read it directly from the RHS (after updating it by storing in it its own
3143 components). If there are some necessary unscalarized data in the LHS,
3144 those will be loaded by the original assignment too. If neither of these
3145 cases happen, the original statement can be removed. Most of this is done
3146 by load_assign_lhs_subreplacements.
3148 In the second case, we would like to store all RHS scalarized components
3149 directly into LHS and if they cover the aggregate completely, remove the
3150 statement too. In the third case, we want the LHS components to be loaded
3151 directly from the RHS (DSE will remove the original statement if it
3152 becomes redundant).
3154 This is a bit complex but manageable when types match and when unions do
3155 not cause confusion in a way that we cannot really load a component of LHS
3156 from the RHS or vice versa (the access representing this level can have
3157 subaccesses that are accessible only through a different union field at a
3158 higher level - different from the one used in the examined expression).
3159 Unions are fun.
3161 Therefore, I specially handle a fourth case, happening when there is a
3162 specific type cast or it is impossible to locate a scalarized subaccess on
3163 the other side of the expression. If that happens, I simply "refresh" the
3164 RHS by storing in it is scalarized components leave the original statement
3165 there to do the copying and then load the scalar replacements of the LHS.
3166 This is what the first branch does. */
3168 if (modify_this_stmt
3169 || gimple_has_volatile_ops (*stmt)
3170 || contains_vce_or_bfcref_p (rhs)
3171 || contains_vce_or_bfcref_p (lhs))
3173 if (access_has_children_p (racc))
3174 generate_subtree_copies (racc->first_child, racc->base, 0, 0, 0,
3175 gsi, false, false, loc);
3176 if (access_has_children_p (lacc))
3177 generate_subtree_copies (lacc->first_child, lacc->base, 0, 0, 0,
3178 gsi, true, true, loc);
3179 sra_stats.separate_lhs_rhs_handling++;
3181 /* This gimplification must be done after generate_subtree_copies,
3182 lest we insert the subtree copies in the middle of the gimplified
3183 sequence. */
3184 if (force_gimple_rhs)
3185 rhs = force_gimple_operand_gsi (&orig_gsi, rhs, true, NULL_TREE,
3186 true, GSI_SAME_STMT);
3187 if (gimple_assign_rhs1 (*stmt) != rhs)
3189 modify_this_stmt = true;
3190 gimple_assign_set_rhs_from_tree (&orig_gsi, rhs);
3191 gcc_assert (*stmt == gsi_stmt (orig_gsi));
3194 return modify_this_stmt ? SRA_AM_MODIFIED : SRA_AM_NONE;
3196 else
3198 if (access_has_children_p (lacc)
3199 && access_has_children_p (racc)
3200 /* When an access represents an unscalarizable region, it usually
3201 represents accesses with variable offset and thus must not be used
3202 to generate new memory accesses. */
3203 && !lacc->grp_unscalarizable_region
3204 && !racc->grp_unscalarizable_region)
3206 gimple_stmt_iterator orig_gsi = *gsi;
3207 enum unscalarized_data_handling refreshed;
3209 if (lacc->grp_read && !lacc->grp_covered)
3210 refreshed = handle_unscalarized_data_in_subtree (racc, gsi);
3211 else
3212 refreshed = SRA_UDH_NONE;
3214 load_assign_lhs_subreplacements (lacc, racc, lacc->offset,
3215 &orig_gsi, gsi, &refreshed);
3216 if (refreshed != SRA_UDH_RIGHT)
3218 gsi_next (gsi);
3219 unlink_stmt_vdef (*stmt);
3220 gsi_remove (&orig_gsi, true);
3221 release_defs (*stmt);
3222 sra_stats.deleted++;
3223 return SRA_AM_REMOVED;
3226 else
3228 if (access_has_children_p (racc)
3229 && !racc->grp_unscalarized_data)
3231 if (dump_file)
3233 fprintf (dump_file, "Removing load: ");
3234 print_gimple_stmt (dump_file, *stmt, 0, 0);
3236 generate_subtree_copies (racc->first_child, lhs,
3237 racc->offset, 0, 0, gsi,
3238 false, false, loc);
3239 gcc_assert (*stmt == gsi_stmt (*gsi));
3240 unlink_stmt_vdef (*stmt);
3241 gsi_remove (gsi, true);
3242 release_defs (*stmt);
3243 sra_stats.deleted++;
3244 return SRA_AM_REMOVED;
3246 /* Restore the aggregate RHS from its components so the
3247 prevailing aggregate copy does the right thing. */
3248 if (access_has_children_p (racc))
3249 generate_subtree_copies (racc->first_child, racc->base, 0, 0, 0,
3250 gsi, false, false, loc);
3251 /* Re-load the components of the aggregate copy destination.
3252 But use the RHS aggregate to load from to expose more
3253 optimization opportunities. */
3254 if (access_has_children_p (lacc))
3255 generate_subtree_copies (lacc->first_child, rhs, lacc->offset,
3256 0, 0, gsi, true, true, loc);
3259 return SRA_AM_NONE;
3263 /* Traverse the function body and all modifications as decided in
3264 analyze_all_variable_accesses. Return true iff the CFG has been
3265 changed. */
3267 static bool
3268 sra_modify_function_body (void)
3270 bool cfg_changed = false;
3271 basic_block bb;
3273 FOR_EACH_BB (bb)
3275 gimple_stmt_iterator gsi = gsi_start_bb (bb);
3276 while (!gsi_end_p (gsi))
3278 gimple stmt = gsi_stmt (gsi);
3279 enum assignment_mod_result assign_result;
3280 bool modified = false, deleted = false;
3281 tree *t;
3282 unsigned i;
3284 switch (gimple_code (stmt))
3286 case GIMPLE_RETURN:
3287 t = gimple_return_retval_ptr (stmt);
3288 if (*t != NULL_TREE)
3289 modified |= sra_modify_expr (t, &gsi, false);
3290 break;
3292 case GIMPLE_ASSIGN:
3293 assign_result = sra_modify_assign (&stmt, &gsi);
3294 modified |= assign_result == SRA_AM_MODIFIED;
3295 deleted = assign_result == SRA_AM_REMOVED;
3296 break;
3298 case GIMPLE_CALL:
3299 /* Operands must be processed before the lhs. */
3300 for (i = 0; i < gimple_call_num_args (stmt); i++)
3302 t = gimple_call_arg_ptr (stmt, i);
3303 modified |= sra_modify_expr (t, &gsi, false);
3306 if (gimple_call_lhs (stmt))
3308 t = gimple_call_lhs_ptr (stmt);
3309 modified |= sra_modify_expr (t, &gsi, true);
3311 break;
3313 case GIMPLE_ASM:
3314 for (i = 0; i < gimple_asm_ninputs (stmt); i++)
3316 t = &TREE_VALUE (gimple_asm_input_op (stmt, i));
3317 modified |= sra_modify_expr (t, &gsi, false);
3319 for (i = 0; i < gimple_asm_noutputs (stmt); i++)
3321 t = &TREE_VALUE (gimple_asm_output_op (stmt, i));
3322 modified |= sra_modify_expr (t, &gsi, true);
3324 break;
3326 default:
3327 break;
3330 if (modified)
3332 update_stmt (stmt);
3333 if (maybe_clean_eh_stmt (stmt)
3334 && gimple_purge_dead_eh_edges (gimple_bb (stmt)))
3335 cfg_changed = true;
3337 if (!deleted)
3338 gsi_next (&gsi);
3342 return cfg_changed;
3345 /* Generate statements initializing scalar replacements of parts of function
3346 parameters. */
3348 static void
3349 initialize_parameter_reductions (void)
3351 gimple_stmt_iterator gsi;
3352 gimple_seq seq = NULL;
3353 tree parm;
3355 gsi = gsi_start (seq);
3356 for (parm = DECL_ARGUMENTS (current_function_decl);
3357 parm;
3358 parm = DECL_CHAIN (parm))
3360 vec<access_p> *access_vec;
3361 struct access *access;
3363 if (!bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
3364 continue;
3365 access_vec = get_base_access_vector (parm);
3366 if (!access_vec)
3367 continue;
3369 for (access = (*access_vec)[0];
3370 access;
3371 access = access->next_grp)
3372 generate_subtree_copies (access, parm, 0, 0, 0, &gsi, true, true,
3373 EXPR_LOCATION (parm));
3376 seq = gsi_seq (gsi);
3377 if (seq)
3378 gsi_insert_seq_on_edge_immediate (single_succ_edge (ENTRY_BLOCK_PTR), seq);
3381 /* The "main" function of intraprocedural SRA passes. Runs the analysis and if
3382 it reveals there are components of some aggregates to be scalarized, it runs
3383 the required transformations. */
3384 static unsigned int
3385 perform_intra_sra (void)
3387 int ret = 0;
3388 sra_initialize ();
3390 if (!find_var_candidates ())
3391 goto out;
3393 if (!scan_function ())
3394 goto out;
3396 if (!analyze_all_variable_accesses ())
3397 goto out;
3399 if (sra_modify_function_body ())
3400 ret = TODO_update_ssa | TODO_cleanup_cfg;
3401 else
3402 ret = TODO_update_ssa;
3403 initialize_parameter_reductions ();
3405 statistics_counter_event (cfun, "Scalar replacements created",
3406 sra_stats.replacements);
3407 statistics_counter_event (cfun, "Modified expressions", sra_stats.exprs);
3408 statistics_counter_event (cfun, "Subtree copy stmts",
3409 sra_stats.subtree_copies);
3410 statistics_counter_event (cfun, "Subreplacement stmts",
3411 sra_stats.subreplacements);
3412 statistics_counter_event (cfun, "Deleted stmts", sra_stats.deleted);
3413 statistics_counter_event (cfun, "Separate LHS and RHS handling",
3414 sra_stats.separate_lhs_rhs_handling);
3416 out:
3417 sra_deinitialize ();
3418 return ret;
3421 /* Perform early intraprocedural SRA. */
3422 static unsigned int
3423 early_intra_sra (void)
3425 sra_mode = SRA_MODE_EARLY_INTRA;
3426 return perform_intra_sra ();
3429 /* Perform "late" intraprocedural SRA. */
3430 static unsigned int
3431 late_intra_sra (void)
3433 sra_mode = SRA_MODE_INTRA;
3434 return perform_intra_sra ();
3438 static bool
3439 gate_intra_sra (void)
3441 return flag_tree_sra != 0 && dbg_cnt (tree_sra);
3445 struct gimple_opt_pass pass_sra_early =
3448 GIMPLE_PASS,
3449 "esra", /* name */
3450 OPTGROUP_NONE, /* optinfo_flags */
3451 gate_intra_sra, /* gate */
3452 early_intra_sra, /* execute */
3453 NULL, /* sub */
3454 NULL, /* next */
3455 0, /* static_pass_number */
3456 TV_TREE_SRA, /* tv_id */
3457 PROP_cfg | PROP_ssa, /* properties_required */
3458 0, /* properties_provided */
3459 0, /* properties_destroyed */
3460 0, /* todo_flags_start */
3461 TODO_update_ssa
3462 | TODO_verify_ssa /* todo_flags_finish */
3466 struct gimple_opt_pass pass_sra =
3469 GIMPLE_PASS,
3470 "sra", /* name */
3471 OPTGROUP_NONE, /* optinfo_flags */
3472 gate_intra_sra, /* gate */
3473 late_intra_sra, /* execute */
3474 NULL, /* sub */
3475 NULL, /* next */
3476 0, /* static_pass_number */
3477 TV_TREE_SRA, /* tv_id */
3478 PROP_cfg | PROP_ssa, /* properties_required */
3479 0, /* properties_provided */
3480 0, /* properties_destroyed */
3481 TODO_update_address_taken, /* todo_flags_start */
3482 TODO_update_ssa
3483 | TODO_verify_ssa /* todo_flags_finish */
3488 /* Return true iff PARM (which must be a parm_decl) is an unused scalar
3489 parameter. */
3491 static bool
3492 is_unused_scalar_param (tree parm)
3494 tree name;
3495 return (is_gimple_reg (parm)
3496 && (!(name = ssa_default_def (cfun, parm))
3497 || has_zero_uses (name)));
3500 /* Scan immediate uses of a default definition SSA name of a parameter PARM and
3501 examine whether there are any direct or otherwise infeasible ones. If so,
3502 return true, otherwise return false. PARM must be a gimple register with a
3503 non-NULL default definition. */
3505 static bool
3506 ptr_parm_has_direct_uses (tree parm)
3508 imm_use_iterator ui;
3509 gimple stmt;
3510 tree name = ssa_default_def (cfun, parm);
3511 bool ret = false;
3513 FOR_EACH_IMM_USE_STMT (stmt, ui, name)
3515 int uses_ok = 0;
3516 use_operand_p use_p;
3518 if (is_gimple_debug (stmt))
3519 continue;
3521 /* Valid uses include dereferences on the lhs and the rhs. */
3522 if (gimple_has_lhs (stmt))
3524 tree lhs = gimple_get_lhs (stmt);
3525 while (handled_component_p (lhs))
3526 lhs = TREE_OPERAND (lhs, 0);
3527 if (TREE_CODE (lhs) == MEM_REF
3528 && TREE_OPERAND (lhs, 0) == name
3529 && integer_zerop (TREE_OPERAND (lhs, 1))
3530 && types_compatible_p (TREE_TYPE (lhs),
3531 TREE_TYPE (TREE_TYPE (name)))
3532 && !TREE_THIS_VOLATILE (lhs))
3533 uses_ok++;
3535 if (gimple_assign_single_p (stmt))
3537 tree rhs = gimple_assign_rhs1 (stmt);
3538 while (handled_component_p (rhs))
3539 rhs = TREE_OPERAND (rhs, 0);
3540 if (TREE_CODE (rhs) == MEM_REF
3541 && TREE_OPERAND (rhs, 0) == name
3542 && integer_zerop (TREE_OPERAND (rhs, 1))
3543 && types_compatible_p (TREE_TYPE (rhs),
3544 TREE_TYPE (TREE_TYPE (name)))
3545 && !TREE_THIS_VOLATILE (rhs))
3546 uses_ok++;
3548 else if (is_gimple_call (stmt))
3550 unsigned i;
3551 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3553 tree arg = gimple_call_arg (stmt, i);
3554 while (handled_component_p (arg))
3555 arg = TREE_OPERAND (arg, 0);
3556 if (TREE_CODE (arg) == MEM_REF
3557 && TREE_OPERAND (arg, 0) == name
3558 && integer_zerop (TREE_OPERAND (arg, 1))
3559 && types_compatible_p (TREE_TYPE (arg),
3560 TREE_TYPE (TREE_TYPE (name)))
3561 && !TREE_THIS_VOLATILE (arg))
3562 uses_ok++;
3566 /* If the number of valid uses does not match the number of
3567 uses in this stmt there is an unhandled use. */
3568 FOR_EACH_IMM_USE_ON_STMT (use_p, ui)
3569 --uses_ok;
3571 if (uses_ok != 0)
3572 ret = true;
3574 if (ret)
3575 BREAK_FROM_IMM_USE_STMT (ui);
3578 return ret;
3581 /* Identify candidates for reduction for IPA-SRA based on their type and mark
3582 them in candidate_bitmap. Note that these do not necessarily include
3583 parameter which are unused and thus can be removed. Return true iff any
3584 such candidate has been found. */
3586 static bool
3587 find_param_candidates (void)
3589 tree parm;
3590 int count = 0;
3591 bool ret = false;
3592 const char *msg;
3594 for (parm = DECL_ARGUMENTS (current_function_decl);
3595 parm;
3596 parm = DECL_CHAIN (parm))
3598 tree type = TREE_TYPE (parm);
3599 tree_node **slot;
3601 count++;
3603 if (TREE_THIS_VOLATILE (parm)
3604 || TREE_ADDRESSABLE (parm)
3605 || (!is_gimple_reg_type (type) && is_va_list_type (type)))
3606 continue;
3608 if (is_unused_scalar_param (parm))
3610 ret = true;
3611 continue;
3614 if (POINTER_TYPE_P (type))
3616 type = TREE_TYPE (type);
3618 if (TREE_CODE (type) == FUNCTION_TYPE
3619 || TYPE_VOLATILE (type)
3620 || (TREE_CODE (type) == ARRAY_TYPE
3621 && TYPE_NONALIASED_COMPONENT (type))
3622 || !is_gimple_reg (parm)
3623 || is_va_list_type (type)
3624 || ptr_parm_has_direct_uses (parm))
3625 continue;
3627 else if (!AGGREGATE_TYPE_P (type))
3628 continue;
3630 if (!COMPLETE_TYPE_P (type)
3631 || !host_integerp (TYPE_SIZE (type), 1)
3632 || tree_low_cst (TYPE_SIZE (type), 1) == 0
3633 || (AGGREGATE_TYPE_P (type)
3634 && type_internals_preclude_sra_p (type, &msg)))
3635 continue;
3637 bitmap_set_bit (candidate_bitmap, DECL_UID (parm));
3638 slot = candidates.find_slot_with_hash (parm, DECL_UID (parm), INSERT);
3639 *slot = parm;
3641 ret = true;
3642 if (dump_file && (dump_flags & TDF_DETAILS))
3644 fprintf (dump_file, "Candidate (%d): ", DECL_UID (parm));
3645 print_generic_expr (dump_file, parm, 0);
3646 fprintf (dump_file, "\n");
3650 func_param_count = count;
3651 return ret;
3654 /* Callback of walk_aliased_vdefs, marks the access passed as DATA as
3655 maybe_modified. */
3657 static bool
3658 mark_maybe_modified (ao_ref *ao ATTRIBUTE_UNUSED, tree vdef ATTRIBUTE_UNUSED,
3659 void *data)
3661 struct access *repr = (struct access *) data;
3663 repr->grp_maybe_modified = 1;
3664 return true;
3667 /* Analyze what representatives (in linked lists accessible from
3668 REPRESENTATIVES) can be modified by side effects of statements in the
3669 current function. */
3671 static void
3672 analyze_modified_params (vec<access_p> representatives)
3674 int i;
3676 for (i = 0; i < func_param_count; i++)
3678 struct access *repr;
3680 for (repr = representatives[i];
3681 repr;
3682 repr = repr->next_grp)
3684 struct access *access;
3685 bitmap visited;
3686 ao_ref ar;
3688 if (no_accesses_p (repr))
3689 continue;
3690 if (!POINTER_TYPE_P (TREE_TYPE (repr->base))
3691 || repr->grp_maybe_modified)
3692 continue;
3694 ao_ref_init (&ar, repr->expr);
3695 visited = BITMAP_ALLOC (NULL);
3696 for (access = repr; access; access = access->next_sibling)
3698 /* All accesses are read ones, otherwise grp_maybe_modified would
3699 be trivially set. */
3700 walk_aliased_vdefs (&ar, gimple_vuse (access->stmt),
3701 mark_maybe_modified, repr, &visited);
3702 if (repr->grp_maybe_modified)
3703 break;
3705 BITMAP_FREE (visited);
3710 /* Propagate distances in bb_dereferences in the opposite direction than the
3711 control flow edges, in each step storing the maximum of the current value
3712 and the minimum of all successors. These steps are repeated until the table
3713 stabilizes. Note that BBs which might terminate the functions (according to
3714 final_bbs bitmap) never updated in this way. */
3716 static void
3717 propagate_dereference_distances (void)
3719 vec<basic_block> queue;
3720 basic_block bb;
3722 queue.create (last_basic_block_for_function (cfun));
3723 queue.quick_push (ENTRY_BLOCK_PTR);
3724 FOR_EACH_BB (bb)
3726 queue.quick_push (bb);
3727 bb->aux = bb;
3730 while (!queue.is_empty ())
3732 edge_iterator ei;
3733 edge e;
3734 bool change = false;
3735 int i;
3737 bb = queue.pop ();
3738 bb->aux = NULL;
3740 if (bitmap_bit_p (final_bbs, bb->index))
3741 continue;
3743 for (i = 0; i < func_param_count; i++)
3745 int idx = bb->index * func_param_count + i;
3746 bool first = true;
3747 HOST_WIDE_INT inh = 0;
3749 FOR_EACH_EDGE (e, ei, bb->succs)
3751 int succ_idx = e->dest->index * func_param_count + i;
3753 if (e->src == EXIT_BLOCK_PTR)
3754 continue;
3756 if (first)
3758 first = false;
3759 inh = bb_dereferences [succ_idx];
3761 else if (bb_dereferences [succ_idx] < inh)
3762 inh = bb_dereferences [succ_idx];
3765 if (!first && bb_dereferences[idx] < inh)
3767 bb_dereferences[idx] = inh;
3768 change = true;
3772 if (change && !bitmap_bit_p (final_bbs, bb->index))
3773 FOR_EACH_EDGE (e, ei, bb->preds)
3775 if (e->src->aux)
3776 continue;
3778 e->src->aux = e->src;
3779 queue.quick_push (e->src);
3783 queue.release ();
3786 /* Dump a dereferences TABLE with heading STR to file F. */
3788 static void
3789 dump_dereferences_table (FILE *f, const char *str, HOST_WIDE_INT *table)
3791 basic_block bb;
3793 fprintf (dump_file, str);
3794 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, EXIT_BLOCK_PTR, next_bb)
3796 fprintf (f, "%4i %i ", bb->index, bitmap_bit_p (final_bbs, bb->index));
3797 if (bb != EXIT_BLOCK_PTR)
3799 int i;
3800 for (i = 0; i < func_param_count; i++)
3802 int idx = bb->index * func_param_count + i;
3803 fprintf (f, " %4" HOST_WIDE_INT_PRINT "d", table[idx]);
3806 fprintf (f, "\n");
3808 fprintf (dump_file, "\n");
3811 /* Determine what (parts of) parameters passed by reference that are not
3812 assigned to are not certainly dereferenced in this function and thus the
3813 dereferencing cannot be safely moved to the caller without potentially
3814 introducing a segfault. Mark such REPRESENTATIVES as
3815 grp_not_necessarilly_dereferenced.
3817 The dereferenced maximum "distance," i.e. the offset + size of the accessed
3818 part is calculated rather than simple booleans are calculated for each
3819 pointer parameter to handle cases when only a fraction of the whole
3820 aggregate is allocated (see testsuite/gcc.c-torture/execute/ipa-sra-2.c for
3821 an example).
3823 The maximum dereference distances for each pointer parameter and BB are
3824 already stored in bb_dereference. This routine simply propagates these
3825 values upwards by propagate_dereference_distances and then compares the
3826 distances of individual parameters in the ENTRY BB to the equivalent
3827 distances of each representative of a (fraction of a) parameter. */
3829 static void
3830 analyze_caller_dereference_legality (vec<access_p> representatives)
3832 int i;
3834 if (dump_file && (dump_flags & TDF_DETAILS))
3835 dump_dereferences_table (dump_file,
3836 "Dereference table before propagation:\n",
3837 bb_dereferences);
3839 propagate_dereference_distances ();
3841 if (dump_file && (dump_flags & TDF_DETAILS))
3842 dump_dereferences_table (dump_file,
3843 "Dereference table after propagation:\n",
3844 bb_dereferences);
3846 for (i = 0; i < func_param_count; i++)
3848 struct access *repr = representatives[i];
3849 int idx = ENTRY_BLOCK_PTR->index * func_param_count + i;
3851 if (!repr || no_accesses_p (repr))
3852 continue;
3856 if ((repr->offset + repr->size) > bb_dereferences[idx])
3857 repr->grp_not_necessarilly_dereferenced = 1;
3858 repr = repr->next_grp;
3860 while (repr);
3864 /* Return the representative access for the parameter declaration PARM if it is
3865 a scalar passed by reference which is not written to and the pointer value
3866 is not used directly. Thus, if it is legal to dereference it in the caller
3867 and we can rule out modifications through aliases, such parameter should be
3868 turned into one passed by value. Return NULL otherwise. */
3870 static struct access *
3871 unmodified_by_ref_scalar_representative (tree parm)
3873 int i, access_count;
3874 struct access *repr;
3875 vec<access_p> *access_vec;
3877 access_vec = get_base_access_vector (parm);
3878 gcc_assert (access_vec);
3879 repr = (*access_vec)[0];
3880 if (repr->write)
3881 return NULL;
3882 repr->group_representative = repr;
3884 access_count = access_vec->length ();
3885 for (i = 1; i < access_count; i++)
3887 struct access *access = (*access_vec)[i];
3888 if (access->write)
3889 return NULL;
3890 access->group_representative = repr;
3891 access->next_sibling = repr->next_sibling;
3892 repr->next_sibling = access;
3895 repr->grp_read = 1;
3896 repr->grp_scalar_ptr = 1;
3897 return repr;
3900 /* Return true iff this ACCESS precludes IPA-SRA of the parameter it is
3901 associated with. REQ_ALIGN is the minimum required alignment. */
3903 static bool
3904 access_precludes_ipa_sra_p (struct access *access, unsigned int req_align)
3906 unsigned int exp_align;
3907 /* Avoid issues such as the second simple testcase in PR 42025. The problem
3908 is incompatible assign in a call statement (and possibly even in asm
3909 statements). This can be relaxed by using a new temporary but only for
3910 non-TREE_ADDRESSABLE types and is probably not worth the complexity. (In
3911 intraprocedural SRA we deal with this by keeping the old aggregate around,
3912 something we cannot do in IPA-SRA.) */
3913 if (access->write
3914 && (is_gimple_call (access->stmt)
3915 || gimple_code (access->stmt) == GIMPLE_ASM))
3916 return true;
3918 exp_align = get_object_alignment (access->expr);
3919 if (exp_align < req_align)
3920 return true;
3922 return false;
3926 /* Sort collected accesses for parameter PARM, identify representatives for
3927 each accessed region and link them together. Return NULL if there are
3928 different but overlapping accesses, return the special ptr value meaning
3929 there are no accesses for this parameter if that is the case and return the
3930 first representative otherwise. Set *RO_GRP if there is a group of accesses
3931 with only read (i.e. no write) accesses. */
3933 static struct access *
3934 splice_param_accesses (tree parm, bool *ro_grp)
3936 int i, j, access_count, group_count;
3937 int agg_size, total_size = 0;
3938 struct access *access, *res, **prev_acc_ptr = &res;
3939 vec<access_p> *access_vec;
3941 access_vec = get_base_access_vector (parm);
3942 if (!access_vec)
3943 return &no_accesses_representant;
3944 access_count = access_vec->length ();
3946 access_vec->qsort (compare_access_positions);
3948 i = 0;
3949 total_size = 0;
3950 group_count = 0;
3951 while (i < access_count)
3953 bool modification;
3954 tree a1_alias_type;
3955 access = (*access_vec)[i];
3956 modification = access->write;
3957 if (access_precludes_ipa_sra_p (access, TYPE_ALIGN (access->type)))
3958 return NULL;
3959 a1_alias_type = reference_alias_ptr_type (access->expr);
3961 /* Access is about to become group representative unless we find some
3962 nasty overlap which would preclude us from breaking this parameter
3963 apart. */
3965 j = i + 1;
3966 while (j < access_count)
3968 struct access *ac2 = (*access_vec)[j];
3969 if (ac2->offset != access->offset)
3971 /* All or nothing law for parameters. */
3972 if (access->offset + access->size > ac2->offset)
3973 return NULL;
3974 else
3975 break;
3977 else if (ac2->size != access->size)
3978 return NULL;
3980 if (access_precludes_ipa_sra_p (ac2, TYPE_ALIGN (access->type))
3981 || (ac2->type != access->type
3982 && (TREE_ADDRESSABLE (ac2->type)
3983 || TREE_ADDRESSABLE (access->type)))
3984 || (reference_alias_ptr_type (ac2->expr) != a1_alias_type))
3985 return NULL;
3987 modification |= ac2->write;
3988 ac2->group_representative = access;
3989 ac2->next_sibling = access->next_sibling;
3990 access->next_sibling = ac2;
3991 j++;
3994 group_count++;
3995 access->grp_maybe_modified = modification;
3996 if (!modification)
3997 *ro_grp = true;
3998 *prev_acc_ptr = access;
3999 prev_acc_ptr = &access->next_grp;
4000 total_size += access->size;
4001 i = j;
4004 if (POINTER_TYPE_P (TREE_TYPE (parm)))
4005 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (TREE_TYPE (parm))), 1);
4006 else
4007 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (parm)), 1);
4008 if (total_size >= agg_size)
4009 return NULL;
4011 gcc_assert (group_count > 0);
4012 return res;
4015 /* Decide whether parameters with representative accesses given by REPR should
4016 be reduced into components. */
4018 static int
4019 decide_one_param_reduction (struct access *repr)
4021 int total_size, cur_parm_size, agg_size, new_param_count, parm_size_limit;
4022 bool by_ref;
4023 tree parm;
4025 parm = repr->base;
4026 cur_parm_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (parm)), 1);
4027 gcc_assert (cur_parm_size > 0);
4029 if (POINTER_TYPE_P (TREE_TYPE (parm)))
4031 by_ref = true;
4032 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (TREE_TYPE (parm))), 1);
4034 else
4036 by_ref = false;
4037 agg_size = cur_parm_size;
4040 if (dump_file)
4042 struct access *acc;
4043 fprintf (dump_file, "Evaluating PARAM group sizes for ");
4044 print_generic_expr (dump_file, parm, 0);
4045 fprintf (dump_file, " (UID: %u): \n", DECL_UID (parm));
4046 for (acc = repr; acc; acc = acc->next_grp)
4047 dump_access (dump_file, acc, true);
4050 total_size = 0;
4051 new_param_count = 0;
4053 for (; repr; repr = repr->next_grp)
4055 gcc_assert (parm == repr->base);
4057 /* Taking the address of a non-addressable field is verboten. */
4058 if (by_ref && repr->non_addressable)
4059 return 0;
4061 /* Do not decompose a non-BLKmode param in a way that would
4062 create BLKmode params. Especially for by-reference passing
4063 (thus, pointer-type param) this is hardly worthwhile. */
4064 if (DECL_MODE (parm) != BLKmode
4065 && TYPE_MODE (repr->type) == BLKmode)
4066 return 0;
4068 if (!by_ref || (!repr->grp_maybe_modified
4069 && !repr->grp_not_necessarilly_dereferenced))
4070 total_size += repr->size;
4071 else
4072 total_size += cur_parm_size;
4074 new_param_count++;
4077 gcc_assert (new_param_count > 0);
4079 if (optimize_function_for_size_p (cfun))
4080 parm_size_limit = cur_parm_size;
4081 else
4082 parm_size_limit = (PARAM_VALUE (PARAM_IPA_SRA_PTR_GROWTH_FACTOR)
4083 * cur_parm_size);
4085 if (total_size < agg_size
4086 && total_size <= parm_size_limit)
4088 if (dump_file)
4089 fprintf (dump_file, " ....will be split into %i components\n",
4090 new_param_count);
4091 return new_param_count;
4093 else
4094 return 0;
4097 /* The order of the following enums is important, we need to do extra work for
4098 UNUSED_PARAMS, BY_VAL_ACCESSES and UNMODIF_BY_REF_ACCESSES. */
4099 enum ipa_splicing_result { NO_GOOD_ACCESS, UNUSED_PARAMS, BY_VAL_ACCESSES,
4100 MODIF_BY_REF_ACCESSES, UNMODIF_BY_REF_ACCESSES };
4102 /* Identify representatives of all accesses to all candidate parameters for
4103 IPA-SRA. Return result based on what representatives have been found. */
4105 static enum ipa_splicing_result
4106 splice_all_param_accesses (vec<access_p> &representatives)
4108 enum ipa_splicing_result result = NO_GOOD_ACCESS;
4109 tree parm;
4110 struct access *repr;
4112 representatives.create (func_param_count);
4114 for (parm = DECL_ARGUMENTS (current_function_decl);
4115 parm;
4116 parm = DECL_CHAIN (parm))
4118 if (is_unused_scalar_param (parm))
4120 representatives.quick_push (&no_accesses_representant);
4121 if (result == NO_GOOD_ACCESS)
4122 result = UNUSED_PARAMS;
4124 else if (POINTER_TYPE_P (TREE_TYPE (parm))
4125 && is_gimple_reg_type (TREE_TYPE (TREE_TYPE (parm)))
4126 && bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
4128 repr = unmodified_by_ref_scalar_representative (parm);
4129 representatives.quick_push (repr);
4130 if (repr)
4131 result = UNMODIF_BY_REF_ACCESSES;
4133 else if (bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
4135 bool ro_grp = false;
4136 repr = splice_param_accesses (parm, &ro_grp);
4137 representatives.quick_push (repr);
4139 if (repr && !no_accesses_p (repr))
4141 if (POINTER_TYPE_P (TREE_TYPE (parm)))
4143 if (ro_grp)
4144 result = UNMODIF_BY_REF_ACCESSES;
4145 else if (result < MODIF_BY_REF_ACCESSES)
4146 result = MODIF_BY_REF_ACCESSES;
4148 else if (result < BY_VAL_ACCESSES)
4149 result = BY_VAL_ACCESSES;
4151 else if (no_accesses_p (repr) && (result == NO_GOOD_ACCESS))
4152 result = UNUSED_PARAMS;
4154 else
4155 representatives.quick_push (NULL);
4158 if (result == NO_GOOD_ACCESS)
4160 representatives.release ();
4161 return NO_GOOD_ACCESS;
4164 return result;
4167 /* Return the index of BASE in PARMS. Abort if it is not found. */
4169 static inline int
4170 get_param_index (tree base, vec<tree> parms)
4172 int i, len;
4174 len = parms.length ();
4175 for (i = 0; i < len; i++)
4176 if (parms[i] == base)
4177 return i;
4178 gcc_unreachable ();
4181 /* Convert the decisions made at the representative level into compact
4182 parameter adjustments. REPRESENTATIVES are pointers to first
4183 representatives of each param accesses, ADJUSTMENTS_COUNT is the expected
4184 final number of adjustments. */
4186 static ipa_parm_adjustment_vec
4187 turn_representatives_into_adjustments (vec<access_p> representatives,
4188 int adjustments_count)
4190 vec<tree> parms;
4191 ipa_parm_adjustment_vec adjustments;
4192 tree parm;
4193 int i;
4195 gcc_assert (adjustments_count > 0);
4196 parms = ipa_get_vector_of_formal_parms (current_function_decl);
4197 adjustments.create (adjustments_count);
4198 parm = DECL_ARGUMENTS (current_function_decl);
4199 for (i = 0; i < func_param_count; i++, parm = DECL_CHAIN (parm))
4201 struct access *repr = representatives[i];
4203 if (!repr || no_accesses_p (repr))
4205 struct ipa_parm_adjustment adj;
4207 memset (&adj, 0, sizeof (adj));
4208 adj.base_index = get_param_index (parm, parms);
4209 adj.base = parm;
4210 if (!repr)
4211 adj.copy_param = 1;
4212 else
4213 adj.remove_param = 1;
4214 adjustments.quick_push (adj);
4216 else
4218 struct ipa_parm_adjustment adj;
4219 int index = get_param_index (parm, parms);
4221 for (; repr; repr = repr->next_grp)
4223 memset (&adj, 0, sizeof (adj));
4224 gcc_assert (repr->base == parm);
4225 adj.base_index = index;
4226 adj.base = repr->base;
4227 adj.type = repr->type;
4228 adj.alias_ptr_type = reference_alias_ptr_type (repr->expr);
4229 adj.offset = repr->offset;
4230 adj.by_ref = (POINTER_TYPE_P (TREE_TYPE (repr->base))
4231 && (repr->grp_maybe_modified
4232 || repr->grp_not_necessarilly_dereferenced));
4233 adjustments.quick_push (adj);
4237 parms.release ();
4238 return adjustments;
4241 /* Analyze the collected accesses and produce a plan what to do with the
4242 parameters in the form of adjustments, NULL meaning nothing. */
4244 static ipa_parm_adjustment_vec
4245 analyze_all_param_acesses (void)
4247 enum ipa_splicing_result repr_state;
4248 bool proceed = false;
4249 int i, adjustments_count = 0;
4250 vec<access_p> representatives;
4251 ipa_parm_adjustment_vec adjustments;
4253 repr_state = splice_all_param_accesses (representatives);
4254 if (repr_state == NO_GOOD_ACCESS)
4255 return ipa_parm_adjustment_vec();
4257 /* If there are any parameters passed by reference which are not modified
4258 directly, we need to check whether they can be modified indirectly. */
4259 if (repr_state == UNMODIF_BY_REF_ACCESSES)
4261 analyze_caller_dereference_legality (representatives);
4262 analyze_modified_params (representatives);
4265 for (i = 0; i < func_param_count; i++)
4267 struct access *repr = representatives[i];
4269 if (repr && !no_accesses_p (repr))
4271 if (repr->grp_scalar_ptr)
4273 adjustments_count++;
4274 if (repr->grp_not_necessarilly_dereferenced
4275 || repr->grp_maybe_modified)
4276 representatives[i] = NULL;
4277 else
4279 proceed = true;
4280 sra_stats.scalar_by_ref_to_by_val++;
4283 else
4285 int new_components = decide_one_param_reduction (repr);
4287 if (new_components == 0)
4289 representatives[i] = NULL;
4290 adjustments_count++;
4292 else
4294 adjustments_count += new_components;
4295 sra_stats.aggregate_params_reduced++;
4296 sra_stats.param_reductions_created += new_components;
4297 proceed = true;
4301 else
4303 if (no_accesses_p (repr))
4305 proceed = true;
4306 sra_stats.deleted_unused_parameters++;
4308 adjustments_count++;
4312 if (!proceed && dump_file)
4313 fprintf (dump_file, "NOT proceeding to change params.\n");
4315 if (proceed)
4316 adjustments = turn_representatives_into_adjustments (representatives,
4317 adjustments_count);
4318 else
4319 adjustments = ipa_parm_adjustment_vec();
4321 representatives.release ();
4322 return adjustments;
4325 /* If a parameter replacement identified by ADJ does not yet exist in the form
4326 of declaration, create it and record it, otherwise return the previously
4327 created one. */
4329 static tree
4330 get_replaced_param_substitute (struct ipa_parm_adjustment *adj)
4332 tree repl;
4333 if (!adj->new_ssa_base)
4335 char *pretty_name = make_fancy_name (adj->base);
4337 repl = create_tmp_reg (TREE_TYPE (adj->base), "ISR");
4338 DECL_NAME (repl) = get_identifier (pretty_name);
4339 obstack_free (&name_obstack, pretty_name);
4341 adj->new_ssa_base = repl;
4343 else
4344 repl = adj->new_ssa_base;
4345 return repl;
4348 /* Find the first adjustment for a particular parameter BASE in a vector of
4349 ADJUSTMENTS which is not a copy_param. Return NULL if there is no such
4350 adjustment. */
4352 static struct ipa_parm_adjustment *
4353 get_adjustment_for_base (ipa_parm_adjustment_vec adjustments, tree base)
4355 int i, len;
4357 len = adjustments.length ();
4358 for (i = 0; i < len; i++)
4360 struct ipa_parm_adjustment *adj;
4362 adj = &adjustments[i];
4363 if (!adj->copy_param && adj->base == base)
4364 return adj;
4367 return NULL;
4370 /* If the statement STMT defines an SSA_NAME of a parameter which is to be
4371 removed because its value is not used, replace the SSA_NAME with a one
4372 relating to a created VAR_DECL together all of its uses and return true.
4373 ADJUSTMENTS is a pointer to an adjustments vector. */
4375 static bool
4376 replace_removed_params_ssa_names (gimple stmt,
4377 ipa_parm_adjustment_vec adjustments)
4379 struct ipa_parm_adjustment *adj;
4380 tree lhs, decl, repl, name;
4382 if (gimple_code (stmt) == GIMPLE_PHI)
4383 lhs = gimple_phi_result (stmt);
4384 else if (is_gimple_assign (stmt))
4385 lhs = gimple_assign_lhs (stmt);
4386 else if (is_gimple_call (stmt))
4387 lhs = gimple_call_lhs (stmt);
4388 else
4389 gcc_unreachable ();
4391 if (TREE_CODE (lhs) != SSA_NAME)
4392 return false;
4394 decl = SSA_NAME_VAR (lhs);
4395 if (decl == NULL_TREE
4396 || TREE_CODE (decl) != PARM_DECL)
4397 return false;
4399 adj = get_adjustment_for_base (adjustments, decl);
4400 if (!adj)
4401 return false;
4403 repl = get_replaced_param_substitute (adj);
4404 name = make_ssa_name (repl, stmt);
4406 if (dump_file)
4408 fprintf (dump_file, "replacing an SSA name of a removed param ");
4409 print_generic_expr (dump_file, lhs, 0);
4410 fprintf (dump_file, " with ");
4411 print_generic_expr (dump_file, name, 0);
4412 fprintf (dump_file, "\n");
4415 if (is_gimple_assign (stmt))
4416 gimple_assign_set_lhs (stmt, name);
4417 else if (is_gimple_call (stmt))
4418 gimple_call_set_lhs (stmt, name);
4419 else
4420 gimple_phi_set_result (stmt, name);
4422 replace_uses_by (lhs, name);
4423 release_ssa_name (lhs);
4424 return true;
4427 /* If the expression *EXPR should be replaced by a reduction of a parameter, do
4428 so. ADJUSTMENTS is a pointer to a vector of adjustments. CONVERT
4429 specifies whether the function should care about type incompatibility the
4430 current and new expressions. If it is false, the function will leave
4431 incompatibility issues to the caller. Return true iff the expression
4432 was modified. */
4434 static bool
4435 sra_ipa_modify_expr (tree *expr, bool convert,
4436 ipa_parm_adjustment_vec adjustments)
4438 int i, len;
4439 struct ipa_parm_adjustment *adj, *cand = NULL;
4440 HOST_WIDE_INT offset, size, max_size;
4441 tree base, src;
4443 len = adjustments.length ();
4445 if (TREE_CODE (*expr) == BIT_FIELD_REF
4446 || TREE_CODE (*expr) == IMAGPART_EXPR
4447 || TREE_CODE (*expr) == REALPART_EXPR)
4449 expr = &TREE_OPERAND (*expr, 0);
4450 convert = true;
4453 base = get_ref_base_and_extent (*expr, &offset, &size, &max_size);
4454 if (!base || size == -1 || max_size == -1)
4455 return false;
4457 if (TREE_CODE (base) == MEM_REF)
4459 offset += mem_ref_offset (base).low * BITS_PER_UNIT;
4460 base = TREE_OPERAND (base, 0);
4463 base = get_ssa_base_param (base);
4464 if (!base || TREE_CODE (base) != PARM_DECL)
4465 return false;
4467 for (i = 0; i < len; i++)
4469 adj = &adjustments[i];
4471 if (adj->base == base
4472 && (adj->offset == offset || adj->remove_param))
4474 cand = adj;
4475 break;
4478 if (!cand || cand->copy_param || cand->remove_param)
4479 return false;
4481 if (cand->by_ref)
4482 src = build_simple_mem_ref (cand->reduction);
4483 else
4484 src = cand->reduction;
4486 if (dump_file && (dump_flags & TDF_DETAILS))
4488 fprintf (dump_file, "About to replace expr ");
4489 print_generic_expr (dump_file, *expr, 0);
4490 fprintf (dump_file, " with ");
4491 print_generic_expr (dump_file, src, 0);
4492 fprintf (dump_file, "\n");
4495 if (convert && !useless_type_conversion_p (TREE_TYPE (*expr), cand->type))
4497 tree vce = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (*expr), src);
4498 *expr = vce;
4500 else
4501 *expr = src;
4502 return true;
4505 /* If the statement pointed to by STMT_PTR contains any expressions that need
4506 to replaced with a different one as noted by ADJUSTMENTS, do so. Handle any
4507 potential type incompatibilities (GSI is used to accommodate conversion
4508 statements and must point to the statement). Return true iff the statement
4509 was modified. */
4511 static bool
4512 sra_ipa_modify_assign (gimple *stmt_ptr, gimple_stmt_iterator *gsi,
4513 ipa_parm_adjustment_vec adjustments)
4515 gimple stmt = *stmt_ptr;
4516 tree *lhs_p, *rhs_p;
4517 bool any;
4519 if (!gimple_assign_single_p (stmt))
4520 return false;
4522 rhs_p = gimple_assign_rhs1_ptr (stmt);
4523 lhs_p = gimple_assign_lhs_ptr (stmt);
4525 any = sra_ipa_modify_expr (rhs_p, false, adjustments);
4526 any |= sra_ipa_modify_expr (lhs_p, false, adjustments);
4527 if (any)
4529 tree new_rhs = NULL_TREE;
4531 if (!useless_type_conversion_p (TREE_TYPE (*lhs_p), TREE_TYPE (*rhs_p)))
4533 if (TREE_CODE (*rhs_p) == CONSTRUCTOR)
4535 /* V_C_Es of constructors can cause trouble (PR 42714). */
4536 if (is_gimple_reg_type (TREE_TYPE (*lhs_p)))
4537 *rhs_p = build_zero_cst (TREE_TYPE (*lhs_p));
4538 else
4539 *rhs_p = build_constructor (TREE_TYPE (*lhs_p),
4540 NULL);
4542 else
4543 new_rhs = fold_build1_loc (gimple_location (stmt),
4544 VIEW_CONVERT_EXPR, TREE_TYPE (*lhs_p),
4545 *rhs_p);
4547 else if (REFERENCE_CLASS_P (*rhs_p)
4548 && is_gimple_reg_type (TREE_TYPE (*lhs_p))
4549 && !is_gimple_reg (*lhs_p))
4550 /* This can happen when an assignment in between two single field
4551 structures is turned into an assignment in between two pointers to
4552 scalars (PR 42237). */
4553 new_rhs = *rhs_p;
4555 if (new_rhs)
4557 tree tmp = force_gimple_operand_gsi (gsi, new_rhs, true, NULL_TREE,
4558 true, GSI_SAME_STMT);
4560 gimple_assign_set_rhs_from_tree (gsi, tmp);
4563 return true;
4566 return false;
4569 /* Traverse the function body and all modifications as described in
4570 ADJUSTMENTS. Return true iff the CFG has been changed. */
4572 static bool
4573 ipa_sra_modify_function_body (ipa_parm_adjustment_vec adjustments)
4575 bool cfg_changed = false;
4576 basic_block bb;
4578 FOR_EACH_BB (bb)
4580 gimple_stmt_iterator gsi;
4582 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4583 replace_removed_params_ssa_names (gsi_stmt (gsi), adjustments);
4585 gsi = gsi_start_bb (bb);
4586 while (!gsi_end_p (gsi))
4588 gimple stmt = gsi_stmt (gsi);
4589 bool modified = false;
4590 tree *t;
4591 unsigned i;
4593 switch (gimple_code (stmt))
4595 case GIMPLE_RETURN:
4596 t = gimple_return_retval_ptr (stmt);
4597 if (*t != NULL_TREE)
4598 modified |= sra_ipa_modify_expr (t, true, adjustments);
4599 break;
4601 case GIMPLE_ASSIGN:
4602 modified |= sra_ipa_modify_assign (&stmt, &gsi, adjustments);
4603 modified |= replace_removed_params_ssa_names (stmt, adjustments);
4604 break;
4606 case GIMPLE_CALL:
4607 /* Operands must be processed before the lhs. */
4608 for (i = 0; i < gimple_call_num_args (stmt); i++)
4610 t = gimple_call_arg_ptr (stmt, i);
4611 modified |= sra_ipa_modify_expr (t, true, adjustments);
4614 if (gimple_call_lhs (stmt))
4616 t = gimple_call_lhs_ptr (stmt);
4617 modified |= sra_ipa_modify_expr (t, false, adjustments);
4618 modified |= replace_removed_params_ssa_names (stmt,
4619 adjustments);
4621 break;
4623 case GIMPLE_ASM:
4624 for (i = 0; i < gimple_asm_ninputs (stmt); i++)
4626 t = &TREE_VALUE (gimple_asm_input_op (stmt, i));
4627 modified |= sra_ipa_modify_expr (t, true, adjustments);
4629 for (i = 0; i < gimple_asm_noutputs (stmt); i++)
4631 t = &TREE_VALUE (gimple_asm_output_op (stmt, i));
4632 modified |= sra_ipa_modify_expr (t, false, adjustments);
4634 break;
4636 default:
4637 break;
4640 if (modified)
4642 update_stmt (stmt);
4643 if (maybe_clean_eh_stmt (stmt)
4644 && gimple_purge_dead_eh_edges (gimple_bb (stmt)))
4645 cfg_changed = true;
4647 gsi_next (&gsi);
4651 return cfg_changed;
4654 /* Call gimple_debug_bind_reset_value on all debug statements describing
4655 gimple register parameters that are being removed or replaced. */
4657 static void
4658 sra_ipa_reset_debug_stmts (ipa_parm_adjustment_vec adjustments)
4660 int i, len;
4661 gimple_stmt_iterator *gsip = NULL, gsi;
4663 if (MAY_HAVE_DEBUG_STMTS && single_succ_p (ENTRY_BLOCK_PTR))
4665 gsi = gsi_after_labels (single_succ (ENTRY_BLOCK_PTR));
4666 gsip = &gsi;
4668 len = adjustments.length ();
4669 for (i = 0; i < len; i++)
4671 struct ipa_parm_adjustment *adj;
4672 imm_use_iterator ui;
4673 gimple stmt, def_temp;
4674 tree name, vexpr, copy = NULL_TREE;
4675 use_operand_p use_p;
4677 adj = &adjustments[i];
4678 if (adj->copy_param || !is_gimple_reg (adj->base))
4679 continue;
4680 name = ssa_default_def (cfun, adj->base);
4681 vexpr = NULL;
4682 if (name)
4683 FOR_EACH_IMM_USE_STMT (stmt, ui, name)
4685 if (gimple_clobber_p (stmt))
4687 gimple_stmt_iterator cgsi = gsi_for_stmt (stmt);
4688 unlink_stmt_vdef (stmt);
4689 gsi_remove (&cgsi, true);
4690 release_defs (stmt);
4691 continue;
4693 /* All other users must have been removed by
4694 ipa_sra_modify_function_body. */
4695 gcc_assert (is_gimple_debug (stmt));
4696 if (vexpr == NULL && gsip != NULL)
4698 gcc_assert (TREE_CODE (adj->base) == PARM_DECL);
4699 vexpr = make_node (DEBUG_EXPR_DECL);
4700 def_temp = gimple_build_debug_source_bind (vexpr, adj->base,
4701 NULL);
4702 DECL_ARTIFICIAL (vexpr) = 1;
4703 TREE_TYPE (vexpr) = TREE_TYPE (name);
4704 DECL_MODE (vexpr) = DECL_MODE (adj->base);
4705 gsi_insert_before (gsip, def_temp, GSI_SAME_STMT);
4707 if (vexpr)
4709 FOR_EACH_IMM_USE_ON_STMT (use_p, ui)
4710 SET_USE (use_p, vexpr);
4712 else
4713 gimple_debug_bind_reset_value (stmt);
4714 update_stmt (stmt);
4716 /* Create a VAR_DECL for debug info purposes. */
4717 if (!DECL_IGNORED_P (adj->base))
4719 copy = build_decl (DECL_SOURCE_LOCATION (current_function_decl),
4720 VAR_DECL, DECL_NAME (adj->base),
4721 TREE_TYPE (adj->base));
4722 if (DECL_PT_UID_SET_P (adj->base))
4723 SET_DECL_PT_UID (copy, DECL_PT_UID (adj->base));
4724 TREE_ADDRESSABLE (copy) = TREE_ADDRESSABLE (adj->base);
4725 TREE_READONLY (copy) = TREE_READONLY (adj->base);
4726 TREE_THIS_VOLATILE (copy) = TREE_THIS_VOLATILE (adj->base);
4727 DECL_GIMPLE_REG_P (copy) = DECL_GIMPLE_REG_P (adj->base);
4728 DECL_ARTIFICIAL (copy) = DECL_ARTIFICIAL (adj->base);
4729 DECL_IGNORED_P (copy) = DECL_IGNORED_P (adj->base);
4730 DECL_ABSTRACT_ORIGIN (copy) = DECL_ORIGIN (adj->base);
4731 DECL_SEEN_IN_BIND_EXPR_P (copy) = 1;
4732 SET_DECL_RTL (copy, 0);
4733 TREE_USED (copy) = 1;
4734 DECL_CONTEXT (copy) = current_function_decl;
4735 add_local_decl (cfun, copy);
4736 DECL_CHAIN (copy) =
4737 BLOCK_VARS (DECL_INITIAL (current_function_decl));
4738 BLOCK_VARS (DECL_INITIAL (current_function_decl)) = copy;
4740 if (gsip != NULL && copy && target_for_debug_bind (adj->base))
4742 gcc_assert (TREE_CODE (adj->base) == PARM_DECL);
4743 if (vexpr)
4744 def_temp = gimple_build_debug_bind (copy, vexpr, NULL);
4745 else
4746 def_temp = gimple_build_debug_source_bind (copy, adj->base,
4747 NULL);
4748 gsi_insert_before (gsip, def_temp, GSI_SAME_STMT);
4753 /* Return false iff all callers have at least as many actual arguments as there
4754 are formal parameters in the current function. */
4756 static bool
4757 not_all_callers_have_enough_arguments_p (struct cgraph_node *node,
4758 void *data ATTRIBUTE_UNUSED)
4760 struct cgraph_edge *cs;
4761 for (cs = node->callers; cs; cs = cs->next_caller)
4762 if (!callsite_has_enough_arguments_p (cs->call_stmt))
4763 return true;
4765 return false;
4768 /* Convert all callers of NODE. */
4770 static bool
4771 convert_callers_for_node (struct cgraph_node *node,
4772 void *data)
4774 ipa_parm_adjustment_vec *adjustments = (ipa_parm_adjustment_vec *) data;
4775 bitmap recomputed_callers = BITMAP_ALLOC (NULL);
4776 struct cgraph_edge *cs;
4778 for (cs = node->callers; cs; cs = cs->next_caller)
4780 push_cfun (DECL_STRUCT_FUNCTION (cs->caller->symbol.decl));
4782 if (dump_file)
4783 fprintf (dump_file, "Adjusting call %s/%i -> %s/%i\n",
4784 xstrdup (cgraph_node_name (cs->caller)),
4785 cs->caller->symbol.order,
4786 xstrdup (cgraph_node_name (cs->callee)),
4787 cs->callee->symbol.order);
4789 ipa_modify_call_arguments (cs, cs->call_stmt, *adjustments);
4791 pop_cfun ();
4794 for (cs = node->callers; cs; cs = cs->next_caller)
4795 if (bitmap_set_bit (recomputed_callers, cs->caller->uid)
4796 && gimple_in_ssa_p (DECL_STRUCT_FUNCTION (cs->caller->symbol.decl)))
4797 compute_inline_parameters (cs->caller, true);
4798 BITMAP_FREE (recomputed_callers);
4800 return true;
4803 /* Convert all callers of NODE to pass parameters as given in ADJUSTMENTS. */
4805 static void
4806 convert_callers (struct cgraph_node *node, tree old_decl,
4807 ipa_parm_adjustment_vec adjustments)
4809 basic_block this_block;
4811 cgraph_for_node_and_aliases (node, convert_callers_for_node,
4812 &adjustments, false);
4814 if (!encountered_recursive_call)
4815 return;
4817 FOR_EACH_BB (this_block)
4819 gimple_stmt_iterator gsi;
4821 for (gsi = gsi_start_bb (this_block); !gsi_end_p (gsi); gsi_next (&gsi))
4823 gimple stmt = gsi_stmt (gsi);
4824 tree call_fndecl;
4825 if (gimple_code (stmt) != GIMPLE_CALL)
4826 continue;
4827 call_fndecl = gimple_call_fndecl (stmt);
4828 if (call_fndecl == old_decl)
4830 if (dump_file)
4831 fprintf (dump_file, "Adjusting recursive call");
4832 gimple_call_set_fndecl (stmt, node->symbol.decl);
4833 ipa_modify_call_arguments (NULL, stmt, adjustments);
4838 return;
4841 /* Perform all the modification required in IPA-SRA for NODE to have parameters
4842 as given in ADJUSTMENTS. Return true iff the CFG has been changed. */
4844 static bool
4845 modify_function (struct cgraph_node *node, ipa_parm_adjustment_vec adjustments)
4847 struct cgraph_node *new_node;
4848 bool cfg_changed;
4849 vec<cgraph_edge_p> redirect_callers = collect_callers_of_node (node);
4851 rebuild_cgraph_edges ();
4852 free_dominance_info (CDI_DOMINATORS);
4853 pop_cfun ();
4855 new_node = cgraph_function_versioning (node, redirect_callers,
4856 NULL,
4857 NULL, false, NULL, NULL, "isra");
4858 redirect_callers.release ();
4860 push_cfun (DECL_STRUCT_FUNCTION (new_node->symbol.decl));
4861 ipa_modify_formal_parameters (current_function_decl, adjustments, "ISRA");
4862 cfg_changed = ipa_sra_modify_function_body (adjustments);
4863 sra_ipa_reset_debug_stmts (adjustments);
4864 convert_callers (new_node, node->symbol.decl, adjustments);
4865 cgraph_make_node_local (new_node);
4866 return cfg_changed;
4869 /* Return false the function is apparently unsuitable for IPA-SRA based on it's
4870 attributes, return true otherwise. NODE is the cgraph node of the current
4871 function. */
4873 static bool
4874 ipa_sra_preliminary_function_checks (struct cgraph_node *node)
4876 if (!cgraph_node_can_be_local_p (node))
4878 if (dump_file)
4879 fprintf (dump_file, "Function not local to this compilation unit.\n");
4880 return false;
4883 if (!node->local.can_change_signature)
4885 if (dump_file)
4886 fprintf (dump_file, "Function can not change signature.\n");
4887 return false;
4890 if (!tree_versionable_function_p (node->symbol.decl))
4892 if (dump_file)
4893 fprintf (dump_file, "Function is not versionable.\n");
4894 return false;
4897 if (DECL_VIRTUAL_P (current_function_decl))
4899 if (dump_file)
4900 fprintf (dump_file, "Function is a virtual method.\n");
4901 return false;
4904 if ((DECL_COMDAT (node->symbol.decl) || DECL_EXTERNAL (node->symbol.decl))
4905 && inline_summary(node)->size >= MAX_INLINE_INSNS_AUTO)
4907 if (dump_file)
4908 fprintf (dump_file, "Function too big to be made truly local.\n");
4909 return false;
4912 if (!node->callers)
4914 if (dump_file)
4915 fprintf (dump_file,
4916 "Function has no callers in this compilation unit.\n");
4917 return false;
4920 if (cfun->stdarg)
4922 if (dump_file)
4923 fprintf (dump_file, "Function uses stdarg. \n");
4924 return false;
4927 if (TYPE_ATTRIBUTES (TREE_TYPE (node->symbol.decl)))
4928 return false;
4930 return true;
4933 /* Perform early interprocedural SRA. */
4935 static unsigned int
4936 ipa_early_sra (void)
4938 struct cgraph_node *node = cgraph_get_node (current_function_decl);
4939 ipa_parm_adjustment_vec adjustments;
4940 int ret = 0;
4942 if (!ipa_sra_preliminary_function_checks (node))
4943 return 0;
4945 sra_initialize ();
4946 sra_mode = SRA_MODE_EARLY_IPA;
4948 if (!find_param_candidates ())
4950 if (dump_file)
4951 fprintf (dump_file, "Function has no IPA-SRA candidates.\n");
4952 goto simple_out;
4955 if (cgraph_for_node_and_aliases (node, not_all_callers_have_enough_arguments_p,
4956 NULL, true))
4958 if (dump_file)
4959 fprintf (dump_file, "There are callers with insufficient number of "
4960 "arguments.\n");
4961 goto simple_out;
4964 bb_dereferences = XCNEWVEC (HOST_WIDE_INT,
4965 func_param_count
4966 * last_basic_block_for_function (cfun));
4967 final_bbs = BITMAP_ALLOC (NULL);
4969 scan_function ();
4970 if (encountered_apply_args)
4972 if (dump_file)
4973 fprintf (dump_file, "Function calls __builtin_apply_args().\n");
4974 goto out;
4977 if (encountered_unchangable_recursive_call)
4979 if (dump_file)
4980 fprintf (dump_file, "Function calls itself with insufficient "
4981 "number of arguments.\n");
4982 goto out;
4985 adjustments = analyze_all_param_acesses ();
4986 if (!adjustments.exists ())
4987 goto out;
4988 if (dump_file)
4989 ipa_dump_param_adjustments (dump_file, adjustments, current_function_decl);
4991 if (modify_function (node, adjustments))
4992 ret = TODO_update_ssa | TODO_cleanup_cfg;
4993 else
4994 ret = TODO_update_ssa;
4995 adjustments.release ();
4997 statistics_counter_event (cfun, "Unused parameters deleted",
4998 sra_stats.deleted_unused_parameters);
4999 statistics_counter_event (cfun, "Scalar parameters converted to by-value",
5000 sra_stats.scalar_by_ref_to_by_val);
5001 statistics_counter_event (cfun, "Aggregate parameters broken up",
5002 sra_stats.aggregate_params_reduced);
5003 statistics_counter_event (cfun, "Aggregate parameter components created",
5004 sra_stats.param_reductions_created);
5006 out:
5007 BITMAP_FREE (final_bbs);
5008 free (bb_dereferences);
5009 simple_out:
5010 sra_deinitialize ();
5011 return ret;
5014 /* Return if early ipa sra shall be performed. */
5015 static bool
5016 ipa_early_sra_gate (void)
5018 return flag_ipa_sra && dbg_cnt (eipa_sra);
5021 struct gimple_opt_pass pass_early_ipa_sra =
5024 GIMPLE_PASS,
5025 "eipa_sra", /* name */
5026 OPTGROUP_NONE, /* optinfo_flags */
5027 ipa_early_sra_gate, /* gate */
5028 ipa_early_sra, /* execute */
5029 NULL, /* sub */
5030 NULL, /* next */
5031 0, /* static_pass_number */
5032 TV_IPA_SRA, /* tv_id */
5033 0, /* properties_required */
5034 0, /* properties_provided */
5035 0, /* properties_destroyed */
5036 0, /* todo_flags_start */
5037 TODO_dump_symtab /* todo_flags_finish */