2012-07-26 Kazu Hirata <kazu@codesourcery.com>
[official-gcc.git] / gcc / tree-sra.c
blobe7ac92628e98c8cbb826f1478f97a2f2685bd2d5
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, 2009, 2010, 2011 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 "alloc-pool.h"
78 #include "tm.h"
79 #include "tree.h"
80 #include "gimple.h"
81 #include "cgraph.h"
82 #include "tree-flow.h"
83 #include "tree-pass.h"
84 #include "ipa-prop.h"
85 #include "statistics.h"
86 #include "params.h"
87 #include "target.h"
88 #include "flags.h"
89 #include "dbgcnt.h"
90 #include "tree-inline.h"
91 #include "gimple-pretty-print.h"
92 #include "ipa-inline.h"
94 /* Enumeration of all aggregate reductions we can do. */
95 enum sra_mode { SRA_MODE_EARLY_IPA, /* early call regularization */
96 SRA_MODE_EARLY_INTRA, /* early intraprocedural SRA */
97 SRA_MODE_INTRA }; /* late intraprocedural SRA */
99 /* Global variable describing which aggregate reduction we are performing at
100 the moment. */
101 static enum sra_mode sra_mode;
103 struct assign_link;
105 /* ACCESS represents each access to an aggregate variable (as a whole or a
106 part). It can also represent a group of accesses that refer to exactly the
107 same fragment of an aggregate (i.e. those that have exactly the same offset
108 and size). Such representatives for a single aggregate, once determined,
109 are linked in a linked list and have the group fields set.
111 Moreover, when doing intraprocedural SRA, a tree is built from those
112 representatives (by the means of first_child and next_sibling pointers), in
113 which all items in a subtree are "within" the root, i.e. their offset is
114 greater or equal to offset of the root and offset+size is smaller or equal
115 to offset+size of the root. Children of an access are sorted by offset.
117 Note that accesses to parts of vector and complex number types always
118 represented by an access to the whole complex number or a vector. It is a
119 duty of the modifying functions to replace them appropriately. */
121 struct access
123 /* Values returned by `get_ref_base_and_extent' for each component reference
124 If EXPR isn't a component reference just set `BASE = EXPR', `OFFSET = 0',
125 `SIZE = TREE_SIZE (TREE_TYPE (expr))'. */
126 HOST_WIDE_INT offset;
127 HOST_WIDE_INT size;
128 tree base;
130 /* Expression. It is context dependent so do not use it to create new
131 expressions to access the original aggregate. See PR 42154 for a
132 testcase. */
133 tree expr;
134 /* Type. */
135 tree type;
137 /* The statement this access belongs to. */
138 gimple stmt;
140 /* Next group representative for this aggregate. */
141 struct access *next_grp;
143 /* Pointer to the group representative. Pointer to itself if the struct is
144 the representative. */
145 struct access *group_representative;
147 /* If this access has any children (in terms of the definition above), this
148 points to the first one. */
149 struct access *first_child;
151 /* In intraprocedural SRA, pointer to the next sibling in the access tree as
152 described above. In IPA-SRA this is a pointer to the next access
153 belonging to the same group (having the same representative). */
154 struct access *next_sibling;
156 /* Pointers to the first and last element in the linked list of assign
157 links. */
158 struct assign_link *first_link, *last_link;
160 /* Pointer to the next access in the work queue. */
161 struct access *next_queued;
163 /* Replacement variable for this access "region." Never to be accessed
164 directly, always only by the means of get_access_replacement() and only
165 when grp_to_be_replaced flag is set. */
166 tree replacement_decl;
168 /* Is this particular access write access? */
169 unsigned write : 1;
171 /* Is this access an access to a non-addressable field? */
172 unsigned non_addressable : 1;
174 /* Is this access currently in the work queue? */
175 unsigned grp_queued : 1;
177 /* Does this group contain a write access? This flag is propagated down the
178 access tree. */
179 unsigned grp_write : 1;
181 /* Does this group contain a read access? This flag is propagated down the
182 access tree. */
183 unsigned grp_read : 1;
185 /* Does this group contain a read access that comes from an assignment
186 statement? This flag is propagated down the access tree. */
187 unsigned grp_assignment_read : 1;
189 /* Does this group contain a write access that comes from an assignment
190 statement? This flag is propagated down the access tree. */
191 unsigned grp_assignment_write : 1;
193 /* Does this group contain a read access through a scalar type? This flag is
194 not propagated in the access tree in any direction. */
195 unsigned grp_scalar_read : 1;
197 /* Does this group contain a write access through a scalar type? This flag
198 is not propagated in the access tree in any direction. */
199 unsigned grp_scalar_write : 1;
201 /* Is this access an artificial one created to scalarize some record
202 entirely? */
203 unsigned grp_total_scalarization : 1;
205 /* Other passes of the analysis use this bit to make function
206 analyze_access_subtree create scalar replacements for this group if
207 possible. */
208 unsigned grp_hint : 1;
210 /* Is the subtree rooted in this access fully covered by scalar
211 replacements? */
212 unsigned grp_covered : 1;
214 /* If set to true, this access and all below it in an access tree must not be
215 scalarized. */
216 unsigned grp_unscalarizable_region : 1;
218 /* Whether data have been written to parts of the aggregate covered by this
219 access which is not to be scalarized. This flag is propagated up in the
220 access tree. */
221 unsigned grp_unscalarized_data : 1;
223 /* Does this access and/or group contain a write access through a
224 BIT_FIELD_REF? */
225 unsigned grp_partial_lhs : 1;
227 /* Set when a scalar replacement should be created for this variable. We do
228 the decision and creation at different places because create_tmp_var
229 cannot be called from within FOR_EACH_REFERENCED_VAR. */
230 unsigned grp_to_be_replaced : 1;
232 /* Should TREE_NO_WARNING of a replacement be set? */
233 unsigned grp_no_warning : 1;
235 /* Is it possible that the group refers to data which might be (directly or
236 otherwise) modified? */
237 unsigned grp_maybe_modified : 1;
239 /* Set when this is a representative of a pointer to scalar (i.e. by
240 reference) parameter which we consider for turning into a plain scalar
241 (i.e. a by value parameter). */
242 unsigned grp_scalar_ptr : 1;
244 /* Set when we discover that this pointer is not safe to dereference in the
245 caller. */
246 unsigned grp_not_necessarilly_dereferenced : 1;
249 typedef struct access *access_p;
251 DEF_VEC_P (access_p);
252 DEF_VEC_ALLOC_P (access_p, heap);
254 /* Alloc pool for allocating access structures. */
255 static alloc_pool access_pool;
257 /* A structure linking lhs and rhs accesses from an aggregate assignment. They
258 are used to propagate subaccesses from rhs to lhs as long as they don't
259 conflict with what is already there. */
260 struct assign_link
262 struct access *lacc, *racc;
263 struct assign_link *next;
266 /* Alloc pool for allocating assign link structures. */
267 static alloc_pool link_pool;
269 /* Base (tree) -> Vector (VEC(access_p,heap) *) map. */
270 static struct pointer_map_t *base_access_vec;
272 /* Bitmap of candidates. */
273 static bitmap candidate_bitmap;
275 /* Bitmap of candidates which we should try to entirely scalarize away and
276 those which cannot be (because they are and need be used as a whole). */
277 static bitmap should_scalarize_away_bitmap, cannot_scalarize_away_bitmap;
279 /* Obstack for creation of fancy names. */
280 static struct obstack name_obstack;
282 /* Head of a linked list of accesses that need to have its subaccesses
283 propagated to their assignment counterparts. */
284 static struct access *work_queue_head;
286 /* Number of parameters of the analyzed function when doing early ipa SRA. */
287 static int func_param_count;
289 /* scan_function sets the following to true if it encounters a call to
290 __builtin_apply_args. */
291 static bool encountered_apply_args;
293 /* Set by scan_function when it finds a recursive call. */
294 static bool encountered_recursive_call;
296 /* Set by scan_function when it finds a recursive call with less actual
297 arguments than formal parameters.. */
298 static bool encountered_unchangable_recursive_call;
300 /* This is a table in which for each basic block and parameter there is a
301 distance (offset + size) in that parameter which is dereferenced and
302 accessed in that BB. */
303 static HOST_WIDE_INT *bb_dereferences;
304 /* Bitmap of BBs that can cause the function to "stop" progressing by
305 returning, throwing externally, looping infinitely or calling a function
306 which might abort etc.. */
307 static bitmap final_bbs;
309 /* Representative of no accesses at all. */
310 static struct access no_accesses_representant;
312 /* Predicate to test the special value. */
314 static inline bool
315 no_accesses_p (struct access *access)
317 return access == &no_accesses_representant;
320 /* Dump contents of ACCESS to file F in a human friendly way. If GRP is true,
321 representative fields are dumped, otherwise those which only describe the
322 individual access are. */
324 static struct
326 /* Number of processed aggregates is readily available in
327 analyze_all_variable_accesses and so is not stored here. */
329 /* Number of created scalar replacements. */
330 int replacements;
332 /* Number of times sra_modify_expr or sra_modify_assign themselves changed an
333 expression. */
334 int exprs;
336 /* Number of statements created by generate_subtree_copies. */
337 int subtree_copies;
339 /* Number of statements created by load_assign_lhs_subreplacements. */
340 int subreplacements;
342 /* Number of times sra_modify_assign has deleted a statement. */
343 int deleted;
345 /* Number of times sra_modify_assign has to deal with subaccesses of LHS and
346 RHS reparately due to type conversions or nonexistent matching
347 references. */
348 int separate_lhs_rhs_handling;
350 /* Number of parameters that were removed because they were unused. */
351 int deleted_unused_parameters;
353 /* Number of scalars passed as parameters by reference that have been
354 converted to be passed by value. */
355 int scalar_by_ref_to_by_val;
357 /* Number of aggregate parameters that were replaced by one or more of their
358 components. */
359 int aggregate_params_reduced;
361 /* Numbber of components created when splitting aggregate parameters. */
362 int param_reductions_created;
363 } sra_stats;
365 static void
366 dump_access (FILE *f, struct access *access, bool grp)
368 fprintf (f, "access { ");
369 fprintf (f, "base = (%d)'", DECL_UID (access->base));
370 print_generic_expr (f, access->base, 0);
371 fprintf (f, "', offset = " HOST_WIDE_INT_PRINT_DEC, access->offset);
372 fprintf (f, ", size = " HOST_WIDE_INT_PRINT_DEC, access->size);
373 fprintf (f, ", expr = ");
374 print_generic_expr (f, access->expr, 0);
375 fprintf (f, ", type = ");
376 print_generic_expr (f, access->type, 0);
377 if (grp)
378 fprintf (f, ", grp_read = %d, grp_write = %d, grp_assignment_read = %d, "
379 "grp_assignment_write = %d, grp_scalar_read = %d, "
380 "grp_scalar_write = %d, grp_total_scalarization = %d, "
381 "grp_hint = %d, grp_covered = %d, "
382 "grp_unscalarizable_region = %d, grp_unscalarized_data = %d, "
383 "grp_partial_lhs = %d, grp_to_be_replaced = %d, "
384 "grp_maybe_modified = %d, "
385 "grp_not_necessarilly_dereferenced = %d\n",
386 access->grp_read, access->grp_write, access->grp_assignment_read,
387 access->grp_assignment_write, access->grp_scalar_read,
388 access->grp_scalar_write, access->grp_total_scalarization,
389 access->grp_hint, access->grp_covered,
390 access->grp_unscalarizable_region, access->grp_unscalarized_data,
391 access->grp_partial_lhs, access->grp_to_be_replaced,
392 access->grp_maybe_modified,
393 access->grp_not_necessarilly_dereferenced);
394 else
395 fprintf (f, ", write = %d, grp_total_scalarization = %d, "
396 "grp_partial_lhs = %d\n",
397 access->write, access->grp_total_scalarization,
398 access->grp_partial_lhs);
401 /* Dump a subtree rooted in ACCESS to file F, indent by LEVEL. */
403 static void
404 dump_access_tree_1 (FILE *f, struct access *access, int level)
408 int i;
410 for (i = 0; i < level; i++)
411 fputs ("* ", dump_file);
413 dump_access (f, access, true);
415 if (access->first_child)
416 dump_access_tree_1 (f, access->first_child, level + 1);
418 access = access->next_sibling;
420 while (access);
423 /* Dump all access trees for a variable, given the pointer to the first root in
424 ACCESS. */
426 static void
427 dump_access_tree (FILE *f, struct access *access)
429 for (; access; access = access->next_grp)
430 dump_access_tree_1 (f, access, 0);
433 /* Return true iff ACC is non-NULL and has subaccesses. */
435 static inline bool
436 access_has_children_p (struct access *acc)
438 return acc && acc->first_child;
441 /* Return true iff ACC is (partly) covered by at least one replacement. */
443 static bool
444 access_has_replacements_p (struct access *acc)
446 struct access *child;
447 if (acc->grp_to_be_replaced)
448 return true;
449 for (child = acc->first_child; child; child = child->next_sibling)
450 if (access_has_replacements_p (child))
451 return true;
452 return false;
455 /* Return a vector of pointers to accesses for the variable given in BASE or
456 NULL if there is none. */
458 static VEC (access_p, heap) *
459 get_base_access_vector (tree base)
461 void **slot;
463 slot = pointer_map_contains (base_access_vec, base);
464 if (!slot)
465 return NULL;
466 else
467 return *(VEC (access_p, heap) **) slot;
470 /* Find an access with required OFFSET and SIZE in a subtree of accesses rooted
471 in ACCESS. Return NULL if it cannot be found. */
473 static struct access *
474 find_access_in_subtree (struct access *access, HOST_WIDE_INT offset,
475 HOST_WIDE_INT size)
477 while (access && (access->offset != offset || access->size != size))
479 struct access *child = access->first_child;
481 while (child && (child->offset + child->size <= offset))
482 child = child->next_sibling;
483 access = child;
486 return access;
489 /* Return the first group representative for DECL or NULL if none exists. */
491 static struct access *
492 get_first_repr_for_decl (tree base)
494 VEC (access_p, heap) *access_vec;
496 access_vec = get_base_access_vector (base);
497 if (!access_vec)
498 return NULL;
500 return VEC_index (access_p, access_vec, 0);
503 /* Find an access representative for the variable BASE and given OFFSET and
504 SIZE. Requires that access trees have already been built. Return NULL if
505 it cannot be found. */
507 static struct access *
508 get_var_base_offset_size_access (tree base, HOST_WIDE_INT offset,
509 HOST_WIDE_INT size)
511 struct access *access;
513 access = get_first_repr_for_decl (base);
514 while (access && (access->offset + access->size <= offset))
515 access = access->next_grp;
516 if (!access)
517 return NULL;
519 return find_access_in_subtree (access, offset, size);
522 /* Add LINK to the linked list of assign links of RACC. */
523 static void
524 add_link_to_rhs (struct access *racc, struct assign_link *link)
526 gcc_assert (link->racc == racc);
528 if (!racc->first_link)
530 gcc_assert (!racc->last_link);
531 racc->first_link = link;
533 else
534 racc->last_link->next = link;
536 racc->last_link = link;
537 link->next = NULL;
540 /* Move all link structures in their linked list in OLD_RACC to the linked list
541 in NEW_RACC. */
542 static void
543 relink_to_new_repr (struct access *new_racc, struct access *old_racc)
545 if (!old_racc->first_link)
547 gcc_assert (!old_racc->last_link);
548 return;
551 if (new_racc->first_link)
553 gcc_assert (!new_racc->last_link->next);
554 gcc_assert (!old_racc->last_link || !old_racc->last_link->next);
556 new_racc->last_link->next = old_racc->first_link;
557 new_racc->last_link = old_racc->last_link;
559 else
561 gcc_assert (!new_racc->last_link);
563 new_racc->first_link = old_racc->first_link;
564 new_racc->last_link = old_racc->last_link;
566 old_racc->first_link = old_racc->last_link = NULL;
569 /* Add ACCESS to the work queue (which is actually a stack). */
571 static void
572 add_access_to_work_queue (struct access *access)
574 if (!access->grp_queued)
576 gcc_assert (!access->next_queued);
577 access->next_queued = work_queue_head;
578 access->grp_queued = 1;
579 work_queue_head = access;
583 /* Pop an access from the work queue, and return it, assuming there is one. */
585 static struct access *
586 pop_access_from_work_queue (void)
588 struct access *access = work_queue_head;
590 work_queue_head = access->next_queued;
591 access->next_queued = NULL;
592 access->grp_queued = 0;
593 return access;
597 /* Allocate necessary structures. */
599 static void
600 sra_initialize (void)
602 candidate_bitmap = BITMAP_ALLOC (NULL);
603 should_scalarize_away_bitmap = BITMAP_ALLOC (NULL);
604 cannot_scalarize_away_bitmap = BITMAP_ALLOC (NULL);
605 gcc_obstack_init (&name_obstack);
606 access_pool = create_alloc_pool ("SRA accesses", sizeof (struct access), 16);
607 link_pool = create_alloc_pool ("SRA links", sizeof (struct assign_link), 16);
608 base_access_vec = pointer_map_create ();
609 memset (&sra_stats, 0, sizeof (sra_stats));
610 encountered_apply_args = false;
611 encountered_recursive_call = false;
612 encountered_unchangable_recursive_call = false;
615 /* Hook fed to pointer_map_traverse, deallocate stored vectors. */
617 static bool
618 delete_base_accesses (const void *key ATTRIBUTE_UNUSED, void **value,
619 void *data ATTRIBUTE_UNUSED)
621 VEC (access_p, heap) *access_vec;
622 access_vec = (VEC (access_p, heap) *) *value;
623 VEC_free (access_p, heap, access_vec);
625 return true;
628 /* Deallocate all general structures. */
630 static void
631 sra_deinitialize (void)
633 BITMAP_FREE (candidate_bitmap);
634 BITMAP_FREE (should_scalarize_away_bitmap);
635 BITMAP_FREE (cannot_scalarize_away_bitmap);
636 free_alloc_pool (access_pool);
637 free_alloc_pool (link_pool);
638 obstack_free (&name_obstack, NULL);
640 pointer_map_traverse (base_access_vec, delete_base_accesses, NULL);
641 pointer_map_destroy (base_access_vec);
644 /* Remove DECL from candidates for SRA and write REASON to the dump file if
645 there is one. */
646 static void
647 disqualify_candidate (tree decl, const char *reason)
649 bitmap_clear_bit (candidate_bitmap, DECL_UID (decl));
651 if (dump_file && (dump_flags & TDF_DETAILS))
653 fprintf (dump_file, "! Disqualifying ");
654 print_generic_expr (dump_file, decl, 0);
655 fprintf (dump_file, " - %s\n", reason);
659 /* Return true iff the type contains a field or an element which does not allow
660 scalarization. */
662 static bool
663 type_internals_preclude_sra_p (tree type, const char **msg)
665 tree fld;
666 tree et;
668 switch (TREE_CODE (type))
670 case RECORD_TYPE:
671 case UNION_TYPE:
672 case QUAL_UNION_TYPE:
673 for (fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
674 if (TREE_CODE (fld) == FIELD_DECL)
676 tree ft = TREE_TYPE (fld);
678 if (TREE_THIS_VOLATILE (fld))
680 *msg = "volatile structure field";
681 return true;
683 if (!DECL_FIELD_OFFSET (fld))
685 *msg = "no structure field offset";
686 return true;
688 if (!DECL_SIZE (fld))
690 *msg = "zero structure field size";
691 return true;
693 if (!host_integerp (DECL_FIELD_OFFSET (fld), 1))
695 *msg = "structure field offset not fixed";
696 return true;
698 if (!host_integerp (DECL_SIZE (fld), 1))
700 *msg = "structure field size not fixed";
701 return true;
703 if (AGGREGATE_TYPE_P (ft)
704 && int_bit_position (fld) % BITS_PER_UNIT != 0)
706 *msg = "structure field is bit field";
707 return true;
710 if (AGGREGATE_TYPE_P (ft) && type_internals_preclude_sra_p (ft, msg))
711 return true;
714 return false;
716 case ARRAY_TYPE:
717 et = TREE_TYPE (type);
719 if (TYPE_VOLATILE (et))
721 *msg = "element type is volatile";
722 return true;
725 if (AGGREGATE_TYPE_P (et) && type_internals_preclude_sra_p (et, msg))
726 return true;
728 return false;
730 default:
731 return false;
735 /* If T is an SSA_NAME, return NULL if it is not a default def or return its
736 base variable if it is. Return T if it is not an SSA_NAME. */
738 static tree
739 get_ssa_base_param (tree t)
741 if (TREE_CODE (t) == SSA_NAME)
743 if (SSA_NAME_IS_DEFAULT_DEF (t))
744 return SSA_NAME_VAR (t);
745 else
746 return NULL_TREE;
748 return t;
751 /* Mark a dereference of BASE of distance DIST in a basic block tht STMT
752 belongs to, unless the BB has already been marked as a potentially
753 final. */
755 static void
756 mark_parm_dereference (tree base, HOST_WIDE_INT dist, gimple stmt)
758 basic_block bb = gimple_bb (stmt);
759 int idx, parm_index = 0;
760 tree parm;
762 if (bitmap_bit_p (final_bbs, bb->index))
763 return;
765 for (parm = DECL_ARGUMENTS (current_function_decl);
766 parm && parm != base;
767 parm = DECL_CHAIN (parm))
768 parm_index++;
770 gcc_assert (parm_index < func_param_count);
772 idx = bb->index * func_param_count + parm_index;
773 if (bb_dereferences[idx] < dist)
774 bb_dereferences[idx] = dist;
777 /* Allocate an access structure for BASE, OFFSET and SIZE, clear it, fill in
778 the three fields. Also add it to the vector of accesses corresponding to
779 the base. Finally, return the new access. */
781 static struct access *
782 create_access_1 (tree base, HOST_WIDE_INT offset, HOST_WIDE_INT size)
784 VEC (access_p, heap) *vec;
785 struct access *access;
786 void **slot;
788 access = (struct access *) pool_alloc (access_pool);
789 memset (access, 0, sizeof (struct access));
790 access->base = base;
791 access->offset = offset;
792 access->size = size;
794 slot = pointer_map_contains (base_access_vec, base);
795 if (slot)
796 vec = (VEC (access_p, heap) *) *slot;
797 else
798 vec = VEC_alloc (access_p, heap, 32);
800 VEC_safe_push (access_p, heap, vec, access);
802 *((struct VEC (access_p,heap) **)
803 pointer_map_insert (base_access_vec, base)) = vec;
805 return access;
808 /* Create and insert access for EXPR. Return created access, or NULL if it is
809 not possible. */
811 static struct access *
812 create_access (tree expr, gimple stmt, bool write)
814 struct access *access;
815 HOST_WIDE_INT offset, size, max_size;
816 tree base = expr;
817 bool ptr, unscalarizable_region = false;
819 base = get_ref_base_and_extent (expr, &offset, &size, &max_size);
821 if (sra_mode == SRA_MODE_EARLY_IPA
822 && TREE_CODE (base) == MEM_REF)
824 base = get_ssa_base_param (TREE_OPERAND (base, 0));
825 if (!base)
826 return NULL;
827 ptr = true;
829 else
830 ptr = false;
832 if (!DECL_P (base) || !bitmap_bit_p (candidate_bitmap, DECL_UID (base)))
833 return NULL;
835 if (sra_mode == SRA_MODE_EARLY_IPA)
837 if (size < 0 || size != max_size)
839 disqualify_candidate (base, "Encountered a variable sized access.");
840 return NULL;
842 if (TREE_CODE (expr) == COMPONENT_REF
843 && DECL_BIT_FIELD (TREE_OPERAND (expr, 1)))
845 disqualify_candidate (base, "Encountered a bit-field access.");
846 return NULL;
848 gcc_checking_assert ((offset % BITS_PER_UNIT) == 0);
850 if (ptr)
851 mark_parm_dereference (base, offset + size, stmt);
853 else
855 if (size != max_size)
857 size = max_size;
858 unscalarizable_region = true;
860 if (size < 0)
862 disqualify_candidate (base, "Encountered an unconstrained access.");
863 return NULL;
867 access = create_access_1 (base, offset, size);
868 access->expr = expr;
869 access->type = TREE_TYPE (expr);
870 access->write = write;
871 access->grp_unscalarizable_region = unscalarizable_region;
872 access->stmt = stmt;
874 if (TREE_CODE (expr) == COMPONENT_REF
875 && DECL_NONADDRESSABLE_P (TREE_OPERAND (expr, 1)))
876 access->non_addressable = 1;
878 return access;
882 /* Return true iff TYPE is a RECORD_TYPE with fields that are either of gimple
883 register types or (recursively) records with only these two kinds of fields.
884 It also returns false if any of these records contains a bit-field. */
886 static bool
887 type_consists_of_records_p (tree type)
889 tree fld;
891 if (TREE_CODE (type) != RECORD_TYPE)
892 return false;
894 for (fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
895 if (TREE_CODE (fld) == FIELD_DECL)
897 tree ft = TREE_TYPE (fld);
899 if (DECL_BIT_FIELD (fld))
900 return false;
902 if (!is_gimple_reg_type (ft)
903 && !type_consists_of_records_p (ft))
904 return false;
907 return true;
910 /* Create total_scalarization accesses for all scalar type fields in DECL that
911 must be of a RECORD_TYPE conforming to type_consists_of_records_p. BASE
912 must be the top-most VAR_DECL representing the variable, OFFSET must be the
913 offset of DECL within BASE. REF must be the memory reference expression for
914 the given decl. */
916 static void
917 completely_scalarize_record (tree base, tree decl, HOST_WIDE_INT offset,
918 tree ref)
920 tree fld, decl_type = TREE_TYPE (decl);
922 for (fld = TYPE_FIELDS (decl_type); fld; fld = DECL_CHAIN (fld))
923 if (TREE_CODE (fld) == FIELD_DECL)
925 HOST_WIDE_INT pos = offset + int_bit_position (fld);
926 tree ft = TREE_TYPE (fld);
927 tree nref = build3 (COMPONENT_REF, TREE_TYPE (fld), ref, fld,
928 NULL_TREE);
930 if (is_gimple_reg_type (ft))
932 struct access *access;
933 HOST_WIDE_INT size;
935 size = tree_low_cst (DECL_SIZE (fld), 1);
936 access = create_access_1 (base, pos, size);
937 access->expr = nref;
938 access->type = ft;
939 access->grp_total_scalarization = 1;
940 /* Accesses for intraprocedural SRA can have their stmt NULL. */
942 else
943 completely_scalarize_record (base, fld, pos, nref);
947 /* Create total_scalarization accesses for all scalar type fields in VAR and
948 for VAR a a whole. VAR must be of a RECORD_TYPE conforming to
949 type_consists_of_records_p. */
951 static void
952 completely_scalarize_var (tree var)
954 HOST_WIDE_INT size = tree_low_cst (DECL_SIZE (var), 1);
955 struct access *access;
957 access = create_access_1 (var, 0, size);
958 access->expr = var;
959 access->type = TREE_TYPE (var);
960 access->grp_total_scalarization = 1;
962 completely_scalarize_record (var, var, 0, var);
965 /* Search the given tree for a declaration by skipping handled components and
966 exclude it from the candidates. */
968 static void
969 disqualify_base_of_expr (tree t, const char *reason)
971 t = get_base_address (t);
972 if (sra_mode == SRA_MODE_EARLY_IPA
973 && TREE_CODE (t) == MEM_REF)
974 t = get_ssa_base_param (TREE_OPERAND (t, 0));
976 if (t && DECL_P (t))
977 disqualify_candidate (t, reason);
980 /* Scan expression EXPR and create access structures for all accesses to
981 candidates for scalarization. Return the created access or NULL if none is
982 created. */
984 static struct access *
985 build_access_from_expr_1 (tree expr, gimple stmt, bool write)
987 struct access *ret = NULL;
988 bool partial_ref;
990 if (TREE_CODE (expr) == BIT_FIELD_REF
991 || TREE_CODE (expr) == IMAGPART_EXPR
992 || TREE_CODE (expr) == REALPART_EXPR)
994 expr = TREE_OPERAND (expr, 0);
995 partial_ref = true;
997 else
998 partial_ref = false;
1000 /* We need to dive through V_C_Es in order to get the size of its parameter
1001 and not the result type. Ada produces such statements. We are also
1002 capable of handling the topmost V_C_E but not any of those buried in other
1003 handled components. */
1004 if (TREE_CODE (expr) == VIEW_CONVERT_EXPR)
1005 expr = TREE_OPERAND (expr, 0);
1007 if (contains_view_convert_expr_p (expr))
1009 disqualify_base_of_expr (expr, "V_C_E under a different handled "
1010 "component.");
1011 return NULL;
1014 switch (TREE_CODE (expr))
1016 case MEM_REF:
1017 if (TREE_CODE (TREE_OPERAND (expr, 0)) != ADDR_EXPR
1018 && sra_mode != SRA_MODE_EARLY_IPA)
1019 return NULL;
1020 /* fall through */
1021 case VAR_DECL:
1022 case PARM_DECL:
1023 case RESULT_DECL:
1024 case COMPONENT_REF:
1025 case ARRAY_REF:
1026 case ARRAY_RANGE_REF:
1027 ret = create_access (expr, stmt, write);
1028 break;
1030 default:
1031 break;
1034 if (write && partial_ref && ret)
1035 ret->grp_partial_lhs = 1;
1037 return ret;
1040 /* Scan expression EXPR and create access structures for all accesses to
1041 candidates for scalarization. Return true if any access has been inserted.
1042 STMT must be the statement from which the expression is taken, WRITE must be
1043 true if the expression is a store and false otherwise. */
1045 static bool
1046 build_access_from_expr (tree expr, gimple stmt, bool write)
1048 struct access *access;
1050 access = build_access_from_expr_1 (expr, stmt, write);
1051 if (access)
1053 /* This means the aggregate is accesses as a whole in a way other than an
1054 assign statement and thus cannot be removed even if we had a scalar
1055 replacement for everything. */
1056 if (cannot_scalarize_away_bitmap)
1057 bitmap_set_bit (cannot_scalarize_away_bitmap, DECL_UID (access->base));
1058 return true;
1060 return false;
1063 /* Disqualify LHS and RHS for scalarization if STMT must end its basic block in
1064 modes in which it matters, return true iff they have been disqualified. RHS
1065 may be NULL, in that case ignore it. If we scalarize an aggregate in
1066 intra-SRA we may need to add statements after each statement. This is not
1067 possible if a statement unconditionally has to end the basic block. */
1068 static bool
1069 disqualify_ops_if_throwing_stmt (gimple stmt, tree lhs, tree rhs)
1071 if ((sra_mode == SRA_MODE_EARLY_INTRA || sra_mode == SRA_MODE_INTRA)
1072 && (stmt_can_throw_internal (stmt) || stmt_ends_bb_p (stmt)))
1074 disqualify_base_of_expr (lhs, "LHS of a throwing stmt.");
1075 if (rhs)
1076 disqualify_base_of_expr (rhs, "RHS of a throwing stmt.");
1077 return true;
1079 return false;
1082 /* Scan expressions occurring in STMT, create access structures for all accesses
1083 to candidates for scalarization and remove those candidates which occur in
1084 statements or expressions that prevent them from being split apart. Return
1085 true if any access has been inserted. */
1087 static bool
1088 build_accesses_from_assign (gimple stmt)
1090 tree lhs, rhs;
1091 struct access *lacc, *racc;
1093 if (!gimple_assign_single_p (stmt)
1094 /* Scope clobbers don't influence scalarization. */
1095 || gimple_clobber_p (stmt))
1096 return false;
1098 lhs = gimple_assign_lhs (stmt);
1099 rhs = gimple_assign_rhs1 (stmt);
1101 if (disqualify_ops_if_throwing_stmt (stmt, lhs, rhs))
1102 return false;
1104 racc = build_access_from_expr_1 (rhs, stmt, false);
1105 lacc = build_access_from_expr_1 (lhs, stmt, true);
1107 if (lacc)
1108 lacc->grp_assignment_write = 1;
1110 if (racc)
1112 racc->grp_assignment_read = 1;
1113 if (should_scalarize_away_bitmap && !gimple_has_volatile_ops (stmt)
1114 && !is_gimple_reg_type (racc->type))
1115 bitmap_set_bit (should_scalarize_away_bitmap, DECL_UID (racc->base));
1118 if (lacc && racc
1119 && (sra_mode == SRA_MODE_EARLY_INTRA || sra_mode == SRA_MODE_INTRA)
1120 && !lacc->grp_unscalarizable_region
1121 && !racc->grp_unscalarizable_region
1122 && AGGREGATE_TYPE_P (TREE_TYPE (lhs))
1123 && lacc->size == racc->size
1124 && useless_type_conversion_p (lacc->type, racc->type))
1126 struct assign_link *link;
1128 link = (struct assign_link *) pool_alloc (link_pool);
1129 memset (link, 0, sizeof (struct assign_link));
1131 link->lacc = lacc;
1132 link->racc = racc;
1134 add_link_to_rhs (racc, link);
1137 return lacc || racc;
1140 /* Callback of walk_stmt_load_store_addr_ops visit_addr used to determine
1141 GIMPLE_ASM operands with memory constrains which cannot be scalarized. */
1143 static bool
1144 asm_visit_addr (gimple stmt ATTRIBUTE_UNUSED, tree op,
1145 void *data ATTRIBUTE_UNUSED)
1147 op = get_base_address (op);
1148 if (op
1149 && DECL_P (op))
1150 disqualify_candidate (op, "Non-scalarizable GIMPLE_ASM operand.");
1152 return false;
1155 /* Return true iff callsite CALL has at least as many actual arguments as there
1156 are formal parameters of the function currently processed by IPA-SRA. */
1158 static inline bool
1159 callsite_has_enough_arguments_p (gimple call)
1161 return gimple_call_num_args (call) >= (unsigned) func_param_count;
1164 /* Scan function and look for interesting expressions and create access
1165 structures for them. Return true iff any access is created. */
1167 static bool
1168 scan_function (void)
1170 basic_block bb;
1171 bool ret = false;
1173 FOR_EACH_BB (bb)
1175 gimple_stmt_iterator gsi;
1176 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1178 gimple stmt = gsi_stmt (gsi);
1179 tree t;
1180 unsigned i;
1182 if (final_bbs && stmt_can_throw_external (stmt))
1183 bitmap_set_bit (final_bbs, bb->index);
1184 switch (gimple_code (stmt))
1186 case GIMPLE_RETURN:
1187 t = gimple_return_retval (stmt);
1188 if (t != NULL_TREE)
1189 ret |= build_access_from_expr (t, stmt, false);
1190 if (final_bbs)
1191 bitmap_set_bit (final_bbs, bb->index);
1192 break;
1194 case GIMPLE_ASSIGN:
1195 ret |= build_accesses_from_assign (stmt);
1196 break;
1198 case GIMPLE_CALL:
1199 for (i = 0; i < gimple_call_num_args (stmt); i++)
1200 ret |= build_access_from_expr (gimple_call_arg (stmt, i),
1201 stmt, false);
1203 if (sra_mode == SRA_MODE_EARLY_IPA)
1205 tree dest = gimple_call_fndecl (stmt);
1206 int flags = gimple_call_flags (stmt);
1208 if (dest)
1210 if (DECL_BUILT_IN_CLASS (dest) == BUILT_IN_NORMAL
1211 && DECL_FUNCTION_CODE (dest) == BUILT_IN_APPLY_ARGS)
1212 encountered_apply_args = true;
1213 if (cgraph_get_node (dest)
1214 == cgraph_get_node (current_function_decl))
1216 encountered_recursive_call = true;
1217 if (!callsite_has_enough_arguments_p (stmt))
1218 encountered_unchangable_recursive_call = true;
1222 if (final_bbs
1223 && (flags & (ECF_CONST | ECF_PURE)) == 0)
1224 bitmap_set_bit (final_bbs, bb->index);
1227 t = gimple_call_lhs (stmt);
1228 if (t && !disqualify_ops_if_throwing_stmt (stmt, t, NULL))
1229 ret |= build_access_from_expr (t, stmt, true);
1230 break;
1232 case GIMPLE_ASM:
1233 walk_stmt_load_store_addr_ops (stmt, NULL, NULL, NULL,
1234 asm_visit_addr);
1235 if (final_bbs)
1236 bitmap_set_bit (final_bbs, bb->index);
1238 for (i = 0; i < gimple_asm_ninputs (stmt); i++)
1240 t = TREE_VALUE (gimple_asm_input_op (stmt, i));
1241 ret |= build_access_from_expr (t, stmt, false);
1243 for (i = 0; i < gimple_asm_noutputs (stmt); i++)
1245 t = TREE_VALUE (gimple_asm_output_op (stmt, i));
1246 ret |= build_access_from_expr (t, stmt, true);
1248 break;
1250 default:
1251 break;
1256 return ret;
1259 /* Helper of QSORT function. There are pointers to accesses in the array. An
1260 access is considered smaller than another if it has smaller offset or if the
1261 offsets are the same but is size is bigger. */
1263 static int
1264 compare_access_positions (const void *a, const void *b)
1266 const access_p *fp1 = (const access_p *) a;
1267 const access_p *fp2 = (const access_p *) b;
1268 const access_p f1 = *fp1;
1269 const access_p f2 = *fp2;
1271 if (f1->offset != f2->offset)
1272 return f1->offset < f2->offset ? -1 : 1;
1274 if (f1->size == f2->size)
1276 if (f1->type == f2->type)
1277 return 0;
1278 /* Put any non-aggregate type before any aggregate type. */
1279 else if (!is_gimple_reg_type (f1->type)
1280 && is_gimple_reg_type (f2->type))
1281 return 1;
1282 else if (is_gimple_reg_type (f1->type)
1283 && !is_gimple_reg_type (f2->type))
1284 return -1;
1285 /* Put any complex or vector type before any other scalar type. */
1286 else if (TREE_CODE (f1->type) != COMPLEX_TYPE
1287 && TREE_CODE (f1->type) != VECTOR_TYPE
1288 && (TREE_CODE (f2->type) == COMPLEX_TYPE
1289 || TREE_CODE (f2->type) == VECTOR_TYPE))
1290 return 1;
1291 else if ((TREE_CODE (f1->type) == COMPLEX_TYPE
1292 || TREE_CODE (f1->type) == VECTOR_TYPE)
1293 && TREE_CODE (f2->type) != COMPLEX_TYPE
1294 && TREE_CODE (f2->type) != VECTOR_TYPE)
1295 return -1;
1296 /* Put the integral type with the bigger precision first. */
1297 else if (INTEGRAL_TYPE_P (f1->type)
1298 && INTEGRAL_TYPE_P (f2->type))
1299 return TYPE_PRECISION (f2->type) - TYPE_PRECISION (f1->type);
1300 /* Put any integral type with non-full precision last. */
1301 else if (INTEGRAL_TYPE_P (f1->type)
1302 && (TREE_INT_CST_LOW (TYPE_SIZE (f1->type))
1303 != TYPE_PRECISION (f1->type)))
1304 return 1;
1305 else if (INTEGRAL_TYPE_P (f2->type)
1306 && (TREE_INT_CST_LOW (TYPE_SIZE (f2->type))
1307 != TYPE_PRECISION (f2->type)))
1308 return -1;
1309 /* Stabilize the sort. */
1310 return TYPE_UID (f1->type) - TYPE_UID (f2->type);
1313 /* We want the bigger accesses first, thus the opposite operator in the next
1314 line: */
1315 return f1->size > f2->size ? -1 : 1;
1319 /* Append a name of the declaration to the name obstack. A helper function for
1320 make_fancy_name. */
1322 static void
1323 make_fancy_decl_name (tree decl)
1325 char buffer[32];
1327 tree name = DECL_NAME (decl);
1328 if (name)
1329 obstack_grow (&name_obstack, IDENTIFIER_POINTER (name),
1330 IDENTIFIER_LENGTH (name));
1331 else
1333 sprintf (buffer, "D%u", DECL_UID (decl));
1334 obstack_grow (&name_obstack, buffer, strlen (buffer));
1338 /* Helper for make_fancy_name. */
1340 static void
1341 make_fancy_name_1 (tree expr)
1343 char buffer[32];
1344 tree index;
1346 if (DECL_P (expr))
1348 make_fancy_decl_name (expr);
1349 return;
1352 switch (TREE_CODE (expr))
1354 case COMPONENT_REF:
1355 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1356 obstack_1grow (&name_obstack, '$');
1357 make_fancy_decl_name (TREE_OPERAND (expr, 1));
1358 break;
1360 case ARRAY_REF:
1361 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1362 obstack_1grow (&name_obstack, '$');
1363 /* Arrays with only one element may not have a constant as their
1364 index. */
1365 index = TREE_OPERAND (expr, 1);
1366 if (TREE_CODE (index) != INTEGER_CST)
1367 break;
1368 sprintf (buffer, HOST_WIDE_INT_PRINT_DEC, TREE_INT_CST_LOW (index));
1369 obstack_grow (&name_obstack, buffer, strlen (buffer));
1370 break;
1372 case ADDR_EXPR:
1373 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1374 break;
1376 case MEM_REF:
1377 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1378 if (!integer_zerop (TREE_OPERAND (expr, 1)))
1380 obstack_1grow (&name_obstack, '$');
1381 sprintf (buffer, HOST_WIDE_INT_PRINT_DEC,
1382 TREE_INT_CST_LOW (TREE_OPERAND (expr, 1)));
1383 obstack_grow (&name_obstack, buffer, strlen (buffer));
1385 break;
1387 case BIT_FIELD_REF:
1388 case REALPART_EXPR:
1389 case IMAGPART_EXPR:
1390 gcc_unreachable (); /* we treat these as scalars. */
1391 break;
1392 default:
1393 break;
1397 /* Create a human readable name for replacement variable of ACCESS. */
1399 static char *
1400 make_fancy_name (tree expr)
1402 make_fancy_name_1 (expr);
1403 obstack_1grow (&name_obstack, '\0');
1404 return XOBFINISH (&name_obstack, char *);
1407 /* Construct a MEM_REF that would reference a part of aggregate BASE of type
1408 EXP_TYPE at the given OFFSET. If BASE is something for which
1409 get_addr_base_and_unit_offset returns NULL, gsi must be non-NULL and is used
1410 to insert new statements either before or below the current one as specified
1411 by INSERT_AFTER. This function is not capable of handling bitfields. */
1413 tree
1414 build_ref_for_offset (location_t loc, tree base, HOST_WIDE_INT offset,
1415 tree exp_type, gimple_stmt_iterator *gsi,
1416 bool insert_after)
1418 tree prev_base = base;
1419 tree off;
1420 HOST_WIDE_INT base_offset;
1421 unsigned HOST_WIDE_INT misalign;
1422 unsigned int align;
1424 gcc_checking_assert (offset % BITS_PER_UNIT == 0);
1426 base = get_addr_base_and_unit_offset (base, &base_offset);
1428 /* get_addr_base_and_unit_offset returns NULL for references with a variable
1429 offset such as array[var_index]. */
1430 if (!base)
1432 gimple stmt;
1433 tree tmp, addr;
1435 gcc_checking_assert (gsi);
1436 tmp = create_tmp_reg (build_pointer_type (TREE_TYPE (prev_base)), NULL);
1437 add_referenced_var (tmp);
1438 tmp = make_ssa_name (tmp, NULL);
1439 addr = build_fold_addr_expr (unshare_expr (prev_base));
1440 STRIP_USELESS_TYPE_CONVERSION (addr);
1441 stmt = gimple_build_assign (tmp, addr);
1442 gimple_set_location (stmt, loc);
1443 SSA_NAME_DEF_STMT (tmp) = stmt;
1444 if (insert_after)
1445 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
1446 else
1447 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
1448 update_stmt (stmt);
1450 off = build_int_cst (reference_alias_ptr_type (prev_base),
1451 offset / BITS_PER_UNIT);
1452 base = tmp;
1454 else if (TREE_CODE (base) == MEM_REF)
1456 off = build_int_cst (TREE_TYPE (TREE_OPERAND (base, 1)),
1457 base_offset + offset / BITS_PER_UNIT);
1458 off = int_const_binop (PLUS_EXPR, TREE_OPERAND (base, 1), off);
1459 base = unshare_expr (TREE_OPERAND (base, 0));
1461 else
1463 off = build_int_cst (reference_alias_ptr_type (base),
1464 base_offset + offset / BITS_PER_UNIT);
1465 base = build_fold_addr_expr (unshare_expr (base));
1468 /* If prev_base were always an originally performed access
1469 we can extract more optimistic alignment information
1470 by looking at the access mode. That would constrain the
1471 alignment of base + base_offset which we would need to
1472 adjust according to offset. */
1473 if (!get_pointer_alignment_1 (base, &align, &misalign))
1475 gcc_assert (misalign == 0);
1476 if (TREE_CODE (prev_base) == MEM_REF
1477 || TREE_CODE (prev_base) == TARGET_MEM_REF)
1478 align = TYPE_ALIGN (TREE_TYPE (prev_base));
1480 misalign += (double_int_sext (tree_to_double_int (off),
1481 TYPE_PRECISION (TREE_TYPE (off))).low
1482 * BITS_PER_UNIT);
1483 misalign = misalign & (align - 1);
1484 if (misalign != 0)
1485 align = (misalign & -misalign);
1486 if (align < TYPE_ALIGN (exp_type))
1487 exp_type = build_aligned_type (exp_type, align);
1489 return fold_build2_loc (loc, MEM_REF, exp_type, base, off);
1492 /* Construct a memory reference to a part of an aggregate BASE at the given
1493 OFFSET and of the same type as MODEL. In case this is a reference to a
1494 bit-field, the function will replicate the last component_ref of model's
1495 expr to access it. GSI and INSERT_AFTER have the same meaning as in
1496 build_ref_for_offset. */
1498 static tree
1499 build_ref_for_model (location_t loc, tree base, HOST_WIDE_INT offset,
1500 struct access *model, gimple_stmt_iterator *gsi,
1501 bool insert_after)
1503 if (TREE_CODE (model->expr) == COMPONENT_REF
1504 && DECL_BIT_FIELD (TREE_OPERAND (model->expr, 1)))
1506 /* This access represents a bit-field. */
1507 tree t, exp_type, fld = TREE_OPERAND (model->expr, 1);
1509 offset -= int_bit_position (fld);
1510 exp_type = TREE_TYPE (TREE_OPERAND (model->expr, 0));
1511 t = build_ref_for_offset (loc, base, offset, exp_type, gsi, insert_after);
1512 return fold_build3_loc (loc, COMPONENT_REF, TREE_TYPE (fld), t, fld,
1513 NULL_TREE);
1515 else
1516 return build_ref_for_offset (loc, base, offset, model->type,
1517 gsi, insert_after);
1520 /* Construct a memory reference consisting of component_refs and array_refs to
1521 a part of an aggregate *RES (which is of type TYPE). The requested part
1522 should have type EXP_TYPE at be the given OFFSET. This function might not
1523 succeed, it returns true when it does and only then *RES points to something
1524 meaningful. This function should be used only to build expressions that we
1525 might need to present to user (e.g. in warnings). In all other situations,
1526 build_ref_for_model or build_ref_for_offset should be used instead. */
1528 static bool
1529 build_user_friendly_ref_for_offset (tree *res, tree type, HOST_WIDE_INT offset,
1530 tree exp_type)
1532 while (1)
1534 tree fld;
1535 tree tr_size, index, minidx;
1536 HOST_WIDE_INT el_size;
1538 if (offset == 0 && exp_type
1539 && types_compatible_p (exp_type, type))
1540 return true;
1542 switch (TREE_CODE (type))
1544 case UNION_TYPE:
1545 case QUAL_UNION_TYPE:
1546 case RECORD_TYPE:
1547 for (fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
1549 HOST_WIDE_INT pos, size;
1550 tree tr_pos, expr, *expr_ptr;
1552 if (TREE_CODE (fld) != FIELD_DECL)
1553 continue;
1555 tr_pos = bit_position (fld);
1556 if (!tr_pos || !host_integerp (tr_pos, 1))
1557 continue;
1558 pos = TREE_INT_CST_LOW (tr_pos);
1559 gcc_assert (TREE_CODE (type) == RECORD_TYPE || pos == 0);
1560 tr_size = DECL_SIZE (fld);
1561 if (!tr_size || !host_integerp (tr_size, 1))
1562 continue;
1563 size = TREE_INT_CST_LOW (tr_size);
1564 if (size == 0)
1566 if (pos != offset)
1567 continue;
1569 else if (pos > offset || (pos + size) <= offset)
1570 continue;
1572 expr = build3 (COMPONENT_REF, TREE_TYPE (fld), *res, fld,
1573 NULL_TREE);
1574 expr_ptr = &expr;
1575 if (build_user_friendly_ref_for_offset (expr_ptr, TREE_TYPE (fld),
1576 offset - pos, exp_type))
1578 *res = expr;
1579 return true;
1582 return false;
1584 case ARRAY_TYPE:
1585 tr_size = TYPE_SIZE (TREE_TYPE (type));
1586 if (!tr_size || !host_integerp (tr_size, 1))
1587 return false;
1588 el_size = tree_low_cst (tr_size, 1);
1590 minidx = TYPE_MIN_VALUE (TYPE_DOMAIN (type));
1591 if (TREE_CODE (minidx) != INTEGER_CST || el_size == 0)
1592 return false;
1593 index = build_int_cst (TYPE_DOMAIN (type), offset / el_size);
1594 if (!integer_zerop (minidx))
1595 index = int_const_binop (PLUS_EXPR, index, minidx);
1596 *res = build4 (ARRAY_REF, TREE_TYPE (type), *res, index,
1597 NULL_TREE, NULL_TREE);
1598 offset = offset % el_size;
1599 type = TREE_TYPE (type);
1600 break;
1602 default:
1603 if (offset != 0)
1604 return false;
1606 if (exp_type)
1607 return false;
1608 else
1609 return true;
1614 /* Return true iff TYPE is stdarg va_list type. */
1616 static inline bool
1617 is_va_list_type (tree type)
1619 return TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (va_list_type_node);
1622 /* Print message to dump file why a variable was rejected. */
1624 static void
1625 reject (tree var, const char *msg)
1627 if (dump_file && (dump_flags & TDF_DETAILS))
1629 fprintf (dump_file, "Rejected (%d): %s: ", DECL_UID (var), msg);
1630 print_generic_expr (dump_file, var, 0);
1631 fprintf (dump_file, "\n");
1635 /* The very first phase of intraprocedural SRA. It marks in candidate_bitmap
1636 those with type which is suitable for scalarization. */
1638 static bool
1639 find_var_candidates (void)
1641 tree var, type;
1642 referenced_var_iterator rvi;
1643 bool ret = false;
1644 const char *msg;
1646 FOR_EACH_REFERENCED_VAR (cfun, var, rvi)
1648 if (TREE_CODE (var) != VAR_DECL && TREE_CODE (var) != PARM_DECL)
1649 continue;
1650 type = TREE_TYPE (var);
1652 if (!AGGREGATE_TYPE_P (type))
1654 reject (var, "not aggregate");
1655 continue;
1657 if (needs_to_live_in_memory (var))
1659 reject (var, "needs to live in memory");
1660 continue;
1662 if (TREE_THIS_VOLATILE (var))
1664 reject (var, "is volatile");
1665 continue;
1667 if (!COMPLETE_TYPE_P (type))
1669 reject (var, "has incomplete type");
1670 continue;
1672 if (!host_integerp (TYPE_SIZE (type), 1))
1674 reject (var, "type size not fixed");
1675 continue;
1677 if (tree_low_cst (TYPE_SIZE (type), 1) == 0)
1679 reject (var, "type size is zero");
1680 continue;
1682 if (type_internals_preclude_sra_p (type, &msg))
1684 reject (var, msg);
1685 continue;
1687 if (/* Fix for PR 41089. tree-stdarg.c needs to have va_lists intact but
1688 we also want to schedule it rather late. Thus we ignore it in
1689 the early pass. */
1690 (sra_mode == SRA_MODE_EARLY_INTRA
1691 && is_va_list_type (type)))
1693 reject (var, "is va_list");
1694 continue;
1697 bitmap_set_bit (candidate_bitmap, DECL_UID (var));
1699 if (dump_file && (dump_flags & TDF_DETAILS))
1701 fprintf (dump_file, "Candidate (%d): ", DECL_UID (var));
1702 print_generic_expr (dump_file, var, 0);
1703 fprintf (dump_file, "\n");
1705 ret = true;
1708 return ret;
1711 /* Sort all accesses for the given variable, check for partial overlaps and
1712 return NULL if there are any. If there are none, pick a representative for
1713 each combination of offset and size and create a linked list out of them.
1714 Return the pointer to the first representative and make sure it is the first
1715 one in the vector of accesses. */
1717 static struct access *
1718 sort_and_splice_var_accesses (tree var)
1720 int i, j, access_count;
1721 struct access *res, **prev_acc_ptr = &res;
1722 VEC (access_p, heap) *access_vec;
1723 bool first = true;
1724 HOST_WIDE_INT low = -1, high = 0;
1726 access_vec = get_base_access_vector (var);
1727 if (!access_vec)
1728 return NULL;
1729 access_count = VEC_length (access_p, access_vec);
1731 /* Sort by <OFFSET, SIZE>. */
1732 VEC_qsort (access_p, access_vec, compare_access_positions);
1734 i = 0;
1735 while (i < access_count)
1737 struct access *access = VEC_index (access_p, access_vec, i);
1738 bool grp_write = access->write;
1739 bool grp_read = !access->write;
1740 bool grp_scalar_write = access->write
1741 && is_gimple_reg_type (access->type);
1742 bool grp_scalar_read = !access->write
1743 && is_gimple_reg_type (access->type);
1744 bool grp_assignment_read = access->grp_assignment_read;
1745 bool grp_assignment_write = access->grp_assignment_write;
1746 bool multiple_scalar_reads = false;
1747 bool total_scalarization = access->grp_total_scalarization;
1748 bool grp_partial_lhs = access->grp_partial_lhs;
1749 bool first_scalar = is_gimple_reg_type (access->type);
1750 bool unscalarizable_region = access->grp_unscalarizable_region;
1752 if (first || access->offset >= high)
1754 first = false;
1755 low = access->offset;
1756 high = access->offset + access->size;
1758 else if (access->offset > low && access->offset + access->size > high)
1759 return NULL;
1760 else
1761 gcc_assert (access->offset >= low
1762 && access->offset + access->size <= high);
1764 j = i + 1;
1765 while (j < access_count)
1767 struct access *ac2 = VEC_index (access_p, access_vec, j);
1768 if (ac2->offset != access->offset || ac2->size != access->size)
1769 break;
1770 if (ac2->write)
1772 grp_write = true;
1773 grp_scalar_write = (grp_scalar_write
1774 || is_gimple_reg_type (ac2->type));
1776 else
1778 grp_read = true;
1779 if (is_gimple_reg_type (ac2->type))
1781 if (grp_scalar_read)
1782 multiple_scalar_reads = true;
1783 else
1784 grp_scalar_read = true;
1787 grp_assignment_read |= ac2->grp_assignment_read;
1788 grp_assignment_write |= ac2->grp_assignment_write;
1789 grp_partial_lhs |= ac2->grp_partial_lhs;
1790 unscalarizable_region |= ac2->grp_unscalarizable_region;
1791 total_scalarization |= ac2->grp_total_scalarization;
1792 relink_to_new_repr (access, ac2);
1794 /* If there are both aggregate-type and scalar-type accesses with
1795 this combination of size and offset, the comparison function
1796 should have put the scalars first. */
1797 gcc_assert (first_scalar || !is_gimple_reg_type (ac2->type));
1798 ac2->group_representative = access;
1799 j++;
1802 i = j;
1804 access->group_representative = access;
1805 access->grp_write = grp_write;
1806 access->grp_read = grp_read;
1807 access->grp_scalar_read = grp_scalar_read;
1808 access->grp_scalar_write = grp_scalar_write;
1809 access->grp_assignment_read = grp_assignment_read;
1810 access->grp_assignment_write = grp_assignment_write;
1811 access->grp_hint = multiple_scalar_reads || total_scalarization;
1812 access->grp_total_scalarization = total_scalarization;
1813 access->grp_partial_lhs = grp_partial_lhs;
1814 access->grp_unscalarizable_region = unscalarizable_region;
1815 if (access->first_link)
1816 add_access_to_work_queue (access);
1818 *prev_acc_ptr = access;
1819 prev_acc_ptr = &access->next_grp;
1822 gcc_assert (res == VEC_index (access_p, access_vec, 0));
1823 return res;
1826 /* Create a variable for the given ACCESS which determines the type, name and a
1827 few other properties. Return the variable declaration and store it also to
1828 ACCESS->replacement. */
1830 static tree
1831 create_access_replacement (struct access *access, bool rename)
1833 tree repl;
1835 repl = create_tmp_var (access->type, "SR");
1836 add_referenced_var (repl);
1837 if (!access->grp_partial_lhs
1838 && rename)
1839 mark_sym_for_renaming (repl);
1841 if (TREE_CODE (access->type) == COMPLEX_TYPE
1842 || TREE_CODE (access->type) == VECTOR_TYPE)
1844 if (!access->grp_partial_lhs)
1845 DECL_GIMPLE_REG_P (repl) = 1;
1847 else if (access->grp_partial_lhs
1848 && is_gimple_reg_type (access->type))
1849 TREE_ADDRESSABLE (repl) = 1;
1851 DECL_SOURCE_LOCATION (repl) = DECL_SOURCE_LOCATION (access->base);
1852 DECL_ARTIFICIAL (repl) = 1;
1853 DECL_IGNORED_P (repl) = DECL_IGNORED_P (access->base);
1855 if (DECL_NAME (access->base)
1856 && !DECL_IGNORED_P (access->base)
1857 && !DECL_ARTIFICIAL (access->base))
1859 char *pretty_name = make_fancy_name (access->expr);
1860 tree debug_expr = unshare_expr (access->expr), d;
1862 DECL_NAME (repl) = get_identifier (pretty_name);
1863 obstack_free (&name_obstack, pretty_name);
1865 /* Get rid of any SSA_NAMEs embedded in debug_expr,
1866 as DECL_DEBUG_EXPR isn't considered when looking for still
1867 used SSA_NAMEs and thus they could be freed. All debug info
1868 generation cares is whether something is constant or variable
1869 and that get_ref_base_and_extent works properly on the
1870 expression. */
1871 for (d = debug_expr; handled_component_p (d); d = TREE_OPERAND (d, 0))
1872 switch (TREE_CODE (d))
1874 case ARRAY_REF:
1875 case ARRAY_RANGE_REF:
1876 if (TREE_OPERAND (d, 1)
1877 && TREE_CODE (TREE_OPERAND (d, 1)) == SSA_NAME)
1878 TREE_OPERAND (d, 1) = SSA_NAME_VAR (TREE_OPERAND (d, 1));
1879 if (TREE_OPERAND (d, 3)
1880 && TREE_CODE (TREE_OPERAND (d, 3)) == SSA_NAME)
1881 TREE_OPERAND (d, 3) = SSA_NAME_VAR (TREE_OPERAND (d, 3));
1882 /* FALLTHRU */
1883 case COMPONENT_REF:
1884 if (TREE_OPERAND (d, 2)
1885 && TREE_CODE (TREE_OPERAND (d, 2)) == SSA_NAME)
1886 TREE_OPERAND (d, 2) = SSA_NAME_VAR (TREE_OPERAND (d, 2));
1887 break;
1888 default:
1889 break;
1891 SET_DECL_DEBUG_EXPR (repl, debug_expr);
1892 DECL_DEBUG_EXPR_IS_FROM (repl) = 1;
1893 if (access->grp_no_warning)
1894 TREE_NO_WARNING (repl) = 1;
1895 else
1896 TREE_NO_WARNING (repl) = TREE_NO_WARNING (access->base);
1898 else
1899 TREE_NO_WARNING (repl) = 1;
1901 if (dump_file)
1903 fprintf (dump_file, "Created a replacement for ");
1904 print_generic_expr (dump_file, access->base, 0);
1905 fprintf (dump_file, " offset: %u, size: %u: ",
1906 (unsigned) access->offset, (unsigned) access->size);
1907 print_generic_expr (dump_file, repl, 0);
1908 fprintf (dump_file, "\n");
1910 sra_stats.replacements++;
1912 return repl;
1915 /* Return ACCESS scalar replacement, create it if it does not exist yet. */
1917 static inline tree
1918 get_access_replacement (struct access *access)
1920 gcc_assert (access->grp_to_be_replaced);
1922 if (!access->replacement_decl)
1923 access->replacement_decl = create_access_replacement (access, true);
1924 return access->replacement_decl;
1927 /* Return ACCESS scalar replacement, create it if it does not exist yet but do
1928 not mark it for renaming. */
1930 static inline tree
1931 get_unrenamed_access_replacement (struct access *access)
1933 gcc_assert (!access->grp_to_be_replaced);
1935 if (!access->replacement_decl)
1936 access->replacement_decl = create_access_replacement (access, false);
1937 return access->replacement_decl;
1941 /* Build a subtree of accesses rooted in *ACCESS, and move the pointer in the
1942 linked list along the way. Stop when *ACCESS is NULL or the access pointed
1943 to it is not "within" the root. Return false iff some accesses partially
1944 overlap. */
1946 static bool
1947 build_access_subtree (struct access **access)
1949 struct access *root = *access, *last_child = NULL;
1950 HOST_WIDE_INT limit = root->offset + root->size;
1952 *access = (*access)->next_grp;
1953 while (*access && (*access)->offset + (*access)->size <= limit)
1955 if (!last_child)
1956 root->first_child = *access;
1957 else
1958 last_child->next_sibling = *access;
1959 last_child = *access;
1961 if (!build_access_subtree (access))
1962 return false;
1965 if (*access && (*access)->offset < limit)
1966 return false;
1968 return true;
1971 /* Build a tree of access representatives, ACCESS is the pointer to the first
1972 one, others are linked in a list by the next_grp field. Return false iff
1973 some accesses partially overlap. */
1975 static bool
1976 build_access_trees (struct access *access)
1978 while (access)
1980 struct access *root = access;
1982 if (!build_access_subtree (&access))
1983 return false;
1984 root->next_grp = access;
1986 return true;
1989 /* Return true if expr contains some ARRAY_REFs into a variable bounded
1990 array. */
1992 static bool
1993 expr_with_var_bounded_array_refs_p (tree expr)
1995 while (handled_component_p (expr))
1997 if (TREE_CODE (expr) == ARRAY_REF
1998 && !host_integerp (array_ref_low_bound (expr), 0))
1999 return true;
2000 expr = TREE_OPERAND (expr, 0);
2002 return false;
2005 /* Analyze the subtree of accesses rooted in ROOT, scheduling replacements when
2006 both seeming beneficial and when ALLOW_REPLACEMENTS allows it. Also set all
2007 sorts of access flags appropriately along the way, notably always set
2008 grp_read and grp_assign_read according to MARK_READ and grp_write when
2009 MARK_WRITE is true.
2011 Creating a replacement for a scalar access is considered beneficial if its
2012 grp_hint is set (this means we are either attempting total scalarization or
2013 there is more than one direct read access) or according to the following
2014 table:
2016 Access written to through a scalar type (once or more times)
2018 | Written to in an assignment statement
2020 | | Access read as scalar _once_
2021 | | |
2022 | | | Read in an assignment statement
2023 | | | |
2024 | | | | Scalarize Comment
2025 -----------------------------------------------------------------------------
2026 0 0 0 0 No access for the scalar
2027 0 0 0 1 No access for the scalar
2028 0 0 1 0 No Single read - won't help
2029 0 0 1 1 No The same case
2030 0 1 0 0 No access for the scalar
2031 0 1 0 1 No access for the scalar
2032 0 1 1 0 Yes s = *g; return s.i;
2033 0 1 1 1 Yes The same case as above
2034 1 0 0 0 No Won't help
2035 1 0 0 1 Yes s.i = 1; *g = s;
2036 1 0 1 0 Yes s.i = 5; g = s.i;
2037 1 0 1 1 Yes The same case as above
2038 1 1 0 0 No Won't help.
2039 1 1 0 1 Yes s.i = 1; *g = s;
2040 1 1 1 0 Yes s = *g; return s.i;
2041 1 1 1 1 Yes Any of the above yeses */
2043 static bool
2044 analyze_access_subtree (struct access *root, struct access *parent,
2045 bool allow_replacements)
2047 struct access *child;
2048 HOST_WIDE_INT limit = root->offset + root->size;
2049 HOST_WIDE_INT covered_to = root->offset;
2050 bool scalar = is_gimple_reg_type (root->type);
2051 bool hole = false, sth_created = false;
2053 if (parent)
2055 if (parent->grp_read)
2056 root->grp_read = 1;
2057 if (parent->grp_assignment_read)
2058 root->grp_assignment_read = 1;
2059 if (parent->grp_write)
2060 root->grp_write = 1;
2061 if (parent->grp_assignment_write)
2062 root->grp_assignment_write = 1;
2063 if (parent->grp_total_scalarization)
2064 root->grp_total_scalarization = 1;
2067 if (root->grp_unscalarizable_region)
2068 allow_replacements = false;
2070 if (allow_replacements && expr_with_var_bounded_array_refs_p (root->expr))
2071 allow_replacements = false;
2073 for (child = root->first_child; child; child = child->next_sibling)
2075 hole |= covered_to < child->offset;
2076 sth_created |= analyze_access_subtree (child, root,
2077 allow_replacements && !scalar);
2079 root->grp_unscalarized_data |= child->grp_unscalarized_data;
2080 root->grp_total_scalarization &= child->grp_total_scalarization;
2081 if (child->grp_covered)
2082 covered_to += child->size;
2083 else
2084 hole = true;
2087 if (allow_replacements && scalar && !root->first_child
2088 && (root->grp_hint
2089 || ((root->grp_scalar_read || root->grp_assignment_read)
2090 && (root->grp_scalar_write || root->grp_assignment_write))))
2092 bool new_integer_type;
2093 /* Always create access replacements that cover the whole access.
2094 For integral types this means the precision has to match.
2095 Avoid assumptions based on the integral type kind, too. */
2096 if (INTEGRAL_TYPE_P (root->type)
2097 && (TREE_CODE (root->type) != INTEGER_TYPE
2098 || TYPE_PRECISION (root->type) != root->size)
2099 /* But leave bitfield accesses alone. */
2100 && (TREE_CODE (root->expr) != COMPONENT_REF
2101 || !DECL_BIT_FIELD (TREE_OPERAND (root->expr, 1))))
2103 tree rt = root->type;
2104 gcc_assert ((root->offset % BITS_PER_UNIT) == 0
2105 && (root->size % BITS_PER_UNIT) == 0);
2106 root->type = build_nonstandard_integer_type (root->size,
2107 TYPE_UNSIGNED (rt));
2108 root->expr = build_ref_for_offset (UNKNOWN_LOCATION,
2109 root->base, root->offset,
2110 root->type, NULL, false);
2111 new_integer_type = true;
2113 else
2114 new_integer_type = false;
2116 if (dump_file && (dump_flags & TDF_DETAILS))
2118 fprintf (dump_file, "Marking ");
2119 print_generic_expr (dump_file, root->base, 0);
2120 fprintf (dump_file, " offset: %u, size: %u ",
2121 (unsigned) root->offset, (unsigned) root->size);
2122 fprintf (dump_file, " to be replaced%s.\n",
2123 new_integer_type ? " with an integer": "");
2126 root->grp_to_be_replaced = 1;
2127 sth_created = true;
2128 hole = false;
2130 else
2132 if (covered_to < limit)
2133 hole = true;
2134 if (scalar)
2135 root->grp_total_scalarization = 0;
2138 if (sth_created
2139 && (!hole || root->grp_total_scalarization))
2141 root->grp_covered = 1;
2142 return true;
2144 if (root->grp_write || TREE_CODE (root->base) == PARM_DECL)
2145 root->grp_unscalarized_data = 1; /* not covered and written to */
2146 if (sth_created)
2147 return true;
2148 return false;
2151 /* Analyze all access trees linked by next_grp by the means of
2152 analyze_access_subtree. */
2153 static bool
2154 analyze_access_trees (struct access *access)
2156 bool ret = false;
2158 while (access)
2160 if (analyze_access_subtree (access, NULL, true))
2161 ret = true;
2162 access = access->next_grp;
2165 return ret;
2168 /* Return true iff a potential new child of LACC at offset OFFSET and with size
2169 SIZE would conflict with an already existing one. If exactly such a child
2170 already exists in LACC, store a pointer to it in EXACT_MATCH. */
2172 static bool
2173 child_would_conflict_in_lacc (struct access *lacc, HOST_WIDE_INT norm_offset,
2174 HOST_WIDE_INT size, struct access **exact_match)
2176 struct access *child;
2178 for (child = lacc->first_child; child; child = child->next_sibling)
2180 if (child->offset == norm_offset && child->size == size)
2182 *exact_match = child;
2183 return true;
2186 if (child->offset < norm_offset + size
2187 && child->offset + child->size > norm_offset)
2188 return true;
2191 return false;
2194 /* Create a new child access of PARENT, with all properties just like MODEL
2195 except for its offset and with its grp_write false and grp_read true.
2196 Return the new access or NULL if it cannot be created. Note that this access
2197 is created long after all splicing and sorting, it's not located in any
2198 access vector and is automatically a representative of its group. */
2200 static struct access *
2201 create_artificial_child_access (struct access *parent, struct access *model,
2202 HOST_WIDE_INT new_offset)
2204 struct access *access;
2205 struct access **child;
2206 tree expr = parent->base;
2208 gcc_assert (!model->grp_unscalarizable_region);
2210 access = (struct access *) pool_alloc (access_pool);
2211 memset (access, 0, sizeof (struct access));
2212 if (!build_user_friendly_ref_for_offset (&expr, TREE_TYPE (expr), new_offset,
2213 model->type))
2215 access->grp_no_warning = true;
2216 expr = build_ref_for_model (EXPR_LOCATION (parent->base), parent->base,
2217 new_offset, model, NULL, false);
2220 access->base = parent->base;
2221 access->expr = expr;
2222 access->offset = new_offset;
2223 access->size = model->size;
2224 access->type = model->type;
2225 access->grp_write = true;
2226 access->grp_read = false;
2228 child = &parent->first_child;
2229 while (*child && (*child)->offset < new_offset)
2230 child = &(*child)->next_sibling;
2232 access->next_sibling = *child;
2233 *child = access;
2235 return access;
2239 /* Propagate all subaccesses of RACC across an assignment link to LACC. Return
2240 true if any new subaccess was created. Additionally, if RACC is a scalar
2241 access but LACC is not, change the type of the latter, if possible. */
2243 static bool
2244 propagate_subaccesses_across_link (struct access *lacc, struct access *racc)
2246 struct access *rchild;
2247 HOST_WIDE_INT norm_delta = lacc->offset - racc->offset;
2248 bool ret = false;
2250 if (is_gimple_reg_type (lacc->type)
2251 || lacc->grp_unscalarizable_region
2252 || racc->grp_unscalarizable_region)
2253 return false;
2255 if (is_gimple_reg_type (racc->type))
2257 if (!lacc->first_child && !racc->first_child)
2259 tree t = lacc->base;
2261 lacc->type = racc->type;
2262 if (build_user_friendly_ref_for_offset (&t, TREE_TYPE (t),
2263 lacc->offset, racc->type))
2264 lacc->expr = t;
2265 else
2267 lacc->expr = build_ref_for_model (EXPR_LOCATION (lacc->base),
2268 lacc->base, lacc->offset,
2269 racc, NULL, false);
2270 lacc->grp_no_warning = true;
2273 return false;
2276 for (rchild = racc->first_child; rchild; rchild = rchild->next_sibling)
2278 struct access *new_acc = NULL;
2279 HOST_WIDE_INT norm_offset = rchild->offset + norm_delta;
2281 if (rchild->grp_unscalarizable_region)
2282 continue;
2284 if (child_would_conflict_in_lacc (lacc, norm_offset, rchild->size,
2285 &new_acc))
2287 if (new_acc)
2289 rchild->grp_hint = 1;
2290 new_acc->grp_hint |= new_acc->grp_read;
2291 if (rchild->first_child)
2292 ret |= propagate_subaccesses_across_link (new_acc, rchild);
2294 continue;
2297 rchild->grp_hint = 1;
2298 new_acc = create_artificial_child_access (lacc, rchild, norm_offset);
2299 if (new_acc)
2301 ret = true;
2302 if (racc->first_child)
2303 propagate_subaccesses_across_link (new_acc, rchild);
2307 return ret;
2310 /* Propagate all subaccesses across assignment links. */
2312 static void
2313 propagate_all_subaccesses (void)
2315 while (work_queue_head)
2317 struct access *racc = pop_access_from_work_queue ();
2318 struct assign_link *link;
2320 gcc_assert (racc->first_link);
2322 for (link = racc->first_link; link; link = link->next)
2324 struct access *lacc = link->lacc;
2326 if (!bitmap_bit_p (candidate_bitmap, DECL_UID (lacc->base)))
2327 continue;
2328 lacc = lacc->group_representative;
2329 if (propagate_subaccesses_across_link (lacc, racc)
2330 && lacc->first_link)
2331 add_access_to_work_queue (lacc);
2336 /* Go through all accesses collected throughout the (intraprocedural) analysis
2337 stage, exclude overlapping ones, identify representatives and build trees
2338 out of them, making decisions about scalarization on the way. Return true
2339 iff there are any to-be-scalarized variables after this stage. */
2341 static bool
2342 analyze_all_variable_accesses (void)
2344 int res = 0;
2345 bitmap tmp = BITMAP_ALLOC (NULL);
2346 bitmap_iterator bi;
2347 unsigned i, max_total_scalarization_size;
2349 max_total_scalarization_size = UNITS_PER_WORD * BITS_PER_UNIT
2350 * MOVE_RATIO (optimize_function_for_speed_p (cfun));
2352 EXECUTE_IF_SET_IN_BITMAP (candidate_bitmap, 0, i, bi)
2353 if (bitmap_bit_p (should_scalarize_away_bitmap, i)
2354 && !bitmap_bit_p (cannot_scalarize_away_bitmap, i))
2356 tree var = referenced_var (i);
2358 if (TREE_CODE (var) == VAR_DECL
2359 && type_consists_of_records_p (TREE_TYPE (var)))
2361 if ((unsigned) tree_low_cst (TYPE_SIZE (TREE_TYPE (var)), 1)
2362 <= max_total_scalarization_size)
2364 completely_scalarize_var (var);
2365 if (dump_file && (dump_flags & TDF_DETAILS))
2367 fprintf (dump_file, "Will attempt to totally scalarize ");
2368 print_generic_expr (dump_file, var, 0);
2369 fprintf (dump_file, " (UID: %u): \n", DECL_UID (var));
2372 else if (dump_file && (dump_flags & TDF_DETAILS))
2374 fprintf (dump_file, "Too big to totally scalarize: ");
2375 print_generic_expr (dump_file, var, 0);
2376 fprintf (dump_file, " (UID: %u)\n", DECL_UID (var));
2381 bitmap_copy (tmp, candidate_bitmap);
2382 EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, bi)
2384 tree var = referenced_var (i);
2385 struct access *access;
2387 access = sort_and_splice_var_accesses (var);
2388 if (!access || !build_access_trees (access))
2389 disqualify_candidate (var,
2390 "No or inhibitingly overlapping accesses.");
2393 propagate_all_subaccesses ();
2395 bitmap_copy (tmp, candidate_bitmap);
2396 EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, bi)
2398 tree var = referenced_var (i);
2399 struct access *access = get_first_repr_for_decl (var);
2401 if (analyze_access_trees (access))
2403 res++;
2404 if (dump_file && (dump_flags & TDF_DETAILS))
2406 fprintf (dump_file, "\nAccess trees for ");
2407 print_generic_expr (dump_file, var, 0);
2408 fprintf (dump_file, " (UID: %u): \n", DECL_UID (var));
2409 dump_access_tree (dump_file, access);
2410 fprintf (dump_file, "\n");
2413 else
2414 disqualify_candidate (var, "No scalar replacements to be created.");
2417 BITMAP_FREE (tmp);
2419 if (res)
2421 statistics_counter_event (cfun, "Scalarized aggregates", res);
2422 return true;
2424 else
2425 return false;
2428 /* Generate statements copying scalar replacements of accesses within a subtree
2429 into or out of AGG. ACCESS, all its children, siblings and their children
2430 are to be processed. AGG is an aggregate type expression (can be a
2431 declaration but does not have to be, it can for example also be a mem_ref or
2432 a series of handled components). TOP_OFFSET is the offset of the processed
2433 subtree which has to be subtracted from offsets of individual accesses to
2434 get corresponding offsets for AGG. If CHUNK_SIZE is non-null, copy only
2435 replacements in the interval <start_offset, start_offset + chunk_size>,
2436 otherwise copy all. GSI is a statement iterator used to place the new
2437 statements. WRITE should be true when the statements should write from AGG
2438 to the replacement and false if vice versa. if INSERT_AFTER is true, new
2439 statements will be added after the current statement in GSI, they will be
2440 added before the statement otherwise. */
2442 static void
2443 generate_subtree_copies (struct access *access, tree agg,
2444 HOST_WIDE_INT top_offset,
2445 HOST_WIDE_INT start_offset, HOST_WIDE_INT chunk_size,
2446 gimple_stmt_iterator *gsi, bool write,
2447 bool insert_after, location_t loc)
2451 if (chunk_size && access->offset >= start_offset + chunk_size)
2452 return;
2454 if (access->grp_to_be_replaced
2455 && (chunk_size == 0
2456 || access->offset + access->size > start_offset))
2458 tree expr, repl = get_access_replacement (access);
2459 gimple stmt;
2461 expr = build_ref_for_model (loc, agg, access->offset - top_offset,
2462 access, gsi, insert_after);
2464 if (write)
2466 if (access->grp_partial_lhs)
2467 expr = force_gimple_operand_gsi (gsi, expr, true, NULL_TREE,
2468 !insert_after,
2469 insert_after ? GSI_NEW_STMT
2470 : GSI_SAME_STMT);
2471 stmt = gimple_build_assign (repl, expr);
2473 else
2475 TREE_NO_WARNING (repl) = 1;
2476 if (access->grp_partial_lhs)
2477 repl = force_gimple_operand_gsi (gsi, repl, true, NULL_TREE,
2478 !insert_after,
2479 insert_after ? GSI_NEW_STMT
2480 : GSI_SAME_STMT);
2481 stmt = gimple_build_assign (expr, repl);
2483 gimple_set_location (stmt, loc);
2485 if (insert_after)
2486 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
2487 else
2488 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
2489 update_stmt (stmt);
2490 sra_stats.subtree_copies++;
2493 if (access->first_child)
2494 generate_subtree_copies (access->first_child, agg, top_offset,
2495 start_offset, chunk_size, gsi,
2496 write, insert_after, loc);
2498 access = access->next_sibling;
2500 while (access);
2503 /* Assign zero to all scalar replacements in an access subtree. ACCESS is the
2504 the root of the subtree to be processed. GSI is the statement iterator used
2505 for inserting statements which are added after the current statement if
2506 INSERT_AFTER is true or before it otherwise. */
2508 static void
2509 init_subtree_with_zero (struct access *access, gimple_stmt_iterator *gsi,
2510 bool insert_after, location_t loc)
2513 struct access *child;
2515 if (access->grp_to_be_replaced)
2517 gimple stmt;
2519 stmt = gimple_build_assign (get_access_replacement (access),
2520 build_zero_cst (access->type));
2521 if (insert_after)
2522 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
2523 else
2524 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
2525 update_stmt (stmt);
2526 gimple_set_location (stmt, loc);
2529 for (child = access->first_child; child; child = child->next_sibling)
2530 init_subtree_with_zero (child, gsi, insert_after, loc);
2533 /* Search for an access representative for the given expression EXPR and
2534 return it or NULL if it cannot be found. */
2536 static struct access *
2537 get_access_for_expr (tree expr)
2539 HOST_WIDE_INT offset, size, max_size;
2540 tree base;
2542 /* FIXME: This should not be necessary but Ada produces V_C_Es with a type of
2543 a different size than the size of its argument and we need the latter
2544 one. */
2545 if (TREE_CODE (expr) == VIEW_CONVERT_EXPR)
2546 expr = TREE_OPERAND (expr, 0);
2548 base = get_ref_base_and_extent (expr, &offset, &size, &max_size);
2549 if (max_size == -1 || !DECL_P (base))
2550 return NULL;
2552 if (!bitmap_bit_p (candidate_bitmap, DECL_UID (base)))
2553 return NULL;
2555 return get_var_base_offset_size_access (base, offset, max_size);
2558 /* Replace the expression EXPR with a scalar replacement if there is one and
2559 generate other statements to do type conversion or subtree copying if
2560 necessary. GSI is used to place newly created statements, WRITE is true if
2561 the expression is being written to (it is on a LHS of a statement or output
2562 in an assembly statement). */
2564 static bool
2565 sra_modify_expr (tree *expr, gimple_stmt_iterator *gsi, bool write)
2567 location_t loc;
2568 struct access *access;
2569 tree type, bfr;
2571 if (TREE_CODE (*expr) == BIT_FIELD_REF)
2573 bfr = *expr;
2574 expr = &TREE_OPERAND (*expr, 0);
2576 else
2577 bfr = NULL_TREE;
2579 if (TREE_CODE (*expr) == REALPART_EXPR || TREE_CODE (*expr) == IMAGPART_EXPR)
2580 expr = &TREE_OPERAND (*expr, 0);
2581 access = get_access_for_expr (*expr);
2582 if (!access)
2583 return false;
2584 type = TREE_TYPE (*expr);
2586 loc = gimple_location (gsi_stmt (*gsi));
2587 if (access->grp_to_be_replaced)
2589 tree repl = get_access_replacement (access);
2590 /* If we replace a non-register typed access simply use the original
2591 access expression to extract the scalar component afterwards.
2592 This happens if scalarizing a function return value or parameter
2593 like in gcc.c-torture/execute/20041124-1.c, 20050316-1.c and
2594 gcc.c-torture/compile/20011217-1.c.
2596 We also want to use this when accessing a complex or vector which can
2597 be accessed as a different type too, potentially creating a need for
2598 type conversion (see PR42196) and when scalarized unions are involved
2599 in assembler statements (see PR42398). */
2600 if (!useless_type_conversion_p (type, access->type))
2602 tree ref;
2604 ref = build_ref_for_model (loc, access->base, access->offset, access,
2605 NULL, false);
2607 if (write)
2609 gimple stmt;
2611 if (access->grp_partial_lhs)
2612 ref = force_gimple_operand_gsi (gsi, ref, true, NULL_TREE,
2613 false, GSI_NEW_STMT);
2614 stmt = gimple_build_assign (repl, ref);
2615 gimple_set_location (stmt, loc);
2616 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
2618 else
2620 gimple stmt;
2622 if (access->grp_partial_lhs)
2623 repl = force_gimple_operand_gsi (gsi, repl, true, NULL_TREE,
2624 true, GSI_SAME_STMT);
2625 stmt = gimple_build_assign (ref, repl);
2626 gimple_set_location (stmt, loc);
2627 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
2630 else
2631 *expr = repl;
2632 sra_stats.exprs++;
2635 if (access->first_child)
2637 HOST_WIDE_INT start_offset, chunk_size;
2638 if (bfr
2639 && host_integerp (TREE_OPERAND (bfr, 1), 1)
2640 && host_integerp (TREE_OPERAND (bfr, 2), 1))
2642 chunk_size = tree_low_cst (TREE_OPERAND (bfr, 1), 1);
2643 start_offset = access->offset
2644 + tree_low_cst (TREE_OPERAND (bfr, 2), 1);
2646 else
2647 start_offset = chunk_size = 0;
2649 generate_subtree_copies (access->first_child, access->base, 0,
2650 start_offset, chunk_size, gsi, write, write,
2651 loc);
2653 return true;
2656 /* Where scalar replacements of the RHS have been written to when a replacement
2657 of a LHS of an assigments cannot be direclty loaded from a replacement of
2658 the RHS. */
2659 enum unscalarized_data_handling { SRA_UDH_NONE, /* Nothing done so far. */
2660 SRA_UDH_RIGHT, /* Data flushed to the RHS. */
2661 SRA_UDH_LEFT }; /* Data flushed to the LHS. */
2663 /* Store all replacements in the access tree rooted in TOP_RACC either to their
2664 base aggregate if there are unscalarized data or directly to LHS of the
2665 statement that is pointed to by GSI otherwise. */
2667 static enum unscalarized_data_handling
2668 handle_unscalarized_data_in_subtree (struct access *top_racc,
2669 gimple_stmt_iterator *gsi)
2671 if (top_racc->grp_unscalarized_data)
2673 generate_subtree_copies (top_racc->first_child, top_racc->base, 0, 0, 0,
2674 gsi, false, false,
2675 gimple_location (gsi_stmt (*gsi)));
2676 return SRA_UDH_RIGHT;
2678 else
2680 tree lhs = gimple_assign_lhs (gsi_stmt (*gsi));
2681 generate_subtree_copies (top_racc->first_child, lhs, top_racc->offset,
2682 0, 0, gsi, false, false,
2683 gimple_location (gsi_stmt (*gsi)));
2684 return SRA_UDH_LEFT;
2689 /* Try to generate statements to load all sub-replacements in an access subtree
2690 formed by children of LACC from scalar replacements in the TOP_RACC subtree.
2691 If that is not possible, refresh the TOP_RACC base aggregate and load the
2692 accesses from it. LEFT_OFFSET is the offset of the left whole subtree being
2693 copied. NEW_GSI is stmt iterator used for statement insertions after the
2694 original assignment, OLD_GSI is used to insert statements before the
2695 assignment. *REFRESHED keeps the information whether we have needed to
2696 refresh replacements of the LHS and from which side of the assignments this
2697 takes place. */
2699 static void
2700 load_assign_lhs_subreplacements (struct access *lacc, struct access *top_racc,
2701 HOST_WIDE_INT left_offset,
2702 gimple_stmt_iterator *old_gsi,
2703 gimple_stmt_iterator *new_gsi,
2704 enum unscalarized_data_handling *refreshed)
2706 location_t loc = gimple_location (gsi_stmt (*old_gsi));
2707 for (lacc = lacc->first_child; lacc; lacc = lacc->next_sibling)
2709 if (lacc->grp_to_be_replaced)
2711 struct access *racc;
2712 HOST_WIDE_INT offset = lacc->offset - left_offset + top_racc->offset;
2713 gimple stmt;
2714 tree rhs;
2716 racc = find_access_in_subtree (top_racc, offset, lacc->size);
2717 if (racc && racc->grp_to_be_replaced)
2719 rhs = get_access_replacement (racc);
2720 if (!useless_type_conversion_p (lacc->type, racc->type))
2721 rhs = fold_build1_loc (loc, VIEW_CONVERT_EXPR, lacc->type, rhs);
2723 if (racc->grp_partial_lhs && lacc->grp_partial_lhs)
2724 rhs = force_gimple_operand_gsi (old_gsi, rhs, true, NULL_TREE,
2725 true, GSI_SAME_STMT);
2727 else
2729 /* No suitable access on the right hand side, need to load from
2730 the aggregate. See if we have to update it first... */
2731 if (*refreshed == SRA_UDH_NONE)
2732 *refreshed = handle_unscalarized_data_in_subtree (top_racc,
2733 old_gsi);
2735 if (*refreshed == SRA_UDH_LEFT)
2736 rhs = build_ref_for_model (loc, lacc->base, lacc->offset, lacc,
2737 new_gsi, true);
2738 else
2739 rhs = build_ref_for_model (loc, top_racc->base, offset, lacc,
2740 new_gsi, true);
2741 if (lacc->grp_partial_lhs)
2742 rhs = force_gimple_operand_gsi (new_gsi, rhs, true, NULL_TREE,
2743 false, GSI_NEW_STMT);
2746 stmt = gimple_build_assign (get_access_replacement (lacc), rhs);
2747 gsi_insert_after (new_gsi, stmt, GSI_NEW_STMT);
2748 gimple_set_location (stmt, loc);
2749 update_stmt (stmt);
2750 sra_stats.subreplacements++;
2752 else if (*refreshed == SRA_UDH_NONE
2753 && lacc->grp_read && !lacc->grp_covered)
2754 *refreshed = handle_unscalarized_data_in_subtree (top_racc,
2755 old_gsi);
2757 if (lacc->first_child)
2758 load_assign_lhs_subreplacements (lacc, top_racc, left_offset,
2759 old_gsi, new_gsi, refreshed);
2763 /* Result code for SRA assignment modification. */
2764 enum assignment_mod_result { SRA_AM_NONE, /* nothing done for the stmt */
2765 SRA_AM_MODIFIED, /* stmt changed but not
2766 removed */
2767 SRA_AM_REMOVED }; /* stmt eliminated */
2769 /* Modify assignments with a CONSTRUCTOR on their RHS. STMT contains a pointer
2770 to the assignment and GSI is the statement iterator pointing at it. Returns
2771 the same values as sra_modify_assign. */
2773 static enum assignment_mod_result
2774 sra_modify_constructor_assign (gimple *stmt, gimple_stmt_iterator *gsi)
2776 tree lhs = gimple_assign_lhs (*stmt);
2777 struct access *acc;
2778 location_t loc;
2780 acc = get_access_for_expr (lhs);
2781 if (!acc)
2782 return SRA_AM_NONE;
2784 if (gimple_clobber_p (*stmt))
2786 /* Remove clobbers of fully scalarized variables, otherwise
2787 do nothing. */
2788 if (acc->grp_covered)
2790 unlink_stmt_vdef (*stmt);
2791 gsi_remove (gsi, true);
2792 release_defs (*stmt);
2793 return SRA_AM_REMOVED;
2795 else
2796 return SRA_AM_NONE;
2799 loc = gimple_location (*stmt);
2800 if (VEC_length (constructor_elt,
2801 CONSTRUCTOR_ELTS (gimple_assign_rhs1 (*stmt))) > 0)
2803 /* I have never seen this code path trigger but if it can happen the
2804 following should handle it gracefully. */
2805 if (access_has_children_p (acc))
2806 generate_subtree_copies (acc->first_child, acc->base, 0, 0, 0, gsi,
2807 true, true, loc);
2808 return SRA_AM_MODIFIED;
2811 if (acc->grp_covered)
2813 init_subtree_with_zero (acc, gsi, false, loc);
2814 unlink_stmt_vdef (*stmt);
2815 gsi_remove (gsi, true);
2816 release_defs (*stmt);
2817 return SRA_AM_REMOVED;
2819 else
2821 init_subtree_with_zero (acc, gsi, true, loc);
2822 return SRA_AM_MODIFIED;
2826 /* Create and return a new suitable default definition SSA_NAME for RACC which
2827 is an access describing an uninitialized part of an aggregate that is being
2828 loaded. */
2830 static tree
2831 get_repl_default_def_ssa_name (struct access *racc)
2833 tree repl, decl;
2835 decl = get_unrenamed_access_replacement (racc);
2837 repl = gimple_default_def (cfun, decl);
2838 if (!repl)
2840 repl = make_ssa_name (decl, gimple_build_nop ());
2841 set_default_def (decl, repl);
2844 return repl;
2847 /* Return true if REF has a COMPONENT_REF with a bit-field field declaration
2848 somewhere in it. */
2850 static inline bool
2851 contains_bitfld_comp_ref_p (const_tree ref)
2853 while (handled_component_p (ref))
2855 if (TREE_CODE (ref) == COMPONENT_REF
2856 && DECL_BIT_FIELD (TREE_OPERAND (ref, 1)))
2857 return true;
2858 ref = TREE_OPERAND (ref, 0);
2861 return false;
2864 /* Return true if REF has an VIEW_CONVERT_EXPR or a COMPONENT_REF with a
2865 bit-field field declaration somewhere in it. */
2867 static inline bool
2868 contains_vce_or_bfcref_p (const_tree ref)
2870 while (handled_component_p (ref))
2872 if (TREE_CODE (ref) == VIEW_CONVERT_EXPR
2873 || (TREE_CODE (ref) == COMPONENT_REF
2874 && DECL_BIT_FIELD (TREE_OPERAND (ref, 1))))
2875 return true;
2876 ref = TREE_OPERAND (ref, 0);
2879 return false;
2882 /* Examine both sides of the assignment statement pointed to by STMT, replace
2883 them with a scalare replacement if there is one and generate copying of
2884 replacements if scalarized aggregates have been used in the assignment. GSI
2885 is used to hold generated statements for type conversions and subtree
2886 copying. */
2888 static enum assignment_mod_result
2889 sra_modify_assign (gimple *stmt, gimple_stmt_iterator *gsi)
2891 struct access *lacc, *racc;
2892 tree lhs, rhs;
2893 bool modify_this_stmt = false;
2894 bool force_gimple_rhs = false;
2895 location_t loc;
2896 gimple_stmt_iterator orig_gsi = *gsi;
2898 if (!gimple_assign_single_p (*stmt))
2899 return SRA_AM_NONE;
2900 lhs = gimple_assign_lhs (*stmt);
2901 rhs = gimple_assign_rhs1 (*stmt);
2903 if (TREE_CODE (rhs) == CONSTRUCTOR)
2904 return sra_modify_constructor_assign (stmt, gsi);
2906 if (TREE_CODE (rhs) == REALPART_EXPR || TREE_CODE (lhs) == REALPART_EXPR
2907 || TREE_CODE (rhs) == IMAGPART_EXPR || TREE_CODE (lhs) == IMAGPART_EXPR
2908 || TREE_CODE (rhs) == BIT_FIELD_REF || TREE_CODE (lhs) == BIT_FIELD_REF)
2910 modify_this_stmt = sra_modify_expr (gimple_assign_rhs1_ptr (*stmt),
2911 gsi, false);
2912 modify_this_stmt |= sra_modify_expr (gimple_assign_lhs_ptr (*stmt),
2913 gsi, true);
2914 return modify_this_stmt ? SRA_AM_MODIFIED : SRA_AM_NONE;
2917 lacc = get_access_for_expr (lhs);
2918 racc = get_access_for_expr (rhs);
2919 if (!lacc && !racc)
2920 return SRA_AM_NONE;
2922 loc = gimple_location (*stmt);
2923 if (lacc && lacc->grp_to_be_replaced)
2925 lhs = get_access_replacement (lacc);
2926 gimple_assign_set_lhs (*stmt, lhs);
2927 modify_this_stmt = true;
2928 if (lacc->grp_partial_lhs)
2929 force_gimple_rhs = true;
2930 sra_stats.exprs++;
2933 if (racc && racc->grp_to_be_replaced)
2935 rhs = get_access_replacement (racc);
2936 modify_this_stmt = true;
2937 if (racc->grp_partial_lhs)
2938 force_gimple_rhs = true;
2939 sra_stats.exprs++;
2941 else if (racc
2942 && !racc->grp_unscalarized_data
2943 && TREE_CODE (lhs) == SSA_NAME
2944 && !access_has_replacements_p (racc))
2946 rhs = get_repl_default_def_ssa_name (racc);
2947 modify_this_stmt = true;
2948 sra_stats.exprs++;
2951 if (modify_this_stmt)
2953 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (rhs)))
2955 /* If we can avoid creating a VIEW_CONVERT_EXPR do so.
2956 ??? This should move to fold_stmt which we simply should
2957 call after building a VIEW_CONVERT_EXPR here. */
2958 if (AGGREGATE_TYPE_P (TREE_TYPE (lhs))
2959 && !contains_bitfld_comp_ref_p (lhs)
2960 && !access_has_children_p (lacc))
2962 lhs = build_ref_for_model (loc, lhs, 0, racc, gsi, false);
2963 gimple_assign_set_lhs (*stmt, lhs);
2965 else if (AGGREGATE_TYPE_P (TREE_TYPE (rhs))
2966 && !contains_vce_or_bfcref_p (rhs)
2967 && !access_has_children_p (racc))
2968 rhs = build_ref_for_model (loc, rhs, 0, lacc, gsi, false);
2970 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (rhs)))
2972 rhs = fold_build1_loc (loc, VIEW_CONVERT_EXPR, TREE_TYPE (lhs),
2973 rhs);
2974 if (is_gimple_reg_type (TREE_TYPE (lhs))
2975 && TREE_CODE (lhs) != SSA_NAME)
2976 force_gimple_rhs = true;
2981 /* From this point on, the function deals with assignments in between
2982 aggregates when at least one has scalar reductions of some of its
2983 components. There are three possible scenarios: Both the LHS and RHS have
2984 to-be-scalarized components, 2) only the RHS has or 3) only the LHS has.
2986 In the first case, we would like to load the LHS components from RHS
2987 components whenever possible. If that is not possible, we would like to
2988 read it directly from the RHS (after updating it by storing in it its own
2989 components). If there are some necessary unscalarized data in the LHS,
2990 those will be loaded by the original assignment too. If neither of these
2991 cases happen, the original statement can be removed. Most of this is done
2992 by load_assign_lhs_subreplacements.
2994 In the second case, we would like to store all RHS scalarized components
2995 directly into LHS and if they cover the aggregate completely, remove the
2996 statement too. In the third case, we want the LHS components to be loaded
2997 directly from the RHS (DSE will remove the original statement if it
2998 becomes redundant).
3000 This is a bit complex but manageable when types match and when unions do
3001 not cause confusion in a way that we cannot really load a component of LHS
3002 from the RHS or vice versa (the access representing this level can have
3003 subaccesses that are accessible only through a different union field at a
3004 higher level - different from the one used in the examined expression).
3005 Unions are fun.
3007 Therefore, I specially handle a fourth case, happening when there is a
3008 specific type cast or it is impossible to locate a scalarized subaccess on
3009 the other side of the expression. If that happens, I simply "refresh" the
3010 RHS by storing in it is scalarized components leave the original statement
3011 there to do the copying and then load the scalar replacements of the LHS.
3012 This is what the first branch does. */
3014 if (modify_this_stmt
3015 || gimple_has_volatile_ops (*stmt)
3016 || contains_vce_or_bfcref_p (rhs)
3017 || contains_vce_or_bfcref_p (lhs))
3019 if (access_has_children_p (racc))
3020 generate_subtree_copies (racc->first_child, racc->base, 0, 0, 0,
3021 gsi, false, false, loc);
3022 if (access_has_children_p (lacc))
3023 generate_subtree_copies (lacc->first_child, lacc->base, 0, 0, 0,
3024 gsi, true, true, loc);
3025 sra_stats.separate_lhs_rhs_handling++;
3027 /* This gimplification must be done after generate_subtree_copies,
3028 lest we insert the subtree copies in the middle of the gimplified
3029 sequence. */
3030 if (force_gimple_rhs)
3031 rhs = force_gimple_operand_gsi (&orig_gsi, rhs, true, NULL_TREE,
3032 true, GSI_SAME_STMT);
3033 if (gimple_assign_rhs1 (*stmt) != rhs)
3035 modify_this_stmt = true;
3036 gimple_assign_set_rhs_from_tree (&orig_gsi, rhs);
3037 gcc_assert (*stmt == gsi_stmt (orig_gsi));
3040 return modify_this_stmt ? SRA_AM_MODIFIED : SRA_AM_NONE;
3042 else
3044 if (access_has_children_p (lacc)
3045 && access_has_children_p (racc)
3046 /* When an access represents an unscalarizable region, it usually
3047 represents accesses with variable offset and thus must not be used
3048 to generate new memory accesses. */
3049 && !lacc->grp_unscalarizable_region
3050 && !racc->grp_unscalarizable_region)
3052 gimple_stmt_iterator orig_gsi = *gsi;
3053 enum unscalarized_data_handling refreshed;
3055 if (lacc->grp_read && !lacc->grp_covered)
3056 refreshed = handle_unscalarized_data_in_subtree (racc, gsi);
3057 else
3058 refreshed = SRA_UDH_NONE;
3060 load_assign_lhs_subreplacements (lacc, racc, lacc->offset,
3061 &orig_gsi, gsi, &refreshed);
3062 if (refreshed != SRA_UDH_RIGHT)
3064 gsi_next (gsi);
3065 unlink_stmt_vdef (*stmt);
3066 gsi_remove (&orig_gsi, true);
3067 release_defs (*stmt);
3068 sra_stats.deleted++;
3069 return SRA_AM_REMOVED;
3072 else
3074 if (access_has_children_p (racc)
3075 && !racc->grp_unscalarized_data)
3077 if (dump_file)
3079 fprintf (dump_file, "Removing load: ");
3080 print_gimple_stmt (dump_file, *stmt, 0, 0);
3082 generate_subtree_copies (racc->first_child, lhs,
3083 racc->offset, 0, 0, gsi,
3084 false, false, loc);
3085 gcc_assert (*stmt == gsi_stmt (*gsi));
3086 unlink_stmt_vdef (*stmt);
3087 gsi_remove (gsi, true);
3088 release_defs (*stmt);
3089 sra_stats.deleted++;
3090 return SRA_AM_REMOVED;
3092 /* Restore the aggregate RHS from its components so the
3093 prevailing aggregate copy does the right thing. */
3094 if (access_has_children_p (racc))
3095 generate_subtree_copies (racc->first_child, racc->base, 0, 0, 0,
3096 gsi, false, false, loc);
3097 /* Re-load the components of the aggregate copy destination.
3098 But use the RHS aggregate to load from to expose more
3099 optimization opportunities. */
3100 if (access_has_children_p (lacc))
3101 generate_subtree_copies (lacc->first_child, rhs, lacc->offset,
3102 0, 0, gsi, true, true, loc);
3105 return SRA_AM_NONE;
3109 /* Traverse the function body and all modifications as decided in
3110 analyze_all_variable_accesses. Return true iff the CFG has been
3111 changed. */
3113 static bool
3114 sra_modify_function_body (void)
3116 bool cfg_changed = false;
3117 basic_block bb;
3119 FOR_EACH_BB (bb)
3121 gimple_stmt_iterator gsi = gsi_start_bb (bb);
3122 while (!gsi_end_p (gsi))
3124 gimple stmt = gsi_stmt (gsi);
3125 enum assignment_mod_result assign_result;
3126 bool modified = false, deleted = false;
3127 tree *t;
3128 unsigned i;
3130 switch (gimple_code (stmt))
3132 case GIMPLE_RETURN:
3133 t = gimple_return_retval_ptr (stmt);
3134 if (*t != NULL_TREE)
3135 modified |= sra_modify_expr (t, &gsi, false);
3136 break;
3138 case GIMPLE_ASSIGN:
3139 assign_result = sra_modify_assign (&stmt, &gsi);
3140 modified |= assign_result == SRA_AM_MODIFIED;
3141 deleted = assign_result == SRA_AM_REMOVED;
3142 break;
3144 case GIMPLE_CALL:
3145 /* Operands must be processed before the lhs. */
3146 for (i = 0; i < gimple_call_num_args (stmt); i++)
3148 t = gimple_call_arg_ptr (stmt, i);
3149 modified |= sra_modify_expr (t, &gsi, false);
3152 if (gimple_call_lhs (stmt))
3154 t = gimple_call_lhs_ptr (stmt);
3155 modified |= sra_modify_expr (t, &gsi, true);
3157 break;
3159 case GIMPLE_ASM:
3160 for (i = 0; i < gimple_asm_ninputs (stmt); i++)
3162 t = &TREE_VALUE (gimple_asm_input_op (stmt, i));
3163 modified |= sra_modify_expr (t, &gsi, false);
3165 for (i = 0; i < gimple_asm_noutputs (stmt); i++)
3167 t = &TREE_VALUE (gimple_asm_output_op (stmt, i));
3168 modified |= sra_modify_expr (t, &gsi, true);
3170 break;
3172 default:
3173 break;
3176 if (modified)
3178 update_stmt (stmt);
3179 if (maybe_clean_eh_stmt (stmt)
3180 && gimple_purge_dead_eh_edges (gimple_bb (stmt)))
3181 cfg_changed = true;
3183 if (!deleted)
3184 gsi_next (&gsi);
3188 return cfg_changed;
3191 /* Generate statements initializing scalar replacements of parts of function
3192 parameters. */
3194 static void
3195 initialize_parameter_reductions (void)
3197 gimple_stmt_iterator gsi;
3198 gimple_seq seq = NULL;
3199 tree parm;
3201 gsi = gsi_start (seq);
3202 for (parm = DECL_ARGUMENTS (current_function_decl);
3203 parm;
3204 parm = DECL_CHAIN (parm))
3206 VEC (access_p, heap) *access_vec;
3207 struct access *access;
3209 if (!bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
3210 continue;
3211 access_vec = get_base_access_vector (parm);
3212 if (!access_vec)
3213 continue;
3215 for (access = VEC_index (access_p, access_vec, 0);
3216 access;
3217 access = access->next_grp)
3218 generate_subtree_copies (access, parm, 0, 0, 0, &gsi, true, true,
3219 EXPR_LOCATION (parm));
3222 seq = gsi_seq (gsi);
3223 if (seq)
3224 gsi_insert_seq_on_edge_immediate (single_succ_edge (ENTRY_BLOCK_PTR), seq);
3227 /* The "main" function of intraprocedural SRA passes. Runs the analysis and if
3228 it reveals there are components of some aggregates to be scalarized, it runs
3229 the required transformations. */
3230 static unsigned int
3231 perform_intra_sra (void)
3233 int ret = 0;
3234 sra_initialize ();
3236 if (!find_var_candidates ())
3237 goto out;
3239 if (!scan_function ())
3240 goto out;
3242 if (!analyze_all_variable_accesses ())
3243 goto out;
3245 if (sra_modify_function_body ())
3246 ret = TODO_update_ssa | TODO_cleanup_cfg;
3247 else
3248 ret = TODO_update_ssa;
3249 initialize_parameter_reductions ();
3251 statistics_counter_event (cfun, "Scalar replacements created",
3252 sra_stats.replacements);
3253 statistics_counter_event (cfun, "Modified expressions", sra_stats.exprs);
3254 statistics_counter_event (cfun, "Subtree copy stmts",
3255 sra_stats.subtree_copies);
3256 statistics_counter_event (cfun, "Subreplacement stmts",
3257 sra_stats.subreplacements);
3258 statistics_counter_event (cfun, "Deleted stmts", sra_stats.deleted);
3259 statistics_counter_event (cfun, "Separate LHS and RHS handling",
3260 sra_stats.separate_lhs_rhs_handling);
3262 out:
3263 sra_deinitialize ();
3264 return ret;
3267 /* Perform early intraprocedural SRA. */
3268 static unsigned int
3269 early_intra_sra (void)
3271 sra_mode = SRA_MODE_EARLY_INTRA;
3272 return perform_intra_sra ();
3275 /* Perform "late" intraprocedural SRA. */
3276 static unsigned int
3277 late_intra_sra (void)
3279 sra_mode = SRA_MODE_INTRA;
3280 return perform_intra_sra ();
3284 static bool
3285 gate_intra_sra (void)
3287 return flag_tree_sra != 0 && dbg_cnt (tree_sra);
3291 struct gimple_opt_pass pass_sra_early =
3294 GIMPLE_PASS,
3295 "esra", /* name */
3296 gate_intra_sra, /* gate */
3297 early_intra_sra, /* execute */
3298 NULL, /* sub */
3299 NULL, /* next */
3300 0, /* static_pass_number */
3301 TV_TREE_SRA, /* tv_id */
3302 PROP_cfg | PROP_ssa, /* properties_required */
3303 0, /* properties_provided */
3304 0, /* properties_destroyed */
3305 0, /* todo_flags_start */
3306 TODO_update_ssa
3307 | TODO_ggc_collect
3308 | TODO_verify_ssa /* todo_flags_finish */
3312 struct gimple_opt_pass pass_sra =
3315 GIMPLE_PASS,
3316 "sra", /* name */
3317 gate_intra_sra, /* gate */
3318 late_intra_sra, /* execute */
3319 NULL, /* sub */
3320 NULL, /* next */
3321 0, /* static_pass_number */
3322 TV_TREE_SRA, /* tv_id */
3323 PROP_cfg | PROP_ssa, /* properties_required */
3324 0, /* properties_provided */
3325 0, /* properties_destroyed */
3326 TODO_update_address_taken, /* todo_flags_start */
3327 TODO_update_ssa
3328 | TODO_ggc_collect
3329 | TODO_verify_ssa /* todo_flags_finish */
3334 /* Return true iff PARM (which must be a parm_decl) is an unused scalar
3335 parameter. */
3337 static bool
3338 is_unused_scalar_param (tree parm)
3340 tree name;
3341 return (is_gimple_reg (parm)
3342 && (!(name = gimple_default_def (cfun, parm))
3343 || has_zero_uses (name)));
3346 /* Scan immediate uses of a default definition SSA name of a parameter PARM and
3347 examine whether there are any direct or otherwise infeasible ones. If so,
3348 return true, otherwise return false. PARM must be a gimple register with a
3349 non-NULL default definition. */
3351 static bool
3352 ptr_parm_has_direct_uses (tree parm)
3354 imm_use_iterator ui;
3355 gimple stmt;
3356 tree name = gimple_default_def (cfun, parm);
3357 bool ret = false;
3359 FOR_EACH_IMM_USE_STMT (stmt, ui, name)
3361 int uses_ok = 0;
3362 use_operand_p use_p;
3364 if (is_gimple_debug (stmt))
3365 continue;
3367 /* Valid uses include dereferences on the lhs and the rhs. */
3368 if (gimple_has_lhs (stmt))
3370 tree lhs = gimple_get_lhs (stmt);
3371 while (handled_component_p (lhs))
3372 lhs = TREE_OPERAND (lhs, 0);
3373 if (TREE_CODE (lhs) == MEM_REF
3374 && TREE_OPERAND (lhs, 0) == name
3375 && integer_zerop (TREE_OPERAND (lhs, 1))
3376 && types_compatible_p (TREE_TYPE (lhs),
3377 TREE_TYPE (TREE_TYPE (name)))
3378 && !TREE_THIS_VOLATILE (lhs))
3379 uses_ok++;
3381 if (gimple_assign_single_p (stmt))
3383 tree rhs = gimple_assign_rhs1 (stmt);
3384 while (handled_component_p (rhs))
3385 rhs = TREE_OPERAND (rhs, 0);
3386 if (TREE_CODE (rhs) == MEM_REF
3387 && TREE_OPERAND (rhs, 0) == name
3388 && integer_zerop (TREE_OPERAND (rhs, 1))
3389 && types_compatible_p (TREE_TYPE (rhs),
3390 TREE_TYPE (TREE_TYPE (name)))
3391 && !TREE_THIS_VOLATILE (rhs))
3392 uses_ok++;
3394 else if (is_gimple_call (stmt))
3396 unsigned i;
3397 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3399 tree arg = gimple_call_arg (stmt, i);
3400 while (handled_component_p (arg))
3401 arg = TREE_OPERAND (arg, 0);
3402 if (TREE_CODE (arg) == MEM_REF
3403 && TREE_OPERAND (arg, 0) == name
3404 && integer_zerop (TREE_OPERAND (arg, 1))
3405 && types_compatible_p (TREE_TYPE (arg),
3406 TREE_TYPE (TREE_TYPE (name)))
3407 && !TREE_THIS_VOLATILE (arg))
3408 uses_ok++;
3412 /* If the number of valid uses does not match the number of
3413 uses in this stmt there is an unhandled use. */
3414 FOR_EACH_IMM_USE_ON_STMT (use_p, ui)
3415 --uses_ok;
3417 if (uses_ok != 0)
3418 ret = true;
3420 if (ret)
3421 BREAK_FROM_IMM_USE_STMT (ui);
3424 return ret;
3427 /* Identify candidates for reduction for IPA-SRA based on their type and mark
3428 them in candidate_bitmap. Note that these do not necessarily include
3429 parameter which are unused and thus can be removed. Return true iff any
3430 such candidate has been found. */
3432 static bool
3433 find_param_candidates (void)
3435 tree parm;
3436 int count = 0;
3437 bool ret = false;
3438 const char *msg;
3440 for (parm = DECL_ARGUMENTS (current_function_decl);
3441 parm;
3442 parm = DECL_CHAIN (parm))
3444 tree type = TREE_TYPE (parm);
3446 count++;
3448 if (TREE_THIS_VOLATILE (parm)
3449 || TREE_ADDRESSABLE (parm)
3450 || (!is_gimple_reg_type (type) && is_va_list_type (type)))
3451 continue;
3453 if (is_unused_scalar_param (parm))
3455 ret = true;
3456 continue;
3459 if (POINTER_TYPE_P (type))
3461 type = TREE_TYPE (type);
3463 if (TREE_CODE (type) == FUNCTION_TYPE
3464 || TYPE_VOLATILE (type)
3465 || (TREE_CODE (type) == ARRAY_TYPE
3466 && TYPE_NONALIASED_COMPONENT (type))
3467 || !is_gimple_reg (parm)
3468 || is_va_list_type (type)
3469 || ptr_parm_has_direct_uses (parm))
3470 continue;
3472 else if (!AGGREGATE_TYPE_P (type))
3473 continue;
3475 if (!COMPLETE_TYPE_P (type)
3476 || !host_integerp (TYPE_SIZE (type), 1)
3477 || tree_low_cst (TYPE_SIZE (type), 1) == 0
3478 || (AGGREGATE_TYPE_P (type)
3479 && type_internals_preclude_sra_p (type, &msg)))
3480 continue;
3482 bitmap_set_bit (candidate_bitmap, DECL_UID (parm));
3483 ret = true;
3484 if (dump_file && (dump_flags & TDF_DETAILS))
3486 fprintf (dump_file, "Candidate (%d): ", DECL_UID (parm));
3487 print_generic_expr (dump_file, parm, 0);
3488 fprintf (dump_file, "\n");
3492 func_param_count = count;
3493 return ret;
3496 /* Callback of walk_aliased_vdefs, marks the access passed as DATA as
3497 maybe_modified. */
3499 static bool
3500 mark_maybe_modified (ao_ref *ao ATTRIBUTE_UNUSED, tree vdef ATTRIBUTE_UNUSED,
3501 void *data)
3503 struct access *repr = (struct access *) data;
3505 repr->grp_maybe_modified = 1;
3506 return true;
3509 /* Analyze what representatives (in linked lists accessible from
3510 REPRESENTATIVES) can be modified by side effects of statements in the
3511 current function. */
3513 static void
3514 analyze_modified_params (VEC (access_p, heap) *representatives)
3516 int i;
3518 for (i = 0; i < func_param_count; i++)
3520 struct access *repr;
3522 for (repr = VEC_index (access_p, representatives, i);
3523 repr;
3524 repr = repr->next_grp)
3526 struct access *access;
3527 bitmap visited;
3528 ao_ref ar;
3530 if (no_accesses_p (repr))
3531 continue;
3532 if (!POINTER_TYPE_P (TREE_TYPE (repr->base))
3533 || repr->grp_maybe_modified)
3534 continue;
3536 ao_ref_init (&ar, repr->expr);
3537 visited = BITMAP_ALLOC (NULL);
3538 for (access = repr; access; access = access->next_sibling)
3540 /* All accesses are read ones, otherwise grp_maybe_modified would
3541 be trivially set. */
3542 walk_aliased_vdefs (&ar, gimple_vuse (access->stmt),
3543 mark_maybe_modified, repr, &visited);
3544 if (repr->grp_maybe_modified)
3545 break;
3547 BITMAP_FREE (visited);
3552 /* Propagate distances in bb_dereferences in the opposite direction than the
3553 control flow edges, in each step storing the maximum of the current value
3554 and the minimum of all successors. These steps are repeated until the table
3555 stabilizes. Note that BBs which might terminate the functions (according to
3556 final_bbs bitmap) never updated in this way. */
3558 static void
3559 propagate_dereference_distances (void)
3561 VEC (basic_block, heap) *queue;
3562 basic_block bb;
3564 queue = VEC_alloc (basic_block, heap, last_basic_block_for_function (cfun));
3565 VEC_quick_push (basic_block, queue, ENTRY_BLOCK_PTR);
3566 FOR_EACH_BB (bb)
3568 VEC_quick_push (basic_block, queue, bb);
3569 bb->aux = bb;
3572 while (!VEC_empty (basic_block, queue))
3574 edge_iterator ei;
3575 edge e;
3576 bool change = false;
3577 int i;
3579 bb = VEC_pop (basic_block, queue);
3580 bb->aux = NULL;
3582 if (bitmap_bit_p (final_bbs, bb->index))
3583 continue;
3585 for (i = 0; i < func_param_count; i++)
3587 int idx = bb->index * func_param_count + i;
3588 bool first = true;
3589 HOST_WIDE_INT inh = 0;
3591 FOR_EACH_EDGE (e, ei, bb->succs)
3593 int succ_idx = e->dest->index * func_param_count + i;
3595 if (e->src == EXIT_BLOCK_PTR)
3596 continue;
3598 if (first)
3600 first = false;
3601 inh = bb_dereferences [succ_idx];
3603 else if (bb_dereferences [succ_idx] < inh)
3604 inh = bb_dereferences [succ_idx];
3607 if (!first && bb_dereferences[idx] < inh)
3609 bb_dereferences[idx] = inh;
3610 change = true;
3614 if (change && !bitmap_bit_p (final_bbs, bb->index))
3615 FOR_EACH_EDGE (e, ei, bb->preds)
3617 if (e->src->aux)
3618 continue;
3620 e->src->aux = e->src;
3621 VEC_quick_push (basic_block, queue, e->src);
3625 VEC_free (basic_block, heap, queue);
3628 /* Dump a dereferences TABLE with heading STR to file F. */
3630 static void
3631 dump_dereferences_table (FILE *f, const char *str, HOST_WIDE_INT *table)
3633 basic_block bb;
3635 fprintf (dump_file, str);
3636 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, EXIT_BLOCK_PTR, next_bb)
3638 fprintf (f, "%4i %i ", bb->index, bitmap_bit_p (final_bbs, bb->index));
3639 if (bb != EXIT_BLOCK_PTR)
3641 int i;
3642 for (i = 0; i < func_param_count; i++)
3644 int idx = bb->index * func_param_count + i;
3645 fprintf (f, " %4" HOST_WIDE_INT_PRINT "d", table[idx]);
3648 fprintf (f, "\n");
3650 fprintf (dump_file, "\n");
3653 /* Determine what (parts of) parameters passed by reference that are not
3654 assigned to are not certainly dereferenced in this function and thus the
3655 dereferencing cannot be safely moved to the caller without potentially
3656 introducing a segfault. Mark such REPRESENTATIVES as
3657 grp_not_necessarilly_dereferenced.
3659 The dereferenced maximum "distance," i.e. the offset + size of the accessed
3660 part is calculated rather than simple booleans are calculated for each
3661 pointer parameter to handle cases when only a fraction of the whole
3662 aggregate is allocated (see testsuite/gcc.c-torture/execute/ipa-sra-2.c for
3663 an example).
3665 The maximum dereference distances for each pointer parameter and BB are
3666 already stored in bb_dereference. This routine simply propagates these
3667 values upwards by propagate_dereference_distances and then compares the
3668 distances of individual parameters in the ENTRY BB to the equivalent
3669 distances of each representative of a (fraction of a) parameter. */
3671 static void
3672 analyze_caller_dereference_legality (VEC (access_p, heap) *representatives)
3674 int i;
3676 if (dump_file && (dump_flags & TDF_DETAILS))
3677 dump_dereferences_table (dump_file,
3678 "Dereference table before propagation:\n",
3679 bb_dereferences);
3681 propagate_dereference_distances ();
3683 if (dump_file && (dump_flags & TDF_DETAILS))
3684 dump_dereferences_table (dump_file,
3685 "Dereference table after propagation:\n",
3686 bb_dereferences);
3688 for (i = 0; i < func_param_count; i++)
3690 struct access *repr = VEC_index (access_p, representatives, i);
3691 int idx = ENTRY_BLOCK_PTR->index * func_param_count + i;
3693 if (!repr || no_accesses_p (repr))
3694 continue;
3698 if ((repr->offset + repr->size) > bb_dereferences[idx])
3699 repr->grp_not_necessarilly_dereferenced = 1;
3700 repr = repr->next_grp;
3702 while (repr);
3706 /* Return the representative access for the parameter declaration PARM if it is
3707 a scalar passed by reference which is not written to and the pointer value
3708 is not used directly. Thus, if it is legal to dereference it in the caller
3709 and we can rule out modifications through aliases, such parameter should be
3710 turned into one passed by value. Return NULL otherwise. */
3712 static struct access *
3713 unmodified_by_ref_scalar_representative (tree parm)
3715 int i, access_count;
3716 struct access *repr;
3717 VEC (access_p, heap) *access_vec;
3719 access_vec = get_base_access_vector (parm);
3720 gcc_assert (access_vec);
3721 repr = VEC_index (access_p, access_vec, 0);
3722 if (repr->write)
3723 return NULL;
3724 repr->group_representative = repr;
3726 access_count = VEC_length (access_p, access_vec);
3727 for (i = 1; i < access_count; i++)
3729 struct access *access = VEC_index (access_p, access_vec, i);
3730 if (access->write)
3731 return NULL;
3732 access->group_representative = repr;
3733 access->next_sibling = repr->next_sibling;
3734 repr->next_sibling = access;
3737 repr->grp_read = 1;
3738 repr->grp_scalar_ptr = 1;
3739 return repr;
3742 /* Return true iff this access precludes IPA-SRA of the parameter it is
3743 associated with. */
3745 static bool
3746 access_precludes_ipa_sra_p (struct access *access)
3748 /* Avoid issues such as the second simple testcase in PR 42025. The problem
3749 is incompatible assign in a call statement (and possibly even in asm
3750 statements). This can be relaxed by using a new temporary but only for
3751 non-TREE_ADDRESSABLE types and is probably not worth the complexity. (In
3752 intraprocedural SRA we deal with this by keeping the old aggregate around,
3753 something we cannot do in IPA-SRA.) */
3754 if (access->write
3755 && (is_gimple_call (access->stmt)
3756 || gimple_code (access->stmt) == GIMPLE_ASM))
3757 return true;
3759 return false;
3763 /* Sort collected accesses for parameter PARM, identify representatives for
3764 each accessed region and link them together. Return NULL if there are
3765 different but overlapping accesses, return the special ptr value meaning
3766 there are no accesses for this parameter if that is the case and return the
3767 first representative otherwise. Set *RO_GRP if there is a group of accesses
3768 with only read (i.e. no write) accesses. */
3770 static struct access *
3771 splice_param_accesses (tree parm, bool *ro_grp)
3773 int i, j, access_count, group_count;
3774 int agg_size, total_size = 0;
3775 struct access *access, *res, **prev_acc_ptr = &res;
3776 VEC (access_p, heap) *access_vec;
3778 access_vec = get_base_access_vector (parm);
3779 if (!access_vec)
3780 return &no_accesses_representant;
3781 access_count = VEC_length (access_p, access_vec);
3783 VEC_qsort (access_p, access_vec, compare_access_positions);
3785 i = 0;
3786 total_size = 0;
3787 group_count = 0;
3788 while (i < access_count)
3790 bool modification;
3791 tree a1_alias_type;
3792 access = VEC_index (access_p, access_vec, i);
3793 modification = access->write;
3794 if (access_precludes_ipa_sra_p (access))
3795 return NULL;
3796 a1_alias_type = reference_alias_ptr_type (access->expr);
3798 /* Access is about to become group representative unless we find some
3799 nasty overlap which would preclude us from breaking this parameter
3800 apart. */
3802 j = i + 1;
3803 while (j < access_count)
3805 struct access *ac2 = VEC_index (access_p, access_vec, j);
3806 if (ac2->offset != access->offset)
3808 /* All or nothing law for parameters. */
3809 if (access->offset + access->size > ac2->offset)
3810 return NULL;
3811 else
3812 break;
3814 else if (ac2->size != access->size)
3815 return NULL;
3817 if (access_precludes_ipa_sra_p (ac2)
3818 || (ac2->type != access->type
3819 && (TREE_ADDRESSABLE (ac2->type)
3820 || TREE_ADDRESSABLE (access->type)))
3821 || (reference_alias_ptr_type (ac2->expr) != a1_alias_type))
3822 return NULL;
3824 modification |= ac2->write;
3825 ac2->group_representative = access;
3826 ac2->next_sibling = access->next_sibling;
3827 access->next_sibling = ac2;
3828 j++;
3831 group_count++;
3832 access->grp_maybe_modified = modification;
3833 if (!modification)
3834 *ro_grp = true;
3835 *prev_acc_ptr = access;
3836 prev_acc_ptr = &access->next_grp;
3837 total_size += access->size;
3838 i = j;
3841 if (POINTER_TYPE_P (TREE_TYPE (parm)))
3842 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (TREE_TYPE (parm))), 1);
3843 else
3844 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (parm)), 1);
3845 if (total_size >= agg_size)
3846 return NULL;
3848 gcc_assert (group_count > 0);
3849 return res;
3852 /* Decide whether parameters with representative accesses given by REPR should
3853 be reduced into components. */
3855 static int
3856 decide_one_param_reduction (struct access *repr)
3858 int total_size, cur_parm_size, agg_size, new_param_count, parm_size_limit;
3859 bool by_ref;
3860 tree parm;
3862 parm = repr->base;
3863 cur_parm_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (parm)), 1);
3864 gcc_assert (cur_parm_size > 0);
3866 if (POINTER_TYPE_P (TREE_TYPE (parm)))
3868 by_ref = true;
3869 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (TREE_TYPE (parm))), 1);
3871 else
3873 by_ref = false;
3874 agg_size = cur_parm_size;
3877 if (dump_file)
3879 struct access *acc;
3880 fprintf (dump_file, "Evaluating PARAM group sizes for ");
3881 print_generic_expr (dump_file, parm, 0);
3882 fprintf (dump_file, " (UID: %u): \n", DECL_UID (parm));
3883 for (acc = repr; acc; acc = acc->next_grp)
3884 dump_access (dump_file, acc, true);
3887 total_size = 0;
3888 new_param_count = 0;
3890 for (; repr; repr = repr->next_grp)
3892 gcc_assert (parm == repr->base);
3894 /* Taking the address of a non-addressable field is verboten. */
3895 if (by_ref && repr->non_addressable)
3896 return 0;
3898 /* Do not decompose a non-BLKmode param in a way that would
3899 create BLKmode params. Especially for by-reference passing
3900 (thus, pointer-type param) this is hardly worthwhile. */
3901 if (DECL_MODE (parm) != BLKmode
3902 && TYPE_MODE (repr->type) == BLKmode)
3903 return 0;
3905 if (!by_ref || (!repr->grp_maybe_modified
3906 && !repr->grp_not_necessarilly_dereferenced))
3907 total_size += repr->size;
3908 else
3909 total_size += cur_parm_size;
3911 new_param_count++;
3914 gcc_assert (new_param_count > 0);
3916 if (optimize_function_for_size_p (cfun))
3917 parm_size_limit = cur_parm_size;
3918 else
3919 parm_size_limit = (PARAM_VALUE (PARAM_IPA_SRA_PTR_GROWTH_FACTOR)
3920 * cur_parm_size);
3922 if (total_size < agg_size
3923 && total_size <= parm_size_limit)
3925 if (dump_file)
3926 fprintf (dump_file, " ....will be split into %i components\n",
3927 new_param_count);
3928 return new_param_count;
3930 else
3931 return 0;
3934 /* The order of the following enums is important, we need to do extra work for
3935 UNUSED_PARAMS, BY_VAL_ACCESSES and UNMODIF_BY_REF_ACCESSES. */
3936 enum ipa_splicing_result { NO_GOOD_ACCESS, UNUSED_PARAMS, BY_VAL_ACCESSES,
3937 MODIF_BY_REF_ACCESSES, UNMODIF_BY_REF_ACCESSES };
3939 /* Identify representatives of all accesses to all candidate parameters for
3940 IPA-SRA. Return result based on what representatives have been found. */
3942 static enum ipa_splicing_result
3943 splice_all_param_accesses (VEC (access_p, heap) **representatives)
3945 enum ipa_splicing_result result = NO_GOOD_ACCESS;
3946 tree parm;
3947 struct access *repr;
3949 *representatives = VEC_alloc (access_p, heap, func_param_count);
3951 for (parm = DECL_ARGUMENTS (current_function_decl);
3952 parm;
3953 parm = DECL_CHAIN (parm))
3955 if (is_unused_scalar_param (parm))
3957 VEC_quick_push (access_p, *representatives,
3958 &no_accesses_representant);
3959 if (result == NO_GOOD_ACCESS)
3960 result = UNUSED_PARAMS;
3962 else if (POINTER_TYPE_P (TREE_TYPE (parm))
3963 && is_gimple_reg_type (TREE_TYPE (TREE_TYPE (parm)))
3964 && bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
3966 repr = unmodified_by_ref_scalar_representative (parm);
3967 VEC_quick_push (access_p, *representatives, repr);
3968 if (repr)
3969 result = UNMODIF_BY_REF_ACCESSES;
3971 else if (bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
3973 bool ro_grp = false;
3974 repr = splice_param_accesses (parm, &ro_grp);
3975 VEC_quick_push (access_p, *representatives, repr);
3977 if (repr && !no_accesses_p (repr))
3979 if (POINTER_TYPE_P (TREE_TYPE (parm)))
3981 if (ro_grp)
3982 result = UNMODIF_BY_REF_ACCESSES;
3983 else if (result < MODIF_BY_REF_ACCESSES)
3984 result = MODIF_BY_REF_ACCESSES;
3986 else if (result < BY_VAL_ACCESSES)
3987 result = BY_VAL_ACCESSES;
3989 else if (no_accesses_p (repr) && (result == NO_GOOD_ACCESS))
3990 result = UNUSED_PARAMS;
3992 else
3993 VEC_quick_push (access_p, *representatives, NULL);
3996 if (result == NO_GOOD_ACCESS)
3998 VEC_free (access_p, heap, *representatives);
3999 *representatives = NULL;
4000 return NO_GOOD_ACCESS;
4003 return result;
4006 /* Return the index of BASE in PARMS. Abort if it is not found. */
4008 static inline int
4009 get_param_index (tree base, VEC(tree, heap) *parms)
4011 int i, len;
4013 len = VEC_length (tree, parms);
4014 for (i = 0; i < len; i++)
4015 if (VEC_index (tree, parms, i) == base)
4016 return i;
4017 gcc_unreachable ();
4020 /* Convert the decisions made at the representative level into compact
4021 parameter adjustments. REPRESENTATIVES are pointers to first
4022 representatives of each param accesses, ADJUSTMENTS_COUNT is the expected
4023 final number of adjustments. */
4025 static ipa_parm_adjustment_vec
4026 turn_representatives_into_adjustments (VEC (access_p, heap) *representatives,
4027 int adjustments_count)
4029 VEC (tree, heap) *parms;
4030 ipa_parm_adjustment_vec adjustments;
4031 tree parm;
4032 int i;
4034 gcc_assert (adjustments_count > 0);
4035 parms = ipa_get_vector_of_formal_parms (current_function_decl);
4036 adjustments = VEC_alloc (ipa_parm_adjustment_t, heap, adjustments_count);
4037 parm = DECL_ARGUMENTS (current_function_decl);
4038 for (i = 0; i < func_param_count; i++, parm = DECL_CHAIN (parm))
4040 struct access *repr = VEC_index (access_p, representatives, i);
4042 if (!repr || no_accesses_p (repr))
4044 struct ipa_parm_adjustment *adj;
4046 adj = VEC_quick_push (ipa_parm_adjustment_t, adjustments, NULL);
4047 memset (adj, 0, sizeof (*adj));
4048 adj->base_index = get_param_index (parm, parms);
4049 adj->base = parm;
4050 if (!repr)
4051 adj->copy_param = 1;
4052 else
4053 adj->remove_param = 1;
4055 else
4057 struct ipa_parm_adjustment *adj;
4058 int index = get_param_index (parm, parms);
4060 for (; repr; repr = repr->next_grp)
4062 adj = VEC_quick_push (ipa_parm_adjustment_t, adjustments, NULL);
4063 memset (adj, 0, sizeof (*adj));
4064 gcc_assert (repr->base == parm);
4065 adj->base_index = index;
4066 adj->base = repr->base;
4067 adj->type = repr->type;
4068 adj->alias_ptr_type = reference_alias_ptr_type (repr->expr);
4069 adj->offset = repr->offset;
4070 adj->by_ref = (POINTER_TYPE_P (TREE_TYPE (repr->base))
4071 && (repr->grp_maybe_modified
4072 || repr->grp_not_necessarilly_dereferenced));
4077 VEC_free (tree, heap, parms);
4078 return adjustments;
4081 /* Analyze the collected accesses and produce a plan what to do with the
4082 parameters in the form of adjustments, NULL meaning nothing. */
4084 static ipa_parm_adjustment_vec
4085 analyze_all_param_acesses (void)
4087 enum ipa_splicing_result repr_state;
4088 bool proceed = false;
4089 int i, adjustments_count = 0;
4090 VEC (access_p, heap) *representatives;
4091 ipa_parm_adjustment_vec adjustments;
4093 repr_state = splice_all_param_accesses (&representatives);
4094 if (repr_state == NO_GOOD_ACCESS)
4095 return NULL;
4097 /* If there are any parameters passed by reference which are not modified
4098 directly, we need to check whether they can be modified indirectly. */
4099 if (repr_state == UNMODIF_BY_REF_ACCESSES)
4101 analyze_caller_dereference_legality (representatives);
4102 analyze_modified_params (representatives);
4105 for (i = 0; i < func_param_count; i++)
4107 struct access *repr = VEC_index (access_p, representatives, i);
4109 if (repr && !no_accesses_p (repr))
4111 if (repr->grp_scalar_ptr)
4113 adjustments_count++;
4114 if (repr->grp_not_necessarilly_dereferenced
4115 || repr->grp_maybe_modified)
4116 VEC_replace (access_p, representatives, i, NULL);
4117 else
4119 proceed = true;
4120 sra_stats.scalar_by_ref_to_by_val++;
4123 else
4125 int new_components = decide_one_param_reduction (repr);
4127 if (new_components == 0)
4129 VEC_replace (access_p, representatives, i, NULL);
4130 adjustments_count++;
4132 else
4134 adjustments_count += new_components;
4135 sra_stats.aggregate_params_reduced++;
4136 sra_stats.param_reductions_created += new_components;
4137 proceed = true;
4141 else
4143 if (no_accesses_p (repr))
4145 proceed = true;
4146 sra_stats.deleted_unused_parameters++;
4148 adjustments_count++;
4152 if (!proceed && dump_file)
4153 fprintf (dump_file, "NOT proceeding to change params.\n");
4155 if (proceed)
4156 adjustments = turn_representatives_into_adjustments (representatives,
4157 adjustments_count);
4158 else
4159 adjustments = NULL;
4161 VEC_free (access_p, heap, representatives);
4162 return adjustments;
4165 /* If a parameter replacement identified by ADJ does not yet exist in the form
4166 of declaration, create it and record it, otherwise return the previously
4167 created one. */
4169 static tree
4170 get_replaced_param_substitute (struct ipa_parm_adjustment *adj)
4172 tree repl;
4173 if (!adj->new_ssa_base)
4175 char *pretty_name = make_fancy_name (adj->base);
4177 repl = create_tmp_reg (TREE_TYPE (adj->base), "ISR");
4178 DECL_NAME (repl) = get_identifier (pretty_name);
4179 obstack_free (&name_obstack, pretty_name);
4181 add_referenced_var (repl);
4182 adj->new_ssa_base = repl;
4184 else
4185 repl = adj->new_ssa_base;
4186 return repl;
4189 /* Find the first adjustment for a particular parameter BASE in a vector of
4190 ADJUSTMENTS which is not a copy_param. Return NULL if there is no such
4191 adjustment. */
4193 static struct ipa_parm_adjustment *
4194 get_adjustment_for_base (ipa_parm_adjustment_vec adjustments, tree base)
4196 int i, len;
4198 len = VEC_length (ipa_parm_adjustment_t, adjustments);
4199 for (i = 0; i < len; i++)
4201 struct ipa_parm_adjustment *adj;
4203 adj = VEC_index (ipa_parm_adjustment_t, adjustments, i);
4204 if (!adj->copy_param && adj->base == base)
4205 return adj;
4208 return NULL;
4211 /* If the statement STMT defines an SSA_NAME of a parameter which is to be
4212 removed because its value is not used, replace the SSA_NAME with a one
4213 relating to a created VAR_DECL together all of its uses and return true.
4214 ADJUSTMENTS is a pointer to an adjustments vector. */
4216 static bool
4217 replace_removed_params_ssa_names (gimple stmt,
4218 ipa_parm_adjustment_vec adjustments)
4220 struct ipa_parm_adjustment *adj;
4221 tree lhs, decl, repl, name;
4223 if (gimple_code (stmt) == GIMPLE_PHI)
4224 lhs = gimple_phi_result (stmt);
4225 else if (is_gimple_assign (stmt))
4226 lhs = gimple_assign_lhs (stmt);
4227 else if (is_gimple_call (stmt))
4228 lhs = gimple_call_lhs (stmt);
4229 else
4230 gcc_unreachable ();
4232 if (TREE_CODE (lhs) != SSA_NAME)
4233 return false;
4234 decl = SSA_NAME_VAR (lhs);
4235 if (TREE_CODE (decl) != PARM_DECL)
4236 return false;
4238 adj = get_adjustment_for_base (adjustments, decl);
4239 if (!adj)
4240 return false;
4242 repl = get_replaced_param_substitute (adj);
4243 name = make_ssa_name (repl, stmt);
4245 if (dump_file)
4247 fprintf (dump_file, "replacing an SSA name of a removed param ");
4248 print_generic_expr (dump_file, lhs, 0);
4249 fprintf (dump_file, " with ");
4250 print_generic_expr (dump_file, name, 0);
4251 fprintf (dump_file, "\n");
4254 if (is_gimple_assign (stmt))
4255 gimple_assign_set_lhs (stmt, name);
4256 else if (is_gimple_call (stmt))
4257 gimple_call_set_lhs (stmt, name);
4258 else
4259 gimple_phi_set_result (stmt, name);
4261 replace_uses_by (lhs, name);
4262 release_ssa_name (lhs);
4263 return true;
4266 /* If the expression *EXPR should be replaced by a reduction of a parameter, do
4267 so. ADJUSTMENTS is a pointer to a vector of adjustments. CONVERT
4268 specifies whether the function should care about type incompatibility the
4269 current and new expressions. If it is false, the function will leave
4270 incompatibility issues to the caller. Return true iff the expression
4271 was modified. */
4273 static bool
4274 sra_ipa_modify_expr (tree *expr, bool convert,
4275 ipa_parm_adjustment_vec adjustments)
4277 int i, len;
4278 struct ipa_parm_adjustment *adj, *cand = NULL;
4279 HOST_WIDE_INT offset, size, max_size;
4280 tree base, src;
4282 len = VEC_length (ipa_parm_adjustment_t, adjustments);
4284 if (TREE_CODE (*expr) == BIT_FIELD_REF
4285 || TREE_CODE (*expr) == IMAGPART_EXPR
4286 || TREE_CODE (*expr) == REALPART_EXPR)
4288 expr = &TREE_OPERAND (*expr, 0);
4289 convert = true;
4292 base = get_ref_base_and_extent (*expr, &offset, &size, &max_size);
4293 if (!base || size == -1 || max_size == -1)
4294 return false;
4296 if (TREE_CODE (base) == MEM_REF)
4298 offset += mem_ref_offset (base).low * BITS_PER_UNIT;
4299 base = TREE_OPERAND (base, 0);
4302 base = get_ssa_base_param (base);
4303 if (!base || TREE_CODE (base) != PARM_DECL)
4304 return false;
4306 for (i = 0; i < len; i++)
4308 adj = VEC_index (ipa_parm_adjustment_t, adjustments, i);
4310 if (adj->base == base &&
4311 (adj->offset == offset || adj->remove_param))
4313 cand = adj;
4314 break;
4317 if (!cand || cand->copy_param || cand->remove_param)
4318 return false;
4320 if (cand->by_ref)
4321 src = build_simple_mem_ref (cand->reduction);
4322 else
4323 src = cand->reduction;
4325 if (dump_file && (dump_flags & TDF_DETAILS))
4327 fprintf (dump_file, "About to replace expr ");
4328 print_generic_expr (dump_file, *expr, 0);
4329 fprintf (dump_file, " with ");
4330 print_generic_expr (dump_file, src, 0);
4331 fprintf (dump_file, "\n");
4334 if (convert && !useless_type_conversion_p (TREE_TYPE (*expr), cand->type))
4336 tree vce = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (*expr), src);
4337 *expr = vce;
4339 else
4340 *expr = src;
4341 return true;
4344 /* If the statement pointed to by STMT_PTR contains any expressions that need
4345 to replaced with a different one as noted by ADJUSTMENTS, do so. Handle any
4346 potential type incompatibilities (GSI is used to accommodate conversion
4347 statements and must point to the statement). Return true iff the statement
4348 was modified. */
4350 static bool
4351 sra_ipa_modify_assign (gimple *stmt_ptr, gimple_stmt_iterator *gsi,
4352 ipa_parm_adjustment_vec adjustments)
4354 gimple stmt = *stmt_ptr;
4355 tree *lhs_p, *rhs_p;
4356 bool any;
4358 if (!gimple_assign_single_p (stmt))
4359 return false;
4361 rhs_p = gimple_assign_rhs1_ptr (stmt);
4362 lhs_p = gimple_assign_lhs_ptr (stmt);
4364 any = sra_ipa_modify_expr (rhs_p, false, adjustments);
4365 any |= sra_ipa_modify_expr (lhs_p, false, adjustments);
4366 if (any)
4368 tree new_rhs = NULL_TREE;
4370 if (!useless_type_conversion_p (TREE_TYPE (*lhs_p), TREE_TYPE (*rhs_p)))
4372 if (TREE_CODE (*rhs_p) == CONSTRUCTOR)
4374 /* V_C_Es of constructors can cause trouble (PR 42714). */
4375 if (is_gimple_reg_type (TREE_TYPE (*lhs_p)))
4376 *rhs_p = build_zero_cst (TREE_TYPE (*lhs_p));
4377 else
4378 *rhs_p = build_constructor (TREE_TYPE (*lhs_p), 0);
4380 else
4381 new_rhs = fold_build1_loc (gimple_location (stmt),
4382 VIEW_CONVERT_EXPR, TREE_TYPE (*lhs_p),
4383 *rhs_p);
4385 else if (REFERENCE_CLASS_P (*rhs_p)
4386 && is_gimple_reg_type (TREE_TYPE (*lhs_p))
4387 && !is_gimple_reg (*lhs_p))
4388 /* This can happen when an assignment in between two single field
4389 structures is turned into an assignment in between two pointers to
4390 scalars (PR 42237). */
4391 new_rhs = *rhs_p;
4393 if (new_rhs)
4395 tree tmp = force_gimple_operand_gsi (gsi, new_rhs, true, NULL_TREE,
4396 true, GSI_SAME_STMT);
4398 gimple_assign_set_rhs_from_tree (gsi, tmp);
4401 return true;
4404 return false;
4407 /* Traverse the function body and all modifications as described in
4408 ADJUSTMENTS. Return true iff the CFG has been changed. */
4410 static bool
4411 ipa_sra_modify_function_body (ipa_parm_adjustment_vec adjustments)
4413 bool cfg_changed = false;
4414 basic_block bb;
4416 FOR_EACH_BB (bb)
4418 gimple_stmt_iterator gsi;
4420 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4421 replace_removed_params_ssa_names (gsi_stmt (gsi), adjustments);
4423 gsi = gsi_start_bb (bb);
4424 while (!gsi_end_p (gsi))
4426 gimple stmt = gsi_stmt (gsi);
4427 bool modified = false;
4428 tree *t;
4429 unsigned i;
4431 switch (gimple_code (stmt))
4433 case GIMPLE_RETURN:
4434 t = gimple_return_retval_ptr (stmt);
4435 if (*t != NULL_TREE)
4436 modified |= sra_ipa_modify_expr (t, true, adjustments);
4437 break;
4439 case GIMPLE_ASSIGN:
4440 modified |= sra_ipa_modify_assign (&stmt, &gsi, adjustments);
4441 modified |= replace_removed_params_ssa_names (stmt, adjustments);
4442 break;
4444 case GIMPLE_CALL:
4445 /* Operands must be processed before the lhs. */
4446 for (i = 0; i < gimple_call_num_args (stmt); i++)
4448 t = gimple_call_arg_ptr (stmt, i);
4449 modified |= sra_ipa_modify_expr (t, true, adjustments);
4452 if (gimple_call_lhs (stmt))
4454 t = gimple_call_lhs_ptr (stmt);
4455 modified |= sra_ipa_modify_expr (t, false, adjustments);
4456 modified |= replace_removed_params_ssa_names (stmt,
4457 adjustments);
4459 break;
4461 case GIMPLE_ASM:
4462 for (i = 0; i < gimple_asm_ninputs (stmt); i++)
4464 t = &TREE_VALUE (gimple_asm_input_op (stmt, i));
4465 modified |= sra_ipa_modify_expr (t, true, adjustments);
4467 for (i = 0; i < gimple_asm_noutputs (stmt); i++)
4469 t = &TREE_VALUE (gimple_asm_output_op (stmt, i));
4470 modified |= sra_ipa_modify_expr (t, false, adjustments);
4472 break;
4474 default:
4475 break;
4478 if (modified)
4480 update_stmt (stmt);
4481 if (maybe_clean_eh_stmt (stmt)
4482 && gimple_purge_dead_eh_edges (gimple_bb (stmt)))
4483 cfg_changed = true;
4485 gsi_next (&gsi);
4489 return cfg_changed;
4492 /* Call gimple_debug_bind_reset_value on all debug statements describing
4493 gimple register parameters that are being removed or replaced. */
4495 static void
4496 sra_ipa_reset_debug_stmts (ipa_parm_adjustment_vec adjustments)
4498 int i, len;
4499 gimple_stmt_iterator *gsip = NULL, gsi;
4501 if (MAY_HAVE_DEBUG_STMTS && single_succ_p (ENTRY_BLOCK_PTR))
4503 gsi = gsi_after_labels (single_succ (ENTRY_BLOCK_PTR));
4504 gsip = &gsi;
4506 len = VEC_length (ipa_parm_adjustment_t, adjustments);
4507 for (i = 0; i < len; i++)
4509 struct ipa_parm_adjustment *adj;
4510 imm_use_iterator ui;
4511 gimple stmt, def_temp;
4512 tree name, vexpr, copy = NULL_TREE;
4513 use_operand_p use_p;
4515 adj = VEC_index (ipa_parm_adjustment_t, adjustments, i);
4516 if (adj->copy_param || !is_gimple_reg (adj->base))
4517 continue;
4518 name = gimple_default_def (cfun, adj->base);
4519 vexpr = NULL;
4520 if (name)
4521 FOR_EACH_IMM_USE_STMT (stmt, ui, name)
4523 /* All other users must have been removed by
4524 ipa_sra_modify_function_body. */
4525 gcc_assert (is_gimple_debug (stmt));
4526 if (vexpr == NULL && gsip != NULL)
4528 gcc_assert (TREE_CODE (adj->base) == PARM_DECL);
4529 vexpr = make_node (DEBUG_EXPR_DECL);
4530 def_temp = gimple_build_debug_source_bind (vexpr, adj->base,
4531 NULL);
4532 DECL_ARTIFICIAL (vexpr) = 1;
4533 TREE_TYPE (vexpr) = TREE_TYPE (name);
4534 DECL_MODE (vexpr) = DECL_MODE (adj->base);
4535 gsi_insert_before (gsip, def_temp, GSI_SAME_STMT);
4537 if (vexpr)
4539 FOR_EACH_IMM_USE_ON_STMT (use_p, ui)
4540 SET_USE (use_p, vexpr);
4542 else
4543 gimple_debug_bind_reset_value (stmt);
4544 update_stmt (stmt);
4546 /* Create a VAR_DECL for debug info purposes. */
4547 if (!DECL_IGNORED_P (adj->base))
4549 copy = build_decl (DECL_SOURCE_LOCATION (current_function_decl),
4550 VAR_DECL, DECL_NAME (adj->base),
4551 TREE_TYPE (adj->base));
4552 if (DECL_PT_UID_SET_P (adj->base))
4553 SET_DECL_PT_UID (copy, DECL_PT_UID (adj->base));
4554 TREE_ADDRESSABLE (copy) = TREE_ADDRESSABLE (adj->base);
4555 TREE_READONLY (copy) = TREE_READONLY (adj->base);
4556 TREE_THIS_VOLATILE (copy) = TREE_THIS_VOLATILE (adj->base);
4557 DECL_GIMPLE_REG_P (copy) = DECL_GIMPLE_REG_P (adj->base);
4558 DECL_ARTIFICIAL (copy) = DECL_ARTIFICIAL (adj->base);
4559 DECL_IGNORED_P (copy) = DECL_IGNORED_P (adj->base);
4560 DECL_ABSTRACT_ORIGIN (copy) = DECL_ORIGIN (adj->base);
4561 DECL_SEEN_IN_BIND_EXPR_P (copy) = 1;
4562 SET_DECL_RTL (copy, 0);
4563 TREE_USED (copy) = 1;
4564 DECL_CONTEXT (copy) = current_function_decl;
4565 add_referenced_var (copy);
4566 add_local_decl (cfun, copy);
4567 DECL_CHAIN (copy) =
4568 BLOCK_VARS (DECL_INITIAL (current_function_decl));
4569 BLOCK_VARS (DECL_INITIAL (current_function_decl)) = copy;
4571 if (gsip != NULL && copy && target_for_debug_bind (adj->base))
4573 gcc_assert (TREE_CODE (adj->base) == PARM_DECL);
4574 if (vexpr)
4575 def_temp = gimple_build_debug_bind (copy, vexpr, NULL);
4576 else
4577 def_temp = gimple_build_debug_source_bind (copy, adj->base,
4578 NULL);
4579 gsi_insert_before (gsip, def_temp, GSI_SAME_STMT);
4584 /* Return false iff all callers have at least as many actual arguments as there
4585 are formal parameters in the current function. */
4587 static bool
4588 not_all_callers_have_enough_arguments_p (struct cgraph_node *node,
4589 void *data ATTRIBUTE_UNUSED)
4591 struct cgraph_edge *cs;
4592 for (cs = node->callers; cs; cs = cs->next_caller)
4593 if (!callsite_has_enough_arguments_p (cs->call_stmt))
4594 return true;
4596 return false;
4599 /* Convert all callers of NODE. */
4601 static bool
4602 convert_callers_for_node (struct cgraph_node *node,
4603 void *data)
4605 ipa_parm_adjustment_vec adjustments = (ipa_parm_adjustment_vec)data;
4606 bitmap recomputed_callers = BITMAP_ALLOC (NULL);
4607 struct cgraph_edge *cs;
4609 for (cs = node->callers; cs; cs = cs->next_caller)
4611 current_function_decl = cs->caller->symbol.decl;
4612 push_cfun (DECL_STRUCT_FUNCTION (cs->caller->symbol.decl));
4614 if (dump_file)
4615 fprintf (dump_file, "Adjusting call (%i -> %i) %s -> %s\n",
4616 cs->caller->uid, cs->callee->uid,
4617 xstrdup (cgraph_node_name (cs->caller)),
4618 xstrdup (cgraph_node_name (cs->callee)));
4620 ipa_modify_call_arguments (cs, cs->call_stmt, adjustments);
4622 pop_cfun ();
4625 for (cs = node->callers; cs; cs = cs->next_caller)
4626 if (bitmap_set_bit (recomputed_callers, cs->caller->uid)
4627 && gimple_in_ssa_p (DECL_STRUCT_FUNCTION (cs->caller->symbol.decl)))
4628 compute_inline_parameters (cs->caller, true);
4629 BITMAP_FREE (recomputed_callers);
4631 return true;
4634 /* Convert all callers of NODE to pass parameters as given in ADJUSTMENTS. */
4636 static void
4637 convert_callers (struct cgraph_node *node, tree old_decl,
4638 ipa_parm_adjustment_vec adjustments)
4640 tree old_cur_fndecl = current_function_decl;
4641 basic_block this_block;
4643 cgraph_for_node_and_aliases (node, convert_callers_for_node,
4644 adjustments, false);
4646 current_function_decl = old_cur_fndecl;
4648 if (!encountered_recursive_call)
4649 return;
4651 FOR_EACH_BB (this_block)
4653 gimple_stmt_iterator gsi;
4655 for (gsi = gsi_start_bb (this_block); !gsi_end_p (gsi); gsi_next (&gsi))
4657 gimple stmt = gsi_stmt (gsi);
4658 tree call_fndecl;
4659 if (gimple_code (stmt) != GIMPLE_CALL)
4660 continue;
4661 call_fndecl = gimple_call_fndecl (stmt);
4662 if (call_fndecl == old_decl)
4664 if (dump_file)
4665 fprintf (dump_file, "Adjusting recursive call");
4666 gimple_call_set_fndecl (stmt, node->symbol.decl);
4667 ipa_modify_call_arguments (NULL, stmt, adjustments);
4672 return;
4675 /* Perform all the modification required in IPA-SRA for NODE to have parameters
4676 as given in ADJUSTMENTS. Return true iff the CFG has been changed. */
4678 static bool
4679 modify_function (struct cgraph_node *node, ipa_parm_adjustment_vec adjustments)
4681 struct cgraph_node *new_node;
4682 bool cfg_changed;
4683 VEC (cgraph_edge_p, heap) * redirect_callers = collect_callers_of_node (node);
4685 rebuild_cgraph_edges ();
4686 free_dominance_info (CDI_DOMINATORS);
4687 pop_cfun ();
4688 current_function_decl = NULL_TREE;
4690 new_node = cgraph_function_versioning (node, redirect_callers, NULL, NULL,
4691 false, NULL, NULL, "isra");
4692 current_function_decl = new_node->symbol.decl;
4693 push_cfun (DECL_STRUCT_FUNCTION (new_node->symbol.decl));
4695 ipa_modify_formal_parameters (current_function_decl, adjustments, "ISRA");
4696 cfg_changed = ipa_sra_modify_function_body (adjustments);
4697 sra_ipa_reset_debug_stmts (adjustments);
4698 convert_callers (new_node, node->symbol.decl, adjustments);
4699 cgraph_make_node_local (new_node);
4700 return cfg_changed;
4703 /* Return false the function is apparently unsuitable for IPA-SRA based on it's
4704 attributes, return true otherwise. NODE is the cgraph node of the current
4705 function. */
4707 static bool
4708 ipa_sra_preliminary_function_checks (struct cgraph_node *node)
4710 if (!cgraph_node_can_be_local_p (node))
4712 if (dump_file)
4713 fprintf (dump_file, "Function not local to this compilation unit.\n");
4714 return false;
4717 if (!node->local.can_change_signature)
4719 if (dump_file)
4720 fprintf (dump_file, "Function can not change signature.\n");
4721 return false;
4724 if (!tree_versionable_function_p (node->symbol.decl))
4726 if (dump_file)
4727 fprintf (dump_file, "Function is not versionable.\n");
4728 return false;
4731 if (DECL_VIRTUAL_P (current_function_decl))
4733 if (dump_file)
4734 fprintf (dump_file, "Function is a virtual method.\n");
4735 return false;
4738 if ((DECL_COMDAT (node->symbol.decl) || DECL_EXTERNAL (node->symbol.decl))
4739 && inline_summary(node)->size >= MAX_INLINE_INSNS_AUTO)
4741 if (dump_file)
4742 fprintf (dump_file, "Function too big to be made truly local.\n");
4743 return false;
4746 if (!node->callers)
4748 if (dump_file)
4749 fprintf (dump_file,
4750 "Function has no callers in this compilation unit.\n");
4751 return false;
4754 if (cfun->stdarg)
4756 if (dump_file)
4757 fprintf (dump_file, "Function uses stdarg. \n");
4758 return false;
4761 if (TYPE_ATTRIBUTES (TREE_TYPE (node->symbol.decl)))
4762 return false;
4764 return true;
4767 /* Perform early interprocedural SRA. */
4769 static unsigned int
4770 ipa_early_sra (void)
4772 struct cgraph_node *node = cgraph_get_node (current_function_decl);
4773 ipa_parm_adjustment_vec adjustments;
4774 int ret = 0;
4776 if (!ipa_sra_preliminary_function_checks (node))
4777 return 0;
4779 sra_initialize ();
4780 sra_mode = SRA_MODE_EARLY_IPA;
4782 if (!find_param_candidates ())
4784 if (dump_file)
4785 fprintf (dump_file, "Function has no IPA-SRA candidates.\n");
4786 goto simple_out;
4789 if (cgraph_for_node_and_aliases (node, not_all_callers_have_enough_arguments_p,
4790 NULL, true))
4792 if (dump_file)
4793 fprintf (dump_file, "There are callers with insufficient number of "
4794 "arguments.\n");
4795 goto simple_out;
4798 bb_dereferences = XCNEWVEC (HOST_WIDE_INT,
4799 func_param_count
4800 * last_basic_block_for_function (cfun));
4801 final_bbs = BITMAP_ALLOC (NULL);
4803 scan_function ();
4804 if (encountered_apply_args)
4806 if (dump_file)
4807 fprintf (dump_file, "Function calls __builtin_apply_args().\n");
4808 goto out;
4811 if (encountered_unchangable_recursive_call)
4813 if (dump_file)
4814 fprintf (dump_file, "Function calls itself with insufficient "
4815 "number of arguments.\n");
4816 goto out;
4819 adjustments = analyze_all_param_acesses ();
4820 if (!adjustments)
4821 goto out;
4822 if (dump_file)
4823 ipa_dump_param_adjustments (dump_file, adjustments, current_function_decl);
4825 if (modify_function (node, adjustments))
4826 ret = TODO_update_ssa | TODO_cleanup_cfg;
4827 else
4828 ret = TODO_update_ssa;
4829 VEC_free (ipa_parm_adjustment_t, heap, adjustments);
4831 statistics_counter_event (cfun, "Unused parameters deleted",
4832 sra_stats.deleted_unused_parameters);
4833 statistics_counter_event (cfun, "Scalar parameters converted to by-value",
4834 sra_stats.scalar_by_ref_to_by_val);
4835 statistics_counter_event (cfun, "Aggregate parameters broken up",
4836 sra_stats.aggregate_params_reduced);
4837 statistics_counter_event (cfun, "Aggregate parameter components created",
4838 sra_stats.param_reductions_created);
4840 out:
4841 BITMAP_FREE (final_bbs);
4842 free (bb_dereferences);
4843 simple_out:
4844 sra_deinitialize ();
4845 return ret;
4848 /* Return if early ipa sra shall be performed. */
4849 static bool
4850 ipa_early_sra_gate (void)
4852 return flag_ipa_sra && dbg_cnt (eipa_sra);
4855 struct gimple_opt_pass pass_early_ipa_sra =
4858 GIMPLE_PASS,
4859 "eipa_sra", /* name */
4860 ipa_early_sra_gate, /* gate */
4861 ipa_early_sra, /* execute */
4862 NULL, /* sub */
4863 NULL, /* next */
4864 0, /* static_pass_number */
4865 TV_IPA_SRA, /* tv_id */
4866 0, /* properties_required */
4867 0, /* properties_provided */
4868 0, /* properties_destroyed */
4869 0, /* todo_flags_start */
4870 TODO_dump_symtab /* todo_flags_finish */