[AArch64] Rewrite vca<ge, gt, le, lt> Neon patterns in C.
[official-gcc.git] / gcc / tree-sra.c
blob23a4f142783519ef6639e4db7b2baf0580e51192
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 a COMPONENT_REF with a bit-field field declaration
3002 somewhere in it. */
3004 static inline bool
3005 contains_bitfld_comp_ref_p (const_tree ref)
3007 while (handled_component_p (ref))
3009 if (TREE_CODE (ref) == COMPONENT_REF
3010 && DECL_BIT_FIELD (TREE_OPERAND (ref, 1)))
3011 return true;
3012 ref = TREE_OPERAND (ref, 0);
3015 return false;
3018 /* Return true if REF has an VIEW_CONVERT_EXPR or a COMPONENT_REF with a
3019 bit-field field declaration somewhere in it. */
3021 static inline bool
3022 contains_vce_or_bfcref_p (const_tree ref)
3024 while (handled_component_p (ref))
3026 if (TREE_CODE (ref) == VIEW_CONVERT_EXPR
3027 || (TREE_CODE (ref) == COMPONENT_REF
3028 && DECL_BIT_FIELD (TREE_OPERAND (ref, 1))))
3029 return true;
3030 ref = TREE_OPERAND (ref, 0);
3033 return false;
3036 /* Examine both sides of the assignment statement pointed to by STMT, replace
3037 them with a scalare replacement if there is one and generate copying of
3038 replacements if scalarized aggregates have been used in the assignment. GSI
3039 is used to hold generated statements for type conversions and subtree
3040 copying. */
3042 static enum assignment_mod_result
3043 sra_modify_assign (gimple *stmt, gimple_stmt_iterator *gsi)
3045 struct access *lacc, *racc;
3046 tree lhs, rhs;
3047 bool modify_this_stmt = false;
3048 bool force_gimple_rhs = false;
3049 location_t loc;
3050 gimple_stmt_iterator orig_gsi = *gsi;
3052 if (!gimple_assign_single_p (*stmt))
3053 return SRA_AM_NONE;
3054 lhs = gimple_assign_lhs (*stmt);
3055 rhs = gimple_assign_rhs1 (*stmt);
3057 if (TREE_CODE (rhs) == CONSTRUCTOR)
3058 return sra_modify_constructor_assign (stmt, gsi);
3060 if (TREE_CODE (rhs) == REALPART_EXPR || TREE_CODE (lhs) == REALPART_EXPR
3061 || TREE_CODE (rhs) == IMAGPART_EXPR || TREE_CODE (lhs) == IMAGPART_EXPR
3062 || TREE_CODE (rhs) == BIT_FIELD_REF || TREE_CODE (lhs) == BIT_FIELD_REF)
3064 modify_this_stmt = sra_modify_expr (gimple_assign_rhs1_ptr (*stmt),
3065 gsi, false);
3066 modify_this_stmt |= sra_modify_expr (gimple_assign_lhs_ptr (*stmt),
3067 gsi, true);
3068 return modify_this_stmt ? SRA_AM_MODIFIED : SRA_AM_NONE;
3071 lacc = get_access_for_expr (lhs);
3072 racc = get_access_for_expr (rhs);
3073 if (!lacc && !racc)
3074 return SRA_AM_NONE;
3076 loc = gimple_location (*stmt);
3077 if (lacc && lacc->grp_to_be_replaced)
3079 lhs = get_access_replacement (lacc);
3080 gimple_assign_set_lhs (*stmt, lhs);
3081 modify_this_stmt = true;
3082 if (lacc->grp_partial_lhs)
3083 force_gimple_rhs = true;
3084 sra_stats.exprs++;
3087 if (racc && racc->grp_to_be_replaced)
3089 rhs = get_access_replacement (racc);
3090 modify_this_stmt = true;
3091 if (racc->grp_partial_lhs)
3092 force_gimple_rhs = true;
3093 sra_stats.exprs++;
3095 else if (racc
3096 && !racc->grp_unscalarized_data
3097 && TREE_CODE (lhs) == SSA_NAME
3098 && !access_has_replacements_p (racc))
3100 rhs = get_repl_default_def_ssa_name (racc);
3101 modify_this_stmt = true;
3102 sra_stats.exprs++;
3105 if (modify_this_stmt)
3107 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (rhs)))
3109 /* If we can avoid creating a VIEW_CONVERT_EXPR do so.
3110 ??? This should move to fold_stmt which we simply should
3111 call after building a VIEW_CONVERT_EXPR here. */
3112 if (AGGREGATE_TYPE_P (TREE_TYPE (lhs))
3113 && !contains_bitfld_comp_ref_p (lhs))
3115 lhs = build_ref_for_model (loc, lhs, 0, racc, gsi, false);
3116 gimple_assign_set_lhs (*stmt, lhs);
3118 else if (AGGREGATE_TYPE_P (TREE_TYPE (rhs))
3119 && !contains_vce_or_bfcref_p (rhs))
3120 rhs = build_ref_for_model (loc, rhs, 0, lacc, gsi, false);
3122 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (rhs)))
3124 rhs = fold_build1_loc (loc, VIEW_CONVERT_EXPR, TREE_TYPE (lhs),
3125 rhs);
3126 if (is_gimple_reg_type (TREE_TYPE (lhs))
3127 && TREE_CODE (lhs) != SSA_NAME)
3128 force_gimple_rhs = true;
3133 if (lacc && lacc->grp_to_be_debug_replaced)
3135 tree dlhs = get_access_replacement (lacc);
3136 tree drhs = unshare_expr (rhs);
3137 if (!useless_type_conversion_p (TREE_TYPE (dlhs), TREE_TYPE (drhs)))
3139 if (AGGREGATE_TYPE_P (TREE_TYPE (drhs))
3140 && !contains_vce_or_bfcref_p (drhs))
3141 drhs = build_debug_ref_for_model (loc, drhs, 0, lacc);
3142 if (drhs
3143 && !useless_type_conversion_p (TREE_TYPE (dlhs),
3144 TREE_TYPE (drhs)))
3145 drhs = fold_build1_loc (loc, VIEW_CONVERT_EXPR,
3146 TREE_TYPE (dlhs), drhs);
3148 gimple ds = gimple_build_debug_bind (dlhs, drhs, *stmt);
3149 gsi_insert_before (gsi, ds, GSI_SAME_STMT);
3152 /* From this point on, the function deals with assignments in between
3153 aggregates when at least one has scalar reductions of some of its
3154 components. There are three possible scenarios: Both the LHS and RHS have
3155 to-be-scalarized components, 2) only the RHS has or 3) only the LHS has.
3157 In the first case, we would like to load the LHS components from RHS
3158 components whenever possible. If that is not possible, we would like to
3159 read it directly from the RHS (after updating it by storing in it its own
3160 components). If there are some necessary unscalarized data in the LHS,
3161 those will be loaded by the original assignment too. If neither of these
3162 cases happen, the original statement can be removed. Most of this is done
3163 by load_assign_lhs_subreplacements.
3165 In the second case, we would like to store all RHS scalarized components
3166 directly into LHS and if they cover the aggregate completely, remove the
3167 statement too. In the third case, we want the LHS components to be loaded
3168 directly from the RHS (DSE will remove the original statement if it
3169 becomes redundant).
3171 This is a bit complex but manageable when types match and when unions do
3172 not cause confusion in a way that we cannot really load a component of LHS
3173 from the RHS or vice versa (the access representing this level can have
3174 subaccesses that are accessible only through a different union field at a
3175 higher level - different from the one used in the examined expression).
3176 Unions are fun.
3178 Therefore, I specially handle a fourth case, happening when there is a
3179 specific type cast or it is impossible to locate a scalarized subaccess on
3180 the other side of the expression. If that happens, I simply "refresh" the
3181 RHS by storing in it is scalarized components leave the original statement
3182 there to do the copying and then load the scalar replacements of the LHS.
3183 This is what the first branch does. */
3185 if (modify_this_stmt
3186 || gimple_has_volatile_ops (*stmt)
3187 || contains_vce_or_bfcref_p (rhs)
3188 || contains_vce_or_bfcref_p (lhs))
3190 if (access_has_children_p (racc))
3191 generate_subtree_copies (racc->first_child, racc->base, 0, 0, 0,
3192 gsi, false, false, loc);
3193 if (access_has_children_p (lacc))
3194 generate_subtree_copies (lacc->first_child, lacc->base, 0, 0, 0,
3195 gsi, true, true, loc);
3196 sra_stats.separate_lhs_rhs_handling++;
3198 /* This gimplification must be done after generate_subtree_copies,
3199 lest we insert the subtree copies in the middle of the gimplified
3200 sequence. */
3201 if (force_gimple_rhs)
3202 rhs = force_gimple_operand_gsi (&orig_gsi, rhs, true, NULL_TREE,
3203 true, GSI_SAME_STMT);
3204 if (gimple_assign_rhs1 (*stmt) != rhs)
3206 modify_this_stmt = true;
3207 gimple_assign_set_rhs_from_tree (&orig_gsi, rhs);
3208 gcc_assert (*stmt == gsi_stmt (orig_gsi));
3211 return modify_this_stmt ? SRA_AM_MODIFIED : SRA_AM_NONE;
3213 else
3215 if (access_has_children_p (lacc)
3216 && access_has_children_p (racc)
3217 /* When an access represents an unscalarizable region, it usually
3218 represents accesses with variable offset and thus must not be used
3219 to generate new memory accesses. */
3220 && !lacc->grp_unscalarizable_region
3221 && !racc->grp_unscalarizable_region)
3223 gimple_stmt_iterator orig_gsi = *gsi;
3224 enum unscalarized_data_handling refreshed;
3226 if (lacc->grp_read && !lacc->grp_covered)
3227 refreshed = handle_unscalarized_data_in_subtree (racc, gsi);
3228 else
3229 refreshed = SRA_UDH_NONE;
3231 load_assign_lhs_subreplacements (lacc, racc, lacc->offset,
3232 &orig_gsi, gsi, &refreshed);
3233 if (refreshed != SRA_UDH_RIGHT)
3235 gsi_next (gsi);
3236 unlink_stmt_vdef (*stmt);
3237 gsi_remove (&orig_gsi, true);
3238 release_defs (*stmt);
3239 sra_stats.deleted++;
3240 return SRA_AM_REMOVED;
3243 else
3245 if (access_has_children_p (racc)
3246 && !racc->grp_unscalarized_data)
3248 if (dump_file)
3250 fprintf (dump_file, "Removing load: ");
3251 print_gimple_stmt (dump_file, *stmt, 0, 0);
3253 generate_subtree_copies (racc->first_child, lhs,
3254 racc->offset, 0, 0, gsi,
3255 false, false, loc);
3256 gcc_assert (*stmt == gsi_stmt (*gsi));
3257 unlink_stmt_vdef (*stmt);
3258 gsi_remove (gsi, true);
3259 release_defs (*stmt);
3260 sra_stats.deleted++;
3261 return SRA_AM_REMOVED;
3263 /* Restore the aggregate RHS from its components so the
3264 prevailing aggregate copy does the right thing. */
3265 if (access_has_children_p (racc))
3266 generate_subtree_copies (racc->first_child, racc->base, 0, 0, 0,
3267 gsi, false, false, loc);
3268 /* Re-load the components of the aggregate copy destination.
3269 But use the RHS aggregate to load from to expose more
3270 optimization opportunities. */
3271 if (access_has_children_p (lacc))
3272 generate_subtree_copies (lacc->first_child, rhs, lacc->offset,
3273 0, 0, gsi, true, true, loc);
3276 return SRA_AM_NONE;
3280 /* Traverse the function body and all modifications as decided in
3281 analyze_all_variable_accesses. Return true iff the CFG has been
3282 changed. */
3284 static bool
3285 sra_modify_function_body (void)
3287 bool cfg_changed = false;
3288 basic_block bb;
3290 FOR_EACH_BB (bb)
3292 gimple_stmt_iterator gsi = gsi_start_bb (bb);
3293 while (!gsi_end_p (gsi))
3295 gimple stmt = gsi_stmt (gsi);
3296 enum assignment_mod_result assign_result;
3297 bool modified = false, deleted = false;
3298 tree *t;
3299 unsigned i;
3301 switch (gimple_code (stmt))
3303 case GIMPLE_RETURN:
3304 t = gimple_return_retval_ptr (stmt);
3305 if (*t != NULL_TREE)
3306 modified |= sra_modify_expr (t, &gsi, false);
3307 break;
3309 case GIMPLE_ASSIGN:
3310 assign_result = sra_modify_assign (&stmt, &gsi);
3311 modified |= assign_result == SRA_AM_MODIFIED;
3312 deleted = assign_result == SRA_AM_REMOVED;
3313 break;
3315 case GIMPLE_CALL:
3316 /* Operands must be processed before the lhs. */
3317 for (i = 0; i < gimple_call_num_args (stmt); i++)
3319 t = gimple_call_arg_ptr (stmt, i);
3320 modified |= sra_modify_expr (t, &gsi, false);
3323 if (gimple_call_lhs (stmt))
3325 t = gimple_call_lhs_ptr (stmt);
3326 modified |= sra_modify_expr (t, &gsi, true);
3328 break;
3330 case GIMPLE_ASM:
3331 for (i = 0; i < gimple_asm_ninputs (stmt); i++)
3333 t = &TREE_VALUE (gimple_asm_input_op (stmt, i));
3334 modified |= sra_modify_expr (t, &gsi, false);
3336 for (i = 0; i < gimple_asm_noutputs (stmt); i++)
3338 t = &TREE_VALUE (gimple_asm_output_op (stmt, i));
3339 modified |= sra_modify_expr (t, &gsi, true);
3341 break;
3343 default:
3344 break;
3347 if (modified)
3349 update_stmt (stmt);
3350 if (maybe_clean_eh_stmt (stmt)
3351 && gimple_purge_dead_eh_edges (gimple_bb (stmt)))
3352 cfg_changed = true;
3354 if (!deleted)
3355 gsi_next (&gsi);
3359 return cfg_changed;
3362 /* Generate statements initializing scalar replacements of parts of function
3363 parameters. */
3365 static void
3366 initialize_parameter_reductions (void)
3368 gimple_stmt_iterator gsi;
3369 gimple_seq seq = NULL;
3370 tree parm;
3372 gsi = gsi_start (seq);
3373 for (parm = DECL_ARGUMENTS (current_function_decl);
3374 parm;
3375 parm = DECL_CHAIN (parm))
3377 vec<access_p> *access_vec;
3378 struct access *access;
3380 if (!bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
3381 continue;
3382 access_vec = get_base_access_vector (parm);
3383 if (!access_vec)
3384 continue;
3386 for (access = (*access_vec)[0];
3387 access;
3388 access = access->next_grp)
3389 generate_subtree_copies (access, parm, 0, 0, 0, &gsi, true, true,
3390 EXPR_LOCATION (parm));
3393 seq = gsi_seq (gsi);
3394 if (seq)
3395 gsi_insert_seq_on_edge_immediate (single_succ_edge (ENTRY_BLOCK_PTR), seq);
3398 /* The "main" function of intraprocedural SRA passes. Runs the analysis and if
3399 it reveals there are components of some aggregates to be scalarized, it runs
3400 the required transformations. */
3401 static unsigned int
3402 perform_intra_sra (void)
3404 int ret = 0;
3405 sra_initialize ();
3407 if (!find_var_candidates ())
3408 goto out;
3410 if (!scan_function ())
3411 goto out;
3413 if (!analyze_all_variable_accesses ())
3414 goto out;
3416 if (sra_modify_function_body ())
3417 ret = TODO_update_ssa | TODO_cleanup_cfg;
3418 else
3419 ret = TODO_update_ssa;
3420 initialize_parameter_reductions ();
3422 statistics_counter_event (cfun, "Scalar replacements created",
3423 sra_stats.replacements);
3424 statistics_counter_event (cfun, "Modified expressions", sra_stats.exprs);
3425 statistics_counter_event (cfun, "Subtree copy stmts",
3426 sra_stats.subtree_copies);
3427 statistics_counter_event (cfun, "Subreplacement stmts",
3428 sra_stats.subreplacements);
3429 statistics_counter_event (cfun, "Deleted stmts", sra_stats.deleted);
3430 statistics_counter_event (cfun, "Separate LHS and RHS handling",
3431 sra_stats.separate_lhs_rhs_handling);
3433 out:
3434 sra_deinitialize ();
3435 return ret;
3438 /* Perform early intraprocedural SRA. */
3439 static unsigned int
3440 early_intra_sra (void)
3442 sra_mode = SRA_MODE_EARLY_INTRA;
3443 return perform_intra_sra ();
3446 /* Perform "late" intraprocedural SRA. */
3447 static unsigned int
3448 late_intra_sra (void)
3450 sra_mode = SRA_MODE_INTRA;
3451 return perform_intra_sra ();
3455 static bool
3456 gate_intra_sra (void)
3458 return flag_tree_sra != 0 && dbg_cnt (tree_sra);
3462 struct gimple_opt_pass pass_sra_early =
3465 GIMPLE_PASS,
3466 "esra", /* name */
3467 OPTGROUP_NONE, /* optinfo_flags */
3468 gate_intra_sra, /* gate */
3469 early_intra_sra, /* execute */
3470 NULL, /* sub */
3471 NULL, /* next */
3472 0, /* static_pass_number */
3473 TV_TREE_SRA, /* tv_id */
3474 PROP_cfg | PROP_ssa, /* properties_required */
3475 0, /* properties_provided */
3476 0, /* properties_destroyed */
3477 0, /* todo_flags_start */
3478 TODO_update_ssa
3479 | TODO_verify_ssa /* todo_flags_finish */
3483 struct gimple_opt_pass pass_sra =
3486 GIMPLE_PASS,
3487 "sra", /* name */
3488 OPTGROUP_NONE, /* optinfo_flags */
3489 gate_intra_sra, /* gate */
3490 late_intra_sra, /* execute */
3491 NULL, /* sub */
3492 NULL, /* next */
3493 0, /* static_pass_number */
3494 TV_TREE_SRA, /* tv_id */
3495 PROP_cfg | PROP_ssa, /* properties_required */
3496 0, /* properties_provided */
3497 0, /* properties_destroyed */
3498 TODO_update_address_taken, /* todo_flags_start */
3499 TODO_update_ssa
3500 | TODO_verify_ssa /* todo_flags_finish */
3505 /* Return true iff PARM (which must be a parm_decl) is an unused scalar
3506 parameter. */
3508 static bool
3509 is_unused_scalar_param (tree parm)
3511 tree name;
3512 return (is_gimple_reg (parm)
3513 && (!(name = ssa_default_def (cfun, parm))
3514 || has_zero_uses (name)));
3517 /* Scan immediate uses of a default definition SSA name of a parameter PARM and
3518 examine whether there are any direct or otherwise infeasible ones. If so,
3519 return true, otherwise return false. PARM must be a gimple register with a
3520 non-NULL default definition. */
3522 static bool
3523 ptr_parm_has_direct_uses (tree parm)
3525 imm_use_iterator ui;
3526 gimple stmt;
3527 tree name = ssa_default_def (cfun, parm);
3528 bool ret = false;
3530 FOR_EACH_IMM_USE_STMT (stmt, ui, name)
3532 int uses_ok = 0;
3533 use_operand_p use_p;
3535 if (is_gimple_debug (stmt))
3536 continue;
3538 /* Valid uses include dereferences on the lhs and the rhs. */
3539 if (gimple_has_lhs (stmt))
3541 tree lhs = gimple_get_lhs (stmt);
3542 while (handled_component_p (lhs))
3543 lhs = TREE_OPERAND (lhs, 0);
3544 if (TREE_CODE (lhs) == MEM_REF
3545 && TREE_OPERAND (lhs, 0) == name
3546 && integer_zerop (TREE_OPERAND (lhs, 1))
3547 && types_compatible_p (TREE_TYPE (lhs),
3548 TREE_TYPE (TREE_TYPE (name)))
3549 && !TREE_THIS_VOLATILE (lhs))
3550 uses_ok++;
3552 if (gimple_assign_single_p (stmt))
3554 tree rhs = gimple_assign_rhs1 (stmt);
3555 while (handled_component_p (rhs))
3556 rhs = TREE_OPERAND (rhs, 0);
3557 if (TREE_CODE (rhs) == MEM_REF
3558 && TREE_OPERAND (rhs, 0) == name
3559 && integer_zerop (TREE_OPERAND (rhs, 1))
3560 && types_compatible_p (TREE_TYPE (rhs),
3561 TREE_TYPE (TREE_TYPE (name)))
3562 && !TREE_THIS_VOLATILE (rhs))
3563 uses_ok++;
3565 else if (is_gimple_call (stmt))
3567 unsigned i;
3568 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3570 tree arg = gimple_call_arg (stmt, i);
3571 while (handled_component_p (arg))
3572 arg = TREE_OPERAND (arg, 0);
3573 if (TREE_CODE (arg) == MEM_REF
3574 && TREE_OPERAND (arg, 0) == name
3575 && integer_zerop (TREE_OPERAND (arg, 1))
3576 && types_compatible_p (TREE_TYPE (arg),
3577 TREE_TYPE (TREE_TYPE (name)))
3578 && !TREE_THIS_VOLATILE (arg))
3579 uses_ok++;
3583 /* If the number of valid uses does not match the number of
3584 uses in this stmt there is an unhandled use. */
3585 FOR_EACH_IMM_USE_ON_STMT (use_p, ui)
3586 --uses_ok;
3588 if (uses_ok != 0)
3589 ret = true;
3591 if (ret)
3592 BREAK_FROM_IMM_USE_STMT (ui);
3595 return ret;
3598 /* Identify candidates for reduction for IPA-SRA based on their type and mark
3599 them in candidate_bitmap. Note that these do not necessarily include
3600 parameter which are unused and thus can be removed. Return true iff any
3601 such candidate has been found. */
3603 static bool
3604 find_param_candidates (void)
3606 tree parm;
3607 int count = 0;
3608 bool ret = false;
3609 const char *msg;
3611 for (parm = DECL_ARGUMENTS (current_function_decl);
3612 parm;
3613 parm = DECL_CHAIN (parm))
3615 tree type = TREE_TYPE (parm);
3616 tree_node **slot;
3618 count++;
3620 if (TREE_THIS_VOLATILE (parm)
3621 || TREE_ADDRESSABLE (parm)
3622 || (!is_gimple_reg_type (type) && is_va_list_type (type)))
3623 continue;
3625 if (is_unused_scalar_param (parm))
3627 ret = true;
3628 continue;
3631 if (POINTER_TYPE_P (type))
3633 type = TREE_TYPE (type);
3635 if (TREE_CODE (type) == FUNCTION_TYPE
3636 || TYPE_VOLATILE (type)
3637 || (TREE_CODE (type) == ARRAY_TYPE
3638 && TYPE_NONALIASED_COMPONENT (type))
3639 || !is_gimple_reg (parm)
3640 || is_va_list_type (type)
3641 || ptr_parm_has_direct_uses (parm))
3642 continue;
3644 else if (!AGGREGATE_TYPE_P (type))
3645 continue;
3647 if (!COMPLETE_TYPE_P (type)
3648 || !host_integerp (TYPE_SIZE (type), 1)
3649 || tree_low_cst (TYPE_SIZE (type), 1) == 0
3650 || (AGGREGATE_TYPE_P (type)
3651 && type_internals_preclude_sra_p (type, &msg)))
3652 continue;
3654 bitmap_set_bit (candidate_bitmap, DECL_UID (parm));
3655 slot = candidates.find_slot_with_hash (parm, DECL_UID (parm), INSERT);
3656 *slot = parm;
3658 ret = true;
3659 if (dump_file && (dump_flags & TDF_DETAILS))
3661 fprintf (dump_file, "Candidate (%d): ", DECL_UID (parm));
3662 print_generic_expr (dump_file, parm, 0);
3663 fprintf (dump_file, "\n");
3667 func_param_count = count;
3668 return ret;
3671 /* Callback of walk_aliased_vdefs, marks the access passed as DATA as
3672 maybe_modified. */
3674 static bool
3675 mark_maybe_modified (ao_ref *ao ATTRIBUTE_UNUSED, tree vdef ATTRIBUTE_UNUSED,
3676 void *data)
3678 struct access *repr = (struct access *) data;
3680 repr->grp_maybe_modified = 1;
3681 return true;
3684 /* Analyze what representatives (in linked lists accessible from
3685 REPRESENTATIVES) can be modified by side effects of statements in the
3686 current function. */
3688 static void
3689 analyze_modified_params (vec<access_p> representatives)
3691 int i;
3693 for (i = 0; i < func_param_count; i++)
3695 struct access *repr;
3697 for (repr = representatives[i];
3698 repr;
3699 repr = repr->next_grp)
3701 struct access *access;
3702 bitmap visited;
3703 ao_ref ar;
3705 if (no_accesses_p (repr))
3706 continue;
3707 if (!POINTER_TYPE_P (TREE_TYPE (repr->base))
3708 || repr->grp_maybe_modified)
3709 continue;
3711 ao_ref_init (&ar, repr->expr);
3712 visited = BITMAP_ALLOC (NULL);
3713 for (access = repr; access; access = access->next_sibling)
3715 /* All accesses are read ones, otherwise grp_maybe_modified would
3716 be trivially set. */
3717 walk_aliased_vdefs (&ar, gimple_vuse (access->stmt),
3718 mark_maybe_modified, repr, &visited);
3719 if (repr->grp_maybe_modified)
3720 break;
3722 BITMAP_FREE (visited);
3727 /* Propagate distances in bb_dereferences in the opposite direction than the
3728 control flow edges, in each step storing the maximum of the current value
3729 and the minimum of all successors. These steps are repeated until the table
3730 stabilizes. Note that BBs which might terminate the functions (according to
3731 final_bbs bitmap) never updated in this way. */
3733 static void
3734 propagate_dereference_distances (void)
3736 vec<basic_block> queue;
3737 basic_block bb;
3739 queue.create (last_basic_block_for_function (cfun));
3740 queue.quick_push (ENTRY_BLOCK_PTR);
3741 FOR_EACH_BB (bb)
3743 queue.quick_push (bb);
3744 bb->aux = bb;
3747 while (!queue.is_empty ())
3749 edge_iterator ei;
3750 edge e;
3751 bool change = false;
3752 int i;
3754 bb = queue.pop ();
3755 bb->aux = NULL;
3757 if (bitmap_bit_p (final_bbs, bb->index))
3758 continue;
3760 for (i = 0; i < func_param_count; i++)
3762 int idx = bb->index * func_param_count + i;
3763 bool first = true;
3764 HOST_WIDE_INT inh = 0;
3766 FOR_EACH_EDGE (e, ei, bb->succs)
3768 int succ_idx = e->dest->index * func_param_count + i;
3770 if (e->src == EXIT_BLOCK_PTR)
3771 continue;
3773 if (first)
3775 first = false;
3776 inh = bb_dereferences [succ_idx];
3778 else if (bb_dereferences [succ_idx] < inh)
3779 inh = bb_dereferences [succ_idx];
3782 if (!first && bb_dereferences[idx] < inh)
3784 bb_dereferences[idx] = inh;
3785 change = true;
3789 if (change && !bitmap_bit_p (final_bbs, bb->index))
3790 FOR_EACH_EDGE (e, ei, bb->preds)
3792 if (e->src->aux)
3793 continue;
3795 e->src->aux = e->src;
3796 queue.quick_push (e->src);
3800 queue.release ();
3803 /* Dump a dereferences TABLE with heading STR to file F. */
3805 static void
3806 dump_dereferences_table (FILE *f, const char *str, HOST_WIDE_INT *table)
3808 basic_block bb;
3810 fprintf (dump_file, str);
3811 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, EXIT_BLOCK_PTR, next_bb)
3813 fprintf (f, "%4i %i ", bb->index, bitmap_bit_p (final_bbs, bb->index));
3814 if (bb != EXIT_BLOCK_PTR)
3816 int i;
3817 for (i = 0; i < func_param_count; i++)
3819 int idx = bb->index * func_param_count + i;
3820 fprintf (f, " %4" HOST_WIDE_INT_PRINT "d", table[idx]);
3823 fprintf (f, "\n");
3825 fprintf (dump_file, "\n");
3828 /* Determine what (parts of) parameters passed by reference that are not
3829 assigned to are not certainly dereferenced in this function and thus the
3830 dereferencing cannot be safely moved to the caller without potentially
3831 introducing a segfault. Mark such REPRESENTATIVES as
3832 grp_not_necessarilly_dereferenced.
3834 The dereferenced maximum "distance," i.e. the offset + size of the accessed
3835 part is calculated rather than simple booleans are calculated for each
3836 pointer parameter to handle cases when only a fraction of the whole
3837 aggregate is allocated (see testsuite/gcc.c-torture/execute/ipa-sra-2.c for
3838 an example).
3840 The maximum dereference distances for each pointer parameter and BB are
3841 already stored in bb_dereference. This routine simply propagates these
3842 values upwards by propagate_dereference_distances and then compares the
3843 distances of individual parameters in the ENTRY BB to the equivalent
3844 distances of each representative of a (fraction of a) parameter. */
3846 static void
3847 analyze_caller_dereference_legality (vec<access_p> representatives)
3849 int i;
3851 if (dump_file && (dump_flags & TDF_DETAILS))
3852 dump_dereferences_table (dump_file,
3853 "Dereference table before propagation:\n",
3854 bb_dereferences);
3856 propagate_dereference_distances ();
3858 if (dump_file && (dump_flags & TDF_DETAILS))
3859 dump_dereferences_table (dump_file,
3860 "Dereference table after propagation:\n",
3861 bb_dereferences);
3863 for (i = 0; i < func_param_count; i++)
3865 struct access *repr = representatives[i];
3866 int idx = ENTRY_BLOCK_PTR->index * func_param_count + i;
3868 if (!repr || no_accesses_p (repr))
3869 continue;
3873 if ((repr->offset + repr->size) > bb_dereferences[idx])
3874 repr->grp_not_necessarilly_dereferenced = 1;
3875 repr = repr->next_grp;
3877 while (repr);
3881 /* Return the representative access for the parameter declaration PARM if it is
3882 a scalar passed by reference which is not written to and the pointer value
3883 is not used directly. Thus, if it is legal to dereference it in the caller
3884 and we can rule out modifications through aliases, such parameter should be
3885 turned into one passed by value. Return NULL otherwise. */
3887 static struct access *
3888 unmodified_by_ref_scalar_representative (tree parm)
3890 int i, access_count;
3891 struct access *repr;
3892 vec<access_p> *access_vec;
3894 access_vec = get_base_access_vector (parm);
3895 gcc_assert (access_vec);
3896 repr = (*access_vec)[0];
3897 if (repr->write)
3898 return NULL;
3899 repr->group_representative = repr;
3901 access_count = access_vec->length ();
3902 for (i = 1; i < access_count; i++)
3904 struct access *access = (*access_vec)[i];
3905 if (access->write)
3906 return NULL;
3907 access->group_representative = repr;
3908 access->next_sibling = repr->next_sibling;
3909 repr->next_sibling = access;
3912 repr->grp_read = 1;
3913 repr->grp_scalar_ptr = 1;
3914 return repr;
3917 /* Return true iff this ACCESS precludes IPA-SRA of the parameter it is
3918 associated with. REQ_ALIGN is the minimum required alignment. */
3920 static bool
3921 access_precludes_ipa_sra_p (struct access *access, unsigned int req_align)
3923 unsigned int exp_align;
3924 /* Avoid issues such as the second simple testcase in PR 42025. The problem
3925 is incompatible assign in a call statement (and possibly even in asm
3926 statements). This can be relaxed by using a new temporary but only for
3927 non-TREE_ADDRESSABLE types and is probably not worth the complexity. (In
3928 intraprocedural SRA we deal with this by keeping the old aggregate around,
3929 something we cannot do in IPA-SRA.) */
3930 if (access->write
3931 && (is_gimple_call (access->stmt)
3932 || gimple_code (access->stmt) == GIMPLE_ASM))
3933 return true;
3935 exp_align = get_object_alignment (access->expr);
3936 if (exp_align < req_align)
3937 return true;
3939 return false;
3943 /* Sort collected accesses for parameter PARM, identify representatives for
3944 each accessed region and link them together. Return NULL if there are
3945 different but overlapping accesses, return the special ptr value meaning
3946 there are no accesses for this parameter if that is the case and return the
3947 first representative otherwise. Set *RO_GRP if there is a group of accesses
3948 with only read (i.e. no write) accesses. */
3950 static struct access *
3951 splice_param_accesses (tree parm, bool *ro_grp)
3953 int i, j, access_count, group_count;
3954 int agg_size, total_size = 0;
3955 struct access *access, *res, **prev_acc_ptr = &res;
3956 vec<access_p> *access_vec;
3958 access_vec = get_base_access_vector (parm);
3959 if (!access_vec)
3960 return &no_accesses_representant;
3961 access_count = access_vec->length ();
3963 access_vec->qsort (compare_access_positions);
3965 i = 0;
3966 total_size = 0;
3967 group_count = 0;
3968 while (i < access_count)
3970 bool modification;
3971 tree a1_alias_type;
3972 access = (*access_vec)[i];
3973 modification = access->write;
3974 if (access_precludes_ipa_sra_p (access, TYPE_ALIGN (access->type)))
3975 return NULL;
3976 a1_alias_type = reference_alias_ptr_type (access->expr);
3978 /* Access is about to become group representative unless we find some
3979 nasty overlap which would preclude us from breaking this parameter
3980 apart. */
3982 j = i + 1;
3983 while (j < access_count)
3985 struct access *ac2 = (*access_vec)[j];
3986 if (ac2->offset != access->offset)
3988 /* All or nothing law for parameters. */
3989 if (access->offset + access->size > ac2->offset)
3990 return NULL;
3991 else
3992 break;
3994 else if (ac2->size != access->size)
3995 return NULL;
3997 if (access_precludes_ipa_sra_p (ac2, TYPE_ALIGN (access->type))
3998 || (ac2->type != access->type
3999 && (TREE_ADDRESSABLE (ac2->type)
4000 || TREE_ADDRESSABLE (access->type)))
4001 || (reference_alias_ptr_type (ac2->expr) != a1_alias_type))
4002 return NULL;
4004 modification |= ac2->write;
4005 ac2->group_representative = access;
4006 ac2->next_sibling = access->next_sibling;
4007 access->next_sibling = ac2;
4008 j++;
4011 group_count++;
4012 access->grp_maybe_modified = modification;
4013 if (!modification)
4014 *ro_grp = true;
4015 *prev_acc_ptr = access;
4016 prev_acc_ptr = &access->next_grp;
4017 total_size += access->size;
4018 i = j;
4021 if (POINTER_TYPE_P (TREE_TYPE (parm)))
4022 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (TREE_TYPE (parm))), 1);
4023 else
4024 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (parm)), 1);
4025 if (total_size >= agg_size)
4026 return NULL;
4028 gcc_assert (group_count > 0);
4029 return res;
4032 /* Decide whether parameters with representative accesses given by REPR should
4033 be reduced into components. */
4035 static int
4036 decide_one_param_reduction (struct access *repr)
4038 int total_size, cur_parm_size, agg_size, new_param_count, parm_size_limit;
4039 bool by_ref;
4040 tree parm;
4042 parm = repr->base;
4043 cur_parm_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (parm)), 1);
4044 gcc_assert (cur_parm_size > 0);
4046 if (POINTER_TYPE_P (TREE_TYPE (parm)))
4048 by_ref = true;
4049 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (TREE_TYPE (parm))), 1);
4051 else
4053 by_ref = false;
4054 agg_size = cur_parm_size;
4057 if (dump_file)
4059 struct access *acc;
4060 fprintf (dump_file, "Evaluating PARAM group sizes for ");
4061 print_generic_expr (dump_file, parm, 0);
4062 fprintf (dump_file, " (UID: %u): \n", DECL_UID (parm));
4063 for (acc = repr; acc; acc = acc->next_grp)
4064 dump_access (dump_file, acc, true);
4067 total_size = 0;
4068 new_param_count = 0;
4070 for (; repr; repr = repr->next_grp)
4072 gcc_assert (parm == repr->base);
4074 /* Taking the address of a non-addressable field is verboten. */
4075 if (by_ref && repr->non_addressable)
4076 return 0;
4078 /* Do not decompose a non-BLKmode param in a way that would
4079 create BLKmode params. Especially for by-reference passing
4080 (thus, pointer-type param) this is hardly worthwhile. */
4081 if (DECL_MODE (parm) != BLKmode
4082 && TYPE_MODE (repr->type) == BLKmode)
4083 return 0;
4085 if (!by_ref || (!repr->grp_maybe_modified
4086 && !repr->grp_not_necessarilly_dereferenced))
4087 total_size += repr->size;
4088 else
4089 total_size += cur_parm_size;
4091 new_param_count++;
4094 gcc_assert (new_param_count > 0);
4096 if (optimize_function_for_size_p (cfun))
4097 parm_size_limit = cur_parm_size;
4098 else
4099 parm_size_limit = (PARAM_VALUE (PARAM_IPA_SRA_PTR_GROWTH_FACTOR)
4100 * cur_parm_size);
4102 if (total_size < agg_size
4103 && total_size <= parm_size_limit)
4105 if (dump_file)
4106 fprintf (dump_file, " ....will be split into %i components\n",
4107 new_param_count);
4108 return new_param_count;
4110 else
4111 return 0;
4114 /* The order of the following enums is important, we need to do extra work for
4115 UNUSED_PARAMS, BY_VAL_ACCESSES and UNMODIF_BY_REF_ACCESSES. */
4116 enum ipa_splicing_result { NO_GOOD_ACCESS, UNUSED_PARAMS, BY_VAL_ACCESSES,
4117 MODIF_BY_REF_ACCESSES, UNMODIF_BY_REF_ACCESSES };
4119 /* Identify representatives of all accesses to all candidate parameters for
4120 IPA-SRA. Return result based on what representatives have been found. */
4122 static enum ipa_splicing_result
4123 splice_all_param_accesses (vec<access_p> &representatives)
4125 enum ipa_splicing_result result = NO_GOOD_ACCESS;
4126 tree parm;
4127 struct access *repr;
4129 representatives.create (func_param_count);
4131 for (parm = DECL_ARGUMENTS (current_function_decl);
4132 parm;
4133 parm = DECL_CHAIN (parm))
4135 if (is_unused_scalar_param (parm))
4137 representatives.quick_push (&no_accesses_representant);
4138 if (result == NO_GOOD_ACCESS)
4139 result = UNUSED_PARAMS;
4141 else if (POINTER_TYPE_P (TREE_TYPE (parm))
4142 && is_gimple_reg_type (TREE_TYPE (TREE_TYPE (parm)))
4143 && bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
4145 repr = unmodified_by_ref_scalar_representative (parm);
4146 representatives.quick_push (repr);
4147 if (repr)
4148 result = UNMODIF_BY_REF_ACCESSES;
4150 else if (bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
4152 bool ro_grp = false;
4153 repr = splice_param_accesses (parm, &ro_grp);
4154 representatives.quick_push (repr);
4156 if (repr && !no_accesses_p (repr))
4158 if (POINTER_TYPE_P (TREE_TYPE (parm)))
4160 if (ro_grp)
4161 result = UNMODIF_BY_REF_ACCESSES;
4162 else if (result < MODIF_BY_REF_ACCESSES)
4163 result = MODIF_BY_REF_ACCESSES;
4165 else if (result < BY_VAL_ACCESSES)
4166 result = BY_VAL_ACCESSES;
4168 else if (no_accesses_p (repr) && (result == NO_GOOD_ACCESS))
4169 result = UNUSED_PARAMS;
4171 else
4172 representatives.quick_push (NULL);
4175 if (result == NO_GOOD_ACCESS)
4177 representatives.release ();
4178 return NO_GOOD_ACCESS;
4181 return result;
4184 /* Return the index of BASE in PARMS. Abort if it is not found. */
4186 static inline int
4187 get_param_index (tree base, vec<tree> parms)
4189 int i, len;
4191 len = parms.length ();
4192 for (i = 0; i < len; i++)
4193 if (parms[i] == base)
4194 return i;
4195 gcc_unreachable ();
4198 /* Convert the decisions made at the representative level into compact
4199 parameter adjustments. REPRESENTATIVES are pointers to first
4200 representatives of each param accesses, ADJUSTMENTS_COUNT is the expected
4201 final number of adjustments. */
4203 static ipa_parm_adjustment_vec
4204 turn_representatives_into_adjustments (vec<access_p> representatives,
4205 int adjustments_count)
4207 vec<tree> parms;
4208 ipa_parm_adjustment_vec adjustments;
4209 tree parm;
4210 int i;
4212 gcc_assert (adjustments_count > 0);
4213 parms = ipa_get_vector_of_formal_parms (current_function_decl);
4214 adjustments.create (adjustments_count);
4215 parm = DECL_ARGUMENTS (current_function_decl);
4216 for (i = 0; i < func_param_count; i++, parm = DECL_CHAIN (parm))
4218 struct access *repr = representatives[i];
4220 if (!repr || no_accesses_p (repr))
4222 struct ipa_parm_adjustment adj;
4224 memset (&adj, 0, sizeof (adj));
4225 adj.base_index = get_param_index (parm, parms);
4226 adj.base = parm;
4227 if (!repr)
4228 adj.copy_param = 1;
4229 else
4230 adj.remove_param = 1;
4231 adjustments.quick_push (adj);
4233 else
4235 struct ipa_parm_adjustment adj;
4236 int index = get_param_index (parm, parms);
4238 for (; repr; repr = repr->next_grp)
4240 memset (&adj, 0, sizeof (adj));
4241 gcc_assert (repr->base == parm);
4242 adj.base_index = index;
4243 adj.base = repr->base;
4244 adj.type = repr->type;
4245 adj.alias_ptr_type = reference_alias_ptr_type (repr->expr);
4246 adj.offset = repr->offset;
4247 adj.by_ref = (POINTER_TYPE_P (TREE_TYPE (repr->base))
4248 && (repr->grp_maybe_modified
4249 || repr->grp_not_necessarilly_dereferenced));
4250 adjustments.quick_push (adj);
4254 parms.release ();
4255 return adjustments;
4258 /* Analyze the collected accesses and produce a plan what to do with the
4259 parameters in the form of adjustments, NULL meaning nothing. */
4261 static ipa_parm_adjustment_vec
4262 analyze_all_param_acesses (void)
4264 enum ipa_splicing_result repr_state;
4265 bool proceed = false;
4266 int i, adjustments_count = 0;
4267 vec<access_p> representatives;
4268 ipa_parm_adjustment_vec adjustments;
4270 repr_state = splice_all_param_accesses (representatives);
4271 if (repr_state == NO_GOOD_ACCESS)
4272 return ipa_parm_adjustment_vec();
4274 /* If there are any parameters passed by reference which are not modified
4275 directly, we need to check whether they can be modified indirectly. */
4276 if (repr_state == UNMODIF_BY_REF_ACCESSES)
4278 analyze_caller_dereference_legality (representatives);
4279 analyze_modified_params (representatives);
4282 for (i = 0; i < func_param_count; i++)
4284 struct access *repr = representatives[i];
4286 if (repr && !no_accesses_p (repr))
4288 if (repr->grp_scalar_ptr)
4290 adjustments_count++;
4291 if (repr->grp_not_necessarilly_dereferenced
4292 || repr->grp_maybe_modified)
4293 representatives[i] = NULL;
4294 else
4296 proceed = true;
4297 sra_stats.scalar_by_ref_to_by_val++;
4300 else
4302 int new_components = decide_one_param_reduction (repr);
4304 if (new_components == 0)
4306 representatives[i] = NULL;
4307 adjustments_count++;
4309 else
4311 adjustments_count += new_components;
4312 sra_stats.aggregate_params_reduced++;
4313 sra_stats.param_reductions_created += new_components;
4314 proceed = true;
4318 else
4320 if (no_accesses_p (repr))
4322 proceed = true;
4323 sra_stats.deleted_unused_parameters++;
4325 adjustments_count++;
4329 if (!proceed && dump_file)
4330 fprintf (dump_file, "NOT proceeding to change params.\n");
4332 if (proceed)
4333 adjustments = turn_representatives_into_adjustments (representatives,
4334 adjustments_count);
4335 else
4336 adjustments = ipa_parm_adjustment_vec();
4338 representatives.release ();
4339 return adjustments;
4342 /* If a parameter replacement identified by ADJ does not yet exist in the form
4343 of declaration, create it and record it, otherwise return the previously
4344 created one. */
4346 static tree
4347 get_replaced_param_substitute (struct ipa_parm_adjustment *adj)
4349 tree repl;
4350 if (!adj->new_ssa_base)
4352 char *pretty_name = make_fancy_name (adj->base);
4354 repl = create_tmp_reg (TREE_TYPE (adj->base), "ISR");
4355 DECL_NAME (repl) = get_identifier (pretty_name);
4356 obstack_free (&name_obstack, pretty_name);
4358 adj->new_ssa_base = repl;
4360 else
4361 repl = adj->new_ssa_base;
4362 return repl;
4365 /* Find the first adjustment for a particular parameter BASE in a vector of
4366 ADJUSTMENTS which is not a copy_param. Return NULL if there is no such
4367 adjustment. */
4369 static struct ipa_parm_adjustment *
4370 get_adjustment_for_base (ipa_parm_adjustment_vec adjustments, tree base)
4372 int i, len;
4374 len = adjustments.length ();
4375 for (i = 0; i < len; i++)
4377 struct ipa_parm_adjustment *adj;
4379 adj = &adjustments[i];
4380 if (!adj->copy_param && adj->base == base)
4381 return adj;
4384 return NULL;
4387 /* If the statement STMT defines an SSA_NAME of a parameter which is to be
4388 removed because its value is not used, replace the SSA_NAME with a one
4389 relating to a created VAR_DECL together all of its uses and return true.
4390 ADJUSTMENTS is a pointer to an adjustments vector. */
4392 static bool
4393 replace_removed_params_ssa_names (gimple stmt,
4394 ipa_parm_adjustment_vec adjustments)
4396 struct ipa_parm_adjustment *adj;
4397 tree lhs, decl, repl, name;
4399 if (gimple_code (stmt) == GIMPLE_PHI)
4400 lhs = gimple_phi_result (stmt);
4401 else if (is_gimple_assign (stmt))
4402 lhs = gimple_assign_lhs (stmt);
4403 else if (is_gimple_call (stmt))
4404 lhs = gimple_call_lhs (stmt);
4405 else
4406 gcc_unreachable ();
4408 if (TREE_CODE (lhs) != SSA_NAME)
4409 return false;
4411 decl = SSA_NAME_VAR (lhs);
4412 if (decl == NULL_TREE
4413 || TREE_CODE (decl) != PARM_DECL)
4414 return false;
4416 adj = get_adjustment_for_base (adjustments, decl);
4417 if (!adj)
4418 return false;
4420 repl = get_replaced_param_substitute (adj);
4421 name = make_ssa_name (repl, stmt);
4423 if (dump_file)
4425 fprintf (dump_file, "replacing an SSA name of a removed param ");
4426 print_generic_expr (dump_file, lhs, 0);
4427 fprintf (dump_file, " with ");
4428 print_generic_expr (dump_file, name, 0);
4429 fprintf (dump_file, "\n");
4432 if (is_gimple_assign (stmt))
4433 gimple_assign_set_lhs (stmt, name);
4434 else if (is_gimple_call (stmt))
4435 gimple_call_set_lhs (stmt, name);
4436 else
4437 gimple_phi_set_result (stmt, name);
4439 replace_uses_by (lhs, name);
4440 release_ssa_name (lhs);
4441 return true;
4444 /* If the expression *EXPR should be replaced by a reduction of a parameter, do
4445 so. ADJUSTMENTS is a pointer to a vector of adjustments. CONVERT
4446 specifies whether the function should care about type incompatibility the
4447 current and new expressions. If it is false, the function will leave
4448 incompatibility issues to the caller. Return true iff the expression
4449 was modified. */
4451 static bool
4452 sra_ipa_modify_expr (tree *expr, bool convert,
4453 ipa_parm_adjustment_vec adjustments)
4455 int i, len;
4456 struct ipa_parm_adjustment *adj, *cand = NULL;
4457 HOST_WIDE_INT offset, size, max_size;
4458 tree base, src;
4460 len = adjustments.length ();
4462 if (TREE_CODE (*expr) == BIT_FIELD_REF
4463 || TREE_CODE (*expr) == IMAGPART_EXPR
4464 || TREE_CODE (*expr) == REALPART_EXPR)
4466 expr = &TREE_OPERAND (*expr, 0);
4467 convert = true;
4470 base = get_ref_base_and_extent (*expr, &offset, &size, &max_size);
4471 if (!base || size == -1 || max_size == -1)
4472 return false;
4474 if (TREE_CODE (base) == MEM_REF)
4476 offset += mem_ref_offset (base).low * BITS_PER_UNIT;
4477 base = TREE_OPERAND (base, 0);
4480 base = get_ssa_base_param (base);
4481 if (!base || TREE_CODE (base) != PARM_DECL)
4482 return false;
4484 for (i = 0; i < len; i++)
4486 adj = &adjustments[i];
4488 if (adj->base == base
4489 && (adj->offset == offset || adj->remove_param))
4491 cand = adj;
4492 break;
4495 if (!cand || cand->copy_param || cand->remove_param)
4496 return false;
4498 if (cand->by_ref)
4499 src = build_simple_mem_ref (cand->reduction);
4500 else
4501 src = cand->reduction;
4503 if (dump_file && (dump_flags & TDF_DETAILS))
4505 fprintf (dump_file, "About to replace expr ");
4506 print_generic_expr (dump_file, *expr, 0);
4507 fprintf (dump_file, " with ");
4508 print_generic_expr (dump_file, src, 0);
4509 fprintf (dump_file, "\n");
4512 if (convert && !useless_type_conversion_p (TREE_TYPE (*expr), cand->type))
4514 tree vce = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (*expr), src);
4515 *expr = vce;
4517 else
4518 *expr = src;
4519 return true;
4522 /* If the statement pointed to by STMT_PTR contains any expressions that need
4523 to replaced with a different one as noted by ADJUSTMENTS, do so. Handle any
4524 potential type incompatibilities (GSI is used to accommodate conversion
4525 statements and must point to the statement). Return true iff the statement
4526 was modified. */
4528 static bool
4529 sra_ipa_modify_assign (gimple *stmt_ptr, gimple_stmt_iterator *gsi,
4530 ipa_parm_adjustment_vec adjustments)
4532 gimple stmt = *stmt_ptr;
4533 tree *lhs_p, *rhs_p;
4534 bool any;
4536 if (!gimple_assign_single_p (stmt))
4537 return false;
4539 rhs_p = gimple_assign_rhs1_ptr (stmt);
4540 lhs_p = gimple_assign_lhs_ptr (stmt);
4542 any = sra_ipa_modify_expr (rhs_p, false, adjustments);
4543 any |= sra_ipa_modify_expr (lhs_p, false, adjustments);
4544 if (any)
4546 tree new_rhs = NULL_TREE;
4548 if (!useless_type_conversion_p (TREE_TYPE (*lhs_p), TREE_TYPE (*rhs_p)))
4550 if (TREE_CODE (*rhs_p) == CONSTRUCTOR)
4552 /* V_C_Es of constructors can cause trouble (PR 42714). */
4553 if (is_gimple_reg_type (TREE_TYPE (*lhs_p)))
4554 *rhs_p = build_zero_cst (TREE_TYPE (*lhs_p));
4555 else
4556 *rhs_p = build_constructor (TREE_TYPE (*lhs_p),
4557 NULL);
4559 else
4560 new_rhs = fold_build1_loc (gimple_location (stmt),
4561 VIEW_CONVERT_EXPR, TREE_TYPE (*lhs_p),
4562 *rhs_p);
4564 else if (REFERENCE_CLASS_P (*rhs_p)
4565 && is_gimple_reg_type (TREE_TYPE (*lhs_p))
4566 && !is_gimple_reg (*lhs_p))
4567 /* This can happen when an assignment in between two single field
4568 structures is turned into an assignment in between two pointers to
4569 scalars (PR 42237). */
4570 new_rhs = *rhs_p;
4572 if (new_rhs)
4574 tree tmp = force_gimple_operand_gsi (gsi, new_rhs, true, NULL_TREE,
4575 true, GSI_SAME_STMT);
4577 gimple_assign_set_rhs_from_tree (gsi, tmp);
4580 return true;
4583 return false;
4586 /* Traverse the function body and all modifications as described in
4587 ADJUSTMENTS. Return true iff the CFG has been changed. */
4589 static bool
4590 ipa_sra_modify_function_body (ipa_parm_adjustment_vec adjustments)
4592 bool cfg_changed = false;
4593 basic_block bb;
4595 FOR_EACH_BB (bb)
4597 gimple_stmt_iterator gsi;
4599 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4600 replace_removed_params_ssa_names (gsi_stmt (gsi), adjustments);
4602 gsi = gsi_start_bb (bb);
4603 while (!gsi_end_p (gsi))
4605 gimple stmt = gsi_stmt (gsi);
4606 bool modified = false;
4607 tree *t;
4608 unsigned i;
4610 switch (gimple_code (stmt))
4612 case GIMPLE_RETURN:
4613 t = gimple_return_retval_ptr (stmt);
4614 if (*t != NULL_TREE)
4615 modified |= sra_ipa_modify_expr (t, true, adjustments);
4616 break;
4618 case GIMPLE_ASSIGN:
4619 modified |= sra_ipa_modify_assign (&stmt, &gsi, adjustments);
4620 modified |= replace_removed_params_ssa_names (stmt, adjustments);
4621 break;
4623 case GIMPLE_CALL:
4624 /* Operands must be processed before the lhs. */
4625 for (i = 0; i < gimple_call_num_args (stmt); i++)
4627 t = gimple_call_arg_ptr (stmt, i);
4628 modified |= sra_ipa_modify_expr (t, true, adjustments);
4631 if (gimple_call_lhs (stmt))
4633 t = gimple_call_lhs_ptr (stmt);
4634 modified |= sra_ipa_modify_expr (t, false, adjustments);
4635 modified |= replace_removed_params_ssa_names (stmt,
4636 adjustments);
4638 break;
4640 case GIMPLE_ASM:
4641 for (i = 0; i < gimple_asm_ninputs (stmt); i++)
4643 t = &TREE_VALUE (gimple_asm_input_op (stmt, i));
4644 modified |= sra_ipa_modify_expr (t, true, adjustments);
4646 for (i = 0; i < gimple_asm_noutputs (stmt); i++)
4648 t = &TREE_VALUE (gimple_asm_output_op (stmt, i));
4649 modified |= sra_ipa_modify_expr (t, false, adjustments);
4651 break;
4653 default:
4654 break;
4657 if (modified)
4659 update_stmt (stmt);
4660 if (maybe_clean_eh_stmt (stmt)
4661 && gimple_purge_dead_eh_edges (gimple_bb (stmt)))
4662 cfg_changed = true;
4664 gsi_next (&gsi);
4668 return cfg_changed;
4671 /* Call gimple_debug_bind_reset_value on all debug statements describing
4672 gimple register parameters that are being removed or replaced. */
4674 static void
4675 sra_ipa_reset_debug_stmts (ipa_parm_adjustment_vec adjustments)
4677 int i, len;
4678 gimple_stmt_iterator *gsip = NULL, gsi;
4680 if (MAY_HAVE_DEBUG_STMTS && single_succ_p (ENTRY_BLOCK_PTR))
4682 gsi = gsi_after_labels (single_succ (ENTRY_BLOCK_PTR));
4683 gsip = &gsi;
4685 len = adjustments.length ();
4686 for (i = 0; i < len; i++)
4688 struct ipa_parm_adjustment *adj;
4689 imm_use_iterator ui;
4690 gimple stmt, def_temp;
4691 tree name, vexpr, copy = NULL_TREE;
4692 use_operand_p use_p;
4694 adj = &adjustments[i];
4695 if (adj->copy_param || !is_gimple_reg (adj->base))
4696 continue;
4697 name = ssa_default_def (cfun, adj->base);
4698 vexpr = NULL;
4699 if (name)
4700 FOR_EACH_IMM_USE_STMT (stmt, ui, name)
4702 if (gimple_clobber_p (stmt))
4704 gimple_stmt_iterator cgsi = gsi_for_stmt (stmt);
4705 unlink_stmt_vdef (stmt);
4706 gsi_remove (&cgsi, true);
4707 release_defs (stmt);
4708 continue;
4710 /* All other users must have been removed by
4711 ipa_sra_modify_function_body. */
4712 gcc_assert (is_gimple_debug (stmt));
4713 if (vexpr == NULL && gsip != NULL)
4715 gcc_assert (TREE_CODE (adj->base) == PARM_DECL);
4716 vexpr = make_node (DEBUG_EXPR_DECL);
4717 def_temp = gimple_build_debug_source_bind (vexpr, adj->base,
4718 NULL);
4719 DECL_ARTIFICIAL (vexpr) = 1;
4720 TREE_TYPE (vexpr) = TREE_TYPE (name);
4721 DECL_MODE (vexpr) = DECL_MODE (adj->base);
4722 gsi_insert_before (gsip, def_temp, GSI_SAME_STMT);
4724 if (vexpr)
4726 FOR_EACH_IMM_USE_ON_STMT (use_p, ui)
4727 SET_USE (use_p, vexpr);
4729 else
4730 gimple_debug_bind_reset_value (stmt);
4731 update_stmt (stmt);
4733 /* Create a VAR_DECL for debug info purposes. */
4734 if (!DECL_IGNORED_P (adj->base))
4736 copy = build_decl (DECL_SOURCE_LOCATION (current_function_decl),
4737 VAR_DECL, DECL_NAME (adj->base),
4738 TREE_TYPE (adj->base));
4739 if (DECL_PT_UID_SET_P (adj->base))
4740 SET_DECL_PT_UID (copy, DECL_PT_UID (adj->base));
4741 TREE_ADDRESSABLE (copy) = TREE_ADDRESSABLE (adj->base);
4742 TREE_READONLY (copy) = TREE_READONLY (adj->base);
4743 TREE_THIS_VOLATILE (copy) = TREE_THIS_VOLATILE (adj->base);
4744 DECL_GIMPLE_REG_P (copy) = DECL_GIMPLE_REG_P (adj->base);
4745 DECL_ARTIFICIAL (copy) = DECL_ARTIFICIAL (adj->base);
4746 DECL_IGNORED_P (copy) = DECL_IGNORED_P (adj->base);
4747 DECL_ABSTRACT_ORIGIN (copy) = DECL_ORIGIN (adj->base);
4748 DECL_SEEN_IN_BIND_EXPR_P (copy) = 1;
4749 SET_DECL_RTL (copy, 0);
4750 TREE_USED (copy) = 1;
4751 DECL_CONTEXT (copy) = current_function_decl;
4752 add_local_decl (cfun, copy);
4753 DECL_CHAIN (copy) =
4754 BLOCK_VARS (DECL_INITIAL (current_function_decl));
4755 BLOCK_VARS (DECL_INITIAL (current_function_decl)) = copy;
4757 if (gsip != NULL && copy && target_for_debug_bind (adj->base))
4759 gcc_assert (TREE_CODE (adj->base) == PARM_DECL);
4760 if (vexpr)
4761 def_temp = gimple_build_debug_bind (copy, vexpr, NULL);
4762 else
4763 def_temp = gimple_build_debug_source_bind (copy, adj->base,
4764 NULL);
4765 gsi_insert_before (gsip, def_temp, GSI_SAME_STMT);
4770 /* Return false iff all callers have at least as many actual arguments as there
4771 are formal parameters in the current function. */
4773 static bool
4774 not_all_callers_have_enough_arguments_p (struct cgraph_node *node,
4775 void *data ATTRIBUTE_UNUSED)
4777 struct cgraph_edge *cs;
4778 for (cs = node->callers; cs; cs = cs->next_caller)
4779 if (!callsite_has_enough_arguments_p (cs->call_stmt))
4780 return true;
4782 return false;
4785 /* Convert all callers of NODE. */
4787 static bool
4788 convert_callers_for_node (struct cgraph_node *node,
4789 void *data)
4791 ipa_parm_adjustment_vec *adjustments = (ipa_parm_adjustment_vec *) data;
4792 bitmap recomputed_callers = BITMAP_ALLOC (NULL);
4793 struct cgraph_edge *cs;
4795 for (cs = node->callers; cs; cs = cs->next_caller)
4797 push_cfun (DECL_STRUCT_FUNCTION (cs->caller->symbol.decl));
4799 if (dump_file)
4800 fprintf (dump_file, "Adjusting call (%i -> %i) %s -> %s\n",
4801 cs->caller->uid, cs->callee->uid,
4802 xstrdup (cgraph_node_name (cs->caller)),
4803 xstrdup (cgraph_node_name (cs->callee)));
4805 ipa_modify_call_arguments (cs, cs->call_stmt, *adjustments);
4807 pop_cfun ();
4810 for (cs = node->callers; cs; cs = cs->next_caller)
4811 if (bitmap_set_bit (recomputed_callers, cs->caller->uid)
4812 && gimple_in_ssa_p (DECL_STRUCT_FUNCTION (cs->caller->symbol.decl)))
4813 compute_inline_parameters (cs->caller, true);
4814 BITMAP_FREE (recomputed_callers);
4816 return true;
4819 /* Convert all callers of NODE to pass parameters as given in ADJUSTMENTS. */
4821 static void
4822 convert_callers (struct cgraph_node *node, tree old_decl,
4823 ipa_parm_adjustment_vec adjustments)
4825 basic_block this_block;
4827 cgraph_for_node_and_aliases (node, convert_callers_for_node,
4828 &adjustments, false);
4830 if (!encountered_recursive_call)
4831 return;
4833 FOR_EACH_BB (this_block)
4835 gimple_stmt_iterator gsi;
4837 for (gsi = gsi_start_bb (this_block); !gsi_end_p (gsi); gsi_next (&gsi))
4839 gimple stmt = gsi_stmt (gsi);
4840 tree call_fndecl;
4841 if (gimple_code (stmt) != GIMPLE_CALL)
4842 continue;
4843 call_fndecl = gimple_call_fndecl (stmt);
4844 if (call_fndecl == old_decl)
4846 if (dump_file)
4847 fprintf (dump_file, "Adjusting recursive call");
4848 gimple_call_set_fndecl (stmt, node->symbol.decl);
4849 ipa_modify_call_arguments (NULL, stmt, adjustments);
4854 return;
4857 /* Perform all the modification required in IPA-SRA for NODE to have parameters
4858 as given in ADJUSTMENTS. Return true iff the CFG has been changed. */
4860 static bool
4861 modify_function (struct cgraph_node *node, ipa_parm_adjustment_vec adjustments)
4863 struct cgraph_node *new_node;
4864 bool cfg_changed;
4865 vec<cgraph_edge_p> redirect_callers = collect_callers_of_node (node);
4867 rebuild_cgraph_edges ();
4868 free_dominance_info (CDI_DOMINATORS);
4869 pop_cfun ();
4871 new_node = cgraph_function_versioning (node, redirect_callers,
4872 NULL,
4873 NULL, false, NULL, NULL, "isra");
4874 redirect_callers.release ();
4876 push_cfun (DECL_STRUCT_FUNCTION (new_node->symbol.decl));
4877 ipa_modify_formal_parameters (current_function_decl, adjustments, "ISRA");
4878 cfg_changed = ipa_sra_modify_function_body (adjustments);
4879 sra_ipa_reset_debug_stmts (adjustments);
4880 convert_callers (new_node, node->symbol.decl, adjustments);
4881 cgraph_make_node_local (new_node);
4882 return cfg_changed;
4885 /* Return false the function is apparently unsuitable for IPA-SRA based on it's
4886 attributes, return true otherwise. NODE is the cgraph node of the current
4887 function. */
4889 static bool
4890 ipa_sra_preliminary_function_checks (struct cgraph_node *node)
4892 if (!cgraph_node_can_be_local_p (node))
4894 if (dump_file)
4895 fprintf (dump_file, "Function not local to this compilation unit.\n");
4896 return false;
4899 if (!node->local.can_change_signature)
4901 if (dump_file)
4902 fprintf (dump_file, "Function can not change signature.\n");
4903 return false;
4906 if (!tree_versionable_function_p (node->symbol.decl))
4908 if (dump_file)
4909 fprintf (dump_file, "Function is not versionable.\n");
4910 return false;
4913 if (DECL_VIRTUAL_P (current_function_decl))
4915 if (dump_file)
4916 fprintf (dump_file, "Function is a virtual method.\n");
4917 return false;
4920 if ((DECL_COMDAT (node->symbol.decl) || DECL_EXTERNAL (node->symbol.decl))
4921 && inline_summary(node)->size >= MAX_INLINE_INSNS_AUTO)
4923 if (dump_file)
4924 fprintf (dump_file, "Function too big to be made truly local.\n");
4925 return false;
4928 if (!node->callers)
4930 if (dump_file)
4931 fprintf (dump_file,
4932 "Function has no callers in this compilation unit.\n");
4933 return false;
4936 if (cfun->stdarg)
4938 if (dump_file)
4939 fprintf (dump_file, "Function uses stdarg. \n");
4940 return false;
4943 if (TYPE_ATTRIBUTES (TREE_TYPE (node->symbol.decl)))
4944 return false;
4946 return true;
4949 /* Perform early interprocedural SRA. */
4951 static unsigned int
4952 ipa_early_sra (void)
4954 struct cgraph_node *node = cgraph_get_node (current_function_decl);
4955 ipa_parm_adjustment_vec adjustments;
4956 int ret = 0;
4958 if (!ipa_sra_preliminary_function_checks (node))
4959 return 0;
4961 sra_initialize ();
4962 sra_mode = SRA_MODE_EARLY_IPA;
4964 if (!find_param_candidates ())
4966 if (dump_file)
4967 fprintf (dump_file, "Function has no IPA-SRA candidates.\n");
4968 goto simple_out;
4971 if (cgraph_for_node_and_aliases (node, not_all_callers_have_enough_arguments_p,
4972 NULL, true))
4974 if (dump_file)
4975 fprintf (dump_file, "There are callers with insufficient number of "
4976 "arguments.\n");
4977 goto simple_out;
4980 bb_dereferences = XCNEWVEC (HOST_WIDE_INT,
4981 func_param_count
4982 * last_basic_block_for_function (cfun));
4983 final_bbs = BITMAP_ALLOC (NULL);
4985 scan_function ();
4986 if (encountered_apply_args)
4988 if (dump_file)
4989 fprintf (dump_file, "Function calls __builtin_apply_args().\n");
4990 goto out;
4993 if (encountered_unchangable_recursive_call)
4995 if (dump_file)
4996 fprintf (dump_file, "Function calls itself with insufficient "
4997 "number of arguments.\n");
4998 goto out;
5001 adjustments = analyze_all_param_acesses ();
5002 if (!adjustments.exists ())
5003 goto out;
5004 if (dump_file)
5005 ipa_dump_param_adjustments (dump_file, adjustments, current_function_decl);
5007 if (modify_function (node, adjustments))
5008 ret = TODO_update_ssa | TODO_cleanup_cfg;
5009 else
5010 ret = TODO_update_ssa;
5011 adjustments.release ();
5013 statistics_counter_event (cfun, "Unused parameters deleted",
5014 sra_stats.deleted_unused_parameters);
5015 statistics_counter_event (cfun, "Scalar parameters converted to by-value",
5016 sra_stats.scalar_by_ref_to_by_val);
5017 statistics_counter_event (cfun, "Aggregate parameters broken up",
5018 sra_stats.aggregate_params_reduced);
5019 statistics_counter_event (cfun, "Aggregate parameter components created",
5020 sra_stats.param_reductions_created);
5022 out:
5023 BITMAP_FREE (final_bbs);
5024 free (bb_dereferences);
5025 simple_out:
5026 sra_deinitialize ();
5027 return ret;
5030 /* Return if early ipa sra shall be performed. */
5031 static bool
5032 ipa_early_sra_gate (void)
5034 return flag_ipa_sra && dbg_cnt (eipa_sra);
5037 struct gimple_opt_pass pass_early_ipa_sra =
5040 GIMPLE_PASS,
5041 "eipa_sra", /* name */
5042 OPTGROUP_NONE, /* optinfo_flags */
5043 ipa_early_sra_gate, /* gate */
5044 ipa_early_sra, /* execute */
5045 NULL, /* sub */
5046 NULL, /* next */
5047 0, /* static_pass_number */
5048 TV_IPA_SRA, /* tv_id */
5049 0, /* properties_required */
5050 0, /* properties_provided */
5051 0, /* properties_destroyed */
5052 0, /* todo_flags_start */
5053 TODO_dump_symtab /* todo_flags_finish */